@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());
  }
Пример #2
0
  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;
  }
  @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 void loadFromCommonRepository(RulesProfile profile) {
    Rule duplicatedBlocksRule =
        ruleFinder.findByKey("common-" + JavaScriptLanguage.KEY, "DuplicatedBlocks");

    // in SonarLint duplicatedBlocksRule == null
    if (duplicatedBlocksRule != null) {
      profile.activateRule(duplicatedBlocksRule, null);
    }
  }
Пример #5
0
  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());
          }
        }
      }
    }
  }
Пример #6
0
 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;
 }
Пример #7
0
  /** 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));
  }
Пример #8
0
 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;
 }
  @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);
  }
  @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")));
  }
 @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);
   }
 }
Пример #13
0
 protected Rule findRule(VerifierMessageBase base) {
   return ruleFinder.findByKey(
       DroolsRuleRepository.REPOSITORY_KEY, "DROOLS_" + base.getMessageType());
 }
Пример #14
0
 /**
  * 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);
   }
 }