private RuleFinder newRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.find(any(RuleQuery.class))) .thenAnswer( new Answer<Rule>() { public Rule answer(InvocationOnMock iom) throws Throwable { 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; } }); return ruleFinder; }
private RuleFinder newRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(anyString(), anyString())) .thenAnswer( new Answer<Rule>() { public Rule answer(InvocationOnMock iom) throws Throwable { return Rule.create( (String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1]); } }); return ruleFinder; }
/** {@inheritDoc} */ @Override public RulesProfile importProfile(Reader reader, ValidationMessages messages) { RulesProfile profile = RulesProfile.create(); profile.setLanguage(CSharpConstants.LANGUAGE_KEY); try { List<StyleCopRule> styleCopConfig = StyleCopRuleParser.parse(IOUtils.toString(reader)); for (StyleCopRule styleCopRule : styleCopConfig) { if (styleCopRule.isEnabled()) { String ruleName = styleCopRule.getName(); Rule rule = ruleFinder.find(RuleQuery.create().withRepositoryKey(getKey()).withKey(ruleName)); if (rule != null) { String rawPriority = styleCopRule.getPriority(); RulePriority rulePriority = RulePriority.MINOR; if (StringUtils.isNotEmpty(rawPriority)) { rulePriority = RulePriority.valueOfString(rawPriority); } profile.activateRule(rule, rulePriority); } } } } catch (IOException e) { messages.addErrorText("Failed to read the profile to import: " + e.getMessage()); } return profile; }
@Override public RulesProfile importProfile(Reader reader, ValidationMessages messages) { SMInputFactory inputFactory = initStax(); RulesProfile profile = RulesProfile.create(); try { SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader); rootC.advance(); // <ruleset> SMInputCursor ruleCursor = rootC.childElementCursor(RULE_NODE); while (ruleCursor.getNext() != null) { String ruleKey = ruleCursor.getAttrValue(RULE_CLASS_ATTR); Rule rule = ruleFinder.findByKey(CodeNarcConstants.REPOSITORY_KEY, ruleKey); if (rule == null) { messages.addWarningText("CodeNarc rule '" + ruleKey + "' not found"); } else { ActiveRule activeRule = profile.activateRule(rule, null); processProperties(ruleCursor, activeRule); } } } catch (XMLStreamException e) { messages.addErrorText("XML is not valid: " + e.getMessage()); } return profile; }
private List<ProfileDefinition> loadFromDeprecatedRepository(RulesRepository repository) { List<ProfileDefinition> result = new ArrayList<ProfileDefinition>(); for (int index = 0; index < repository.getProvidedProfiles().size(); index++) { RulesProfile deprecated = (RulesProfile) repository.getProvidedProfiles().get(index); DefaultProfileDefinition providedProfile = DefaultProfileDefinition.create(deprecated.getName(), repository.getLanguage().getKey()); for (ActiveRule deprecatedActiveRule : deprecated.getActiveRules(true)) { String repositoryKey = deprecatedActiveRule.getRepositoryKey(); if (StringUtils.isBlank(repositoryKey)) { repositoryKey = getPluginKey(repository); } Rule rule = ruleFinder.findByKey(repositoryKey, deprecatedActiveRule.getRuleKey()); if (rule != null) { ActiveRule activeRule = providedProfile.activateRule(rule, deprecatedActiveRule.getSeverity()); for (ActiveRuleParam arp : deprecatedActiveRule.getActiveRuleParams()) { activeRule.setParameter(arp.getKey(), arp.getValue()); } } } result.add(providedProfile); } return result; }
@Test public void should_send_notification_if_issue_change() throws Exception { when(project.getAnalysisDate()).thenReturn(DateUtils.parseDate("2013-05-18")); RuleKey ruleKey = RuleKey.of("squid", "AvoidCycles"); Rule rule = new Rule("squid", "AvoidCycles"); DefaultIssue issue = new DefaultIssue() .setNew(false) .setChanged(true) .setFieldChange(mock(IssueChangeContext.class), "severity", "MINOR", "BLOCKER") .setRuleKey(ruleKey); when(issueCache.all()).thenReturn(Arrays.asList(issue)); when(ruleFinder.findByKey(ruleKey)).thenReturn(rule); SendIssueNotificationsPostJob job = new SendIssueNotificationsPostJob(issueCache, notifications, ruleFinder); job.executeOn(project, sensorContext); verify(notifications) .sendChanges( eq(issue), any(IssueChangeContext.class), eq(rule), any(Component.class), (Component) isNull()); }
private void loadFromCommonRepository(RulesProfile profile) { Rule duplicatedBlocksRule = ruleFinder.findByKey("common-" + JavaScriptLanguage.KEY, "DuplicatedBlocks"); // in SonarLint duplicatedBlocksRule == null if (duplicatedBlocksRule != null) { profile.activateRule(duplicatedBlocksRule, null); } }
private void processRules( SMInputCursor rulesCursor, RulesProfile profile, ValidationMessages messages) throws XMLStreamException { Map<String, String> parameters = new HashMap<>(); while (rulesCursor.getNext() != null) { SMInputCursor ruleCursor = rulesCursor.childElementCursor(); String repositoryKey = null; String key = null; RulePriority priority = null; parameters.clear(); while (ruleCursor.getNext() != null) { String nodeName = ruleCursor.getLocalName(); if (StringUtils.equals("repositoryKey", nodeName)) { repositoryKey = StringUtils.trim(ruleCursor.collectDescendantText(false)); } else if (StringUtils.equals("key", nodeName)) { key = StringUtils.trim(ruleCursor.collectDescendantText(false)); } else if (StringUtils.equals("priority", nodeName)) { priority = RulePriority.valueOf(StringUtils.trim(ruleCursor.collectDescendantText(false))); } else if (StringUtils.equals("parameters", nodeName)) { SMInputCursor propsCursor = ruleCursor.childElementCursor("parameter"); processParameters(propsCursor, parameters); } } Rule rule = ruleFinder.findByKey(repositoryKey, key); if (rule == null) { messages.addWarningText("Rule not found: " + ruleToString(repositoryKey, key)); } else { ActiveRule activeRule = profile.activateRule(rule, priority); for (Map.Entry<String, String> entry : parameters.entrySet()) { if (rule.getParam(entry.getKey()) == null) { messages.addWarningText( "The parameter '" + entry.getKey() + "' does not exist in the rule: " + ruleToString(repositoryKey, key)); } else { activeRule.setParameter(entry.getKey(), entry.getValue()); } } } } }
/** See https://jira.codehaus.org/browse/SONAR-3583 */ @Test public void should_support_violations_with_missing_rule_id() { Rule ruleWithoutId = Rule.create("repoKey", "ruleKey", "Rule"); Rule ruleWithId = Rule.create("repoKey", "ruleKey", "Rule"); ruleWithId.setId(123); when(ruleFinder.findByKey("repoKey", "ruleKey")).thenReturn(ruleWithId); File file = new File("org/foo/Bar.java"); Violation violation = Violation.create(ruleWithoutId, file); index.addViolation(violation); List<Violation> violations = index.getViolations(file); assertThat(violations.size(), is(1)); assertThat(violations.get(0).getRule().getId(), Matchers.is(123)); }
private ProfileDefinition loadFromDeprecatedCheckProfile(CheckProfile cp) { DefaultProfileDefinition definition = DefaultProfileDefinition.create(cp.getName(), cp.getLanguage()); for (Check check : cp.getChecks()) { RulePriority priority = null; if (check.getPriority() != null) { priority = RulePriority.fromCheckPriority(check.getPriority()); } Rule rule = ruleFinder.findByKey(check.getRepositoryKey(), check.getTemplateKey()); if (rule != null) { ActiveRule activeRule = definition.activateRule(rule, priority); for (Map.Entry<String, String> entry : check.getProperties().entrySet()) { activeRule.setParameter(entry.getKey(), entry.getValue()); } } } return definition; }
private void parseStyleCopViolationsBloc(SMInputCursor violationsCursor) throws XMLStreamException { // Cursor in on <Violations> StringBuffer configKey = new StringBuffer(); RuleQuery ruleQuery = RuleQuery.create().withRepositoryKey(StyleCopConstants.REPOSITORY_KEY); while (violationsCursor.getNext() != null) { configKey.setLength(0); configKey.append(violationsCursor.getAttrValue("RuleNamespace")); configKey.append("#"); configKey.append(violationsCursor.getAttrValue("Rule")); Rule currentRule = ruleFinder.find(ruleQuery.withConfigKey(configKey.toString())); if (currentRule != null) { createViolation(violationsCursor, currentRule); } else { LOG.warn( "Could not find the following rule in the StyleCop rule repository: " + configKey.toString()); } } }
@Test public void shouldInitRemoteIssueWithoutName() throws Exception { // Given that when(ruleFinder.findByKey(RuleKey.of("squid", "CycleBetweenPackages"))) .thenReturn(org.sonar.api.rules.Rule.create().setName(null)); RemoteIssue expectedIssue = new RemoteIssue(); expectedIssue.setProject("TEST"); expectedIssue.setType("3"); expectedIssue.setPriority("4"); expectedIssue.setSummary("Sonar Issue #ABCD"); expectedIssue.setDescription( "Issue detail:\n{quote}\nThe Cyclomatic Complexity of this method is 14 which is greater than 10 authorized.\n" + "{quote}\n\n\nCheck it on Sonar: http://my.sonar.com/issue/show/ABCD"); // Verify RemoteIssue returnedIssue = jiraIssueCreator.initRemoteIssue(sonarIssue, settings, ""); assertThat(returnedIssue.getSummary()).isEqualTo(expectedIssue.getSummary()); assertThat(returnedIssue.getDescription()).isEqualTo(expectedIssue.getDescription()); assertThat(returnedIssue).isEqualTo(expectedIssue); }
@CheckForNull private Rule findRule(RuleKey ruleKey) { // TODO remove this when manual rules when be indexed in E/S if (ruleKey.repository().equals(Rule.MANUAL_REPOSITORY_KEY)) { org.sonar.api.rules.Rule rule = ruleFinder.findByKey(ruleKey); if (rule != null) { RulePriority severity = rule.getSeverity(); return new Rule.Builder() .setKey(rule.getKey()) .setRepositoryKey(rule.getRepositoryKey()) .setName(rule.getName()) .setDescription(rule.getDescription()) .setSeverity(severity != null ? severity.name() : null) .setStatus(rule.getStatus()) .setCreatedAt(rule.getCreatedAt()) .setUpdatedAt(rule.getUpdatedAt()) .build(); } return null; } else { return rules.findByKey(ruleKey); } }
@Before public void init() throws Exception { sonarIssue = new DefaultIssue() .setKey("ABCD") .setMessage( "The Cyclomatic Complexity of this method is 14 which is greater than 10 authorized.") .setSeverity("MINOR") .setRuleKey(RuleKey.of("squid", "CycleBetweenPackages")); ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(RuleKey.of("squid", "CycleBetweenPackages"))) .thenReturn(org.sonar.api.rules.Rule.create().setName("Avoid cycle between java packages")); settings = new Settings(new PropertyDefinitions(JiraIssueCreator.class, JiraPlugin.class)); settings.setProperty(CoreProperties.SERVER_BASE_URL, "http://my.sonar.com"); settings.setProperty(JiraConstants.SERVER_URL_PROPERTY, "http://my.jira.com"); settings.setProperty(JiraConstants.USERNAME_PROPERTY, "foo"); settings.setProperty(JiraConstants.PASSWORD_PROPERTY, "bar"); settings.setProperty(JiraConstants.JIRA_PROJECT_KEY_PROPERTY, "TEST"); jiraIssueCreator = new JiraIssueCreator(ruleFinder); }
@Test public void should_convert_pmd_violation_to_sonar_violation() { when(projectFileSystem.getSourceDirs()).thenReturn(Arrays.asList(new File("/src"))); when(pmdViolation.getFilename()).thenReturn("/src/source.java"); when(pmdViolation.getBeginLine()).thenReturn(42); when(pmdViolation.getDescription()).thenReturn("Description"); when(pmdViolation.getRule()).thenReturn(rule); when(rule.getName()).thenReturn("RULE"); when(context.getResource(new JavaFile("[default].source"))) .thenReturn(new JavaFile("[default].source")); when(ruleFinder.findByKey("pmd", "RULE")).thenReturn(sonarRule); PmdViolationToRuleViolation pmdViolationToRuleViolation = new PmdViolationToRuleViolation(projectFileSystem, ruleFinder); Violation violation = pmdViolationToRuleViolation.toViolation(pmdViolation, context); assertThat(violation) .is( reflectionEqualTo( Violation.create(sonarRule, new JavaFile("[default].source")) .setLineId(42) .setMessage("Description"))); }
protected Rule findRule(VerifierMessageBase base) { return ruleFinder.findByKey( DroolsRuleRepository.REPOSITORY_KEY, "DROOLS_" + base.getMessageType()); }
@Override public ProjectReferentials load(ProjectReactor reactor, Settings settings, Languages languages) { ProjectReferentials ref = new ProjectReferentials(); String defaultName = settings.getString(ModuleQProfiles.SONAR_PROFILE_PROP); for (Language language : languages.all()) { org.sonar.batch.protocol.input.QProfile profile = null; if (StringUtils.isNotBlank(defaultName)) { profile = loadDefaultQProfile(defaultName, language.getKey()); } if (profile == null) { profile = loadQProfile(settings, language.getKey()); } if (profile != null) { ref.addQProfile(profile); } } for (QProfile qProfile : ref.qProfiles()) { ListMultimap<Integer, ActiveRuleParamDto> paramDtosByActiveRuleId = ArrayListMultimap.create(); for (ActiveRuleParamDto dto : activeRuleDao.selectParamsByProfileKey(qProfile.key())) { paramDtosByActiveRuleId.put(dto.getActiveRuleId(), dto); } for (ActiveRuleDto activeDto : activeRuleDao.selectByProfileKey(qProfile.key())) { Rule rule = ruleFinder.findById(activeDto.getRuleId()); if (rule != null) { String internalKey; Rule template = rule.getTemplate(); if (template != null) { internalKey = template.getConfigKey(); } else { internalKey = rule.getConfigKey(); } ActiveRule activeRule = new ActiveRule( rule.ruleKey().repository(), rule.ruleKey().rule(), rule.getName(), activeDto.getSeverityString(), internalKey, rule.getLanguage()); // load parameter values for (ActiveRuleParamDto paramDto : paramDtosByActiveRuleId.get(activeDto.getId())) { activeRule.params().put(paramDto.getKey(), paramDto.getValue()); } // load default values for (RuleParam param : rule.getParams()) { if (!activeRule.params().containsKey(param.getKey())) { activeRule.params().put(param.getKey(), param.getDefaultValue()); } } ref.addActiveRule(activeRule); } } } return ref; }
/** * Should use {@link org.sonar.server.rule.RuleService#getByKey(org.sonar.api.rule.RuleKey)}, but * it's not possible as IssueNotifications is still used by the batch. Can be null for removed * rules */ private Rule getNullableRuleByKey(RuleKey ruleKey) { return ruleFinder.findByKey(ruleKey); }
private void loadActiveKeysFromJsonProfile(RulesProfile rulesProfile) { for (String ruleKey : activatedRuleKeys()) { Rule rule = ruleFinder.findByKey(CheckList.REPOSITORY_KEY, ruleKey); rulesProfile.activateRule(rule, null); } }