Пример #1
0
 public ValidationMessages changeParentProfile(
     Integer profileId, String parentName, String userName) {
   ValidationMessages messages = ValidationMessages.create();
   RulesProfile profile = getSession().getEntity(RulesProfile.class, profileId);
   if (profile != null && !profile.getProvided()) {
     RulesProfile oldParent = getParentProfile(profile);
     RulesProfile newParent = getProfile(profile.getLanguage(), parentName);
     if (isCycle(profile, newParent)) {
       messages.addWarningText("Please do not select a child profile as parent.");
       return messages;
     }
     // Deactivate all inherited rules
     if (oldParent != null) {
       for (ActiveRule activeRule : oldParent.getActiveRules()) {
         deactivate(profile, activeRule.getRule(), userName);
       }
     }
     // Activate all inherited rules
     if (newParent != null) {
       for (ActiveRule activeRule : newParent.getActiveRules()) {
         activateOrChange(profile, activeRule, userName);
       }
     }
     profile.setParentName(newParent == null ? null : newParent.getName());
     getSession().saveWithoutFlush(profile);
     getSession().commit();
   }
   return messages;
 }
Пример #2
0
  private ValidationMessages restoreXmlModel(String xml, @Nullable final String languageKey) {
    checkPermission();

    ValidationMessages validationMessages = ValidationMessages.create();
    Date updateDate = new Date(system2.now());
    DbSession session = dbClient.openSession(false);
    try {
      List<CharacteristicDto> allCharacteristicDtos =
          restoreCharacteristics(characteristicsXMLImporter.importXML(xml), updateDate, session);
      restoreRules(
          allCharacteristicDtos,
          rules(languageKey, session),
          rulesXMLImporter.importXML(xml, validationMessages),
          validationMessages,
          updateDate,
          session);

      session.commit();
    } catch (IllegalArgumentException e) {
      LOG.debug("Error when restoring the model", e);
      validationMessages.addErrorText(e.getMessage());
    } finally {
      MyBatis.closeQuietly(session);
    }
    return validationMessages;
  }
  @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;
  }
Пример #4
0
 private static void checkProfile(RulesProfile profile, ValidationMessages messages) {
   if (StringUtils.isBlank(profile.getName())) {
     messages.addErrorText("The mandatory node <name> is missing.");
   }
   if (StringUtils.isBlank(profile.getLanguage())) {
     messages.addErrorText("The mandatory node <language> is missing.");
   }
 }
Пример #5
0
 @Test
 public void shouldCreateProfile() {
   ProfileDefinition sonarWay =
       new SonarWayProfile(new XMLProfileParser(newRuleFinder(), mock(MetricFinder.class)));
   ValidationMessages validation = ValidationMessages.create();
   RulesProfile profile = sonarWay.createProfile(validation);
   assertThat(profile.getActiveRulesByRepository(CheckstyleConstants.REPOSITORY_KEY).size())
       .isEqualTo(32);
   assertThat(validation.hasErrors()).isFalse();
 }
Пример #6
0
  @Test
  public void should_create_sonar_way_profile() {
    ValidationMessages validation = ValidationMessages.create();

    RuleFinder ruleFinder = ruleFinder();
    XmlSonarWayProfile definition = new XmlSonarWayProfile(new AnnotationProfileParser(ruleFinder));
    RulesProfile profile = definition.createProfile(validation);

    assertThat(profile.getLanguage()).isEqualTo(Xml.KEY);
    assertThat(profile.getName()).isEqualTo(RulesProfile.SONAR_WAY_NAME);
    assertThat(profile.getActiveRulesByRepository(CheckRepository.REPOSITORY_KEY)).hasSize(4);
    assertThat(validation.hasErrors()).isFalse();
  }
Пример #7
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());
          }
        }
      }
    }
  }
  @Test
  public void shouldCreateDefaultProfile() {
    ValidationMessages validation = ValidationMessages.create();

    RuleFinder ruleFinder = ruleFinder();
    CxxDefaultProfile definition =
        new CxxDefaultProfile(
            new XMLProfileParser(ruleFinder), new AnnotationProfileParser(ruleFinder));
    RulesProfile profile = definition.createProfile(validation);

    assertThat(profile.getLanguage()).isEqualTo(CxxLanguage.KEY);
    assertThat(profile.getActiveRulesByRepository("valgrind")).hasSize(15);
    assertThat(validation.hasErrors()).isFalse();
  }
  /** {@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;
  }
Пример #10
0
  public RulesProfile parse(Reader reader, ValidationMessages messages) {
    RulesProfile profile = RulesProfile.create();
    SMInputFactory inputFactory = initStax();
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <profile>
      SMInputCursor cursor = rootC.childElementCursor();
      while (cursor.getNext() != null) {
        String nodeName = cursor.getLocalName();
        if (StringUtils.equals("rules", nodeName)) {
          SMInputCursor rulesCursor = cursor.childElementCursor("rule");
          processRules(rulesCursor, profile, messages);

        } else if (StringUtils.equals("name", nodeName)) {
          profile.setName(StringUtils.trim(cursor.collectDescendantText(false)));

        } else if (StringUtils.equals("language", nodeName)) {
          profile.setLanguage(StringUtils.trim(cursor.collectDescendantText(false)));
        }
      }
    } catch (XMLStreamException e) {
      messages.addErrorText("XML is not valid: " + e.getMessage());
    }
    checkProfile(profile, messages);
    return profile;
  }
Пример #11
0
  private void restoreRules(
      List<CharacteristicDto> allCharacteristicDtos,
      List<RuleDto> rules,
      List<RuleDebt> ruleDebts,
      ValidationMessages validationMessages,
      Date updateDate,
      DbSession session) {
    for (RuleDto rule : rules) {
      RuleDebt ruleDebt = ruleDebt(rule.getRepositoryKey(), rule.getRuleKey(), ruleDebts);
      String subCharacteristicKey = ruleDebt != null ? ruleDebt.subCharacteristicKey() : null;
      CharacteristicDto subCharacteristicDto =
          subCharacteristicKey != null
              ? characteristicByKey(ruleDebt.subCharacteristicKey(), allCharacteristicDtos, true)
              : null;
      ruleOperations.updateRule(
          rule,
          subCharacteristicDto,
          ruleDebt != null ? ruleDebt.function() : null,
          ruleDebt != null ? ruleDebt.coefficient() : null,
          ruleDebt != null ? ruleDebt.offset() : null,
          session);
      rule.setUpdatedAt(updateDate);
      ruleDebts.remove(ruleDebt);
    }

    for (RuleDebt ruleDebt : ruleDebts) {
      validationMessages.addWarningText(
          String.format("The rule '%s' does not exist.", ruleDebt.ruleKey()));
    }
  }
Пример #12
0
 public ValidationMessages restoreProfile(String xmlBackup) {
   ValidationMessages messages = ValidationMessages.create();
   RulesProfile profile = xmlProfileParser.parse(new StringReader(xmlBackup), messages);
   if (profile != null) {
     DatabaseSession session = sessionFactory.getSession();
     RulesProfile existingProfile =
         session.getSingleResult(
             RulesProfile.class, "name", profile.getName(), "language", profile.getLanguage());
     if (existingProfile != null) {
       messages.addErrorText(
           "The profile " + profile + " already exists. Please delete it before restoring.");
     } else if (!messages.hasErrors()) {
       session.saveWithoutFlush(profile);
       session.commit();
     }
   }
   return messages;
 }
  @Test
  public void testImportingProfileWithXPathRule() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/export_xpath_rules.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertThat(profile.getActiveRules().size(), is(0));
    assertThat(messages.hasWarnings(), is(true));
  }
  @Test
  public void testImportingUnknownRules() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml"));
    importer = new PhpmdProfileImporter(mock(RuleFinder.class), new PmdRulePriorityMapper());
    RulesProfile profile = importer.importProfile(reader, messages);

    assertThat(profile.getActiveRules().size(), is(0));
    assertThat(messages.getWarnings().size(), is(3));
  }
  @Test
  public void idPropertyShouldBeTheRuleKey() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent(
                "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/idPropertyShouldBeTheRuleKey.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertNull(profile.getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage"));
    assertThat(messages.getWarnings().size()).isEqualTo(1);
  }
Пример #16
0
 /** Important : the ruby controller has already create the profile */
 public ValidationMessages importProfile(
     String profileName, String language, String importerKey, String profileDefinition) {
   ValidationMessages messages = ValidationMessages.create();
   ProfileImporter importer = getProfileImporter(importerKey);
   RulesProfile profile = importer.importProfile(new StringReader(profileDefinition), messages);
   if (!messages.hasErrors()) {
     DatabaseSession session = sessionFactory.getSession();
     RulesProfile persistedProfile =
         session.getSingleResult(RulesProfile.class, "name", profileName, "language", language);
     for (ActiveRule activeRule : profile.getActiveRules()) {
       ActiveRule persistedActiveRule =
           persistedProfile.activateRule(activeRule.getRule(), activeRule.getSeverity());
       for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
         persistedActiveRule.setParameter(activeRuleParam.getKey(), activeRuleParam.getValue());
       }
     }
     session.saveWithoutFlush(persistedProfile);
     session.commit();
   }
   return messages;
 }
  @Test
  public void testImportingRulesetWithEntireUnusedCodeRuleset() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent(
                "/org/sonar/plugins/php/pmd/entire-unusedcode-ruleset.xml"));
    importer = new PhpmdProfileImporter(createRuleFinder(), new PmdRulePriorityMapper());
    RulesProfile profile = importer.importProfile(reader, messages);

    assertThat(messages.getWarnings().size(), is(0));
    assertThat(profile.getActiveRules().size(), is(4));
  }
  @Before
  public void before() {
    messages = ValidationMessages.create();

    /*
     * The mocked rule finder defines 3 rules :
     *
     * - JavadocCheck with 2 paramters format and ignore, default priority is MAJOR
     * - EqualsHashCodeCheck without parameters, default priority is BLOCKER
     * - MissingOverride with 1 parameter javaFiveCompatibility, default priority is MINOR
     */
    importer = new CheckstyleProfileImporter(newRuleFinder());
  }
  @Test
  public void importSimpleProfile() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent(
                "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/simple.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertThat(profile.getActiveRules().size()).isEqualTo(2);
    assertNotNull(
        profile.getActiveRuleByConfigKey("checkstyle", "Checker/TreeWalker/EqualsHashCode"));
    assertNotNull(profile.getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage"));
    assertThat(messages.hasErrors()).isFalse();
  }
  @Test
  public void importingFiltersIsNotSupported() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent(
                "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/importingFiltersIsNotSupported.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertNull(profile.getActiveRuleByConfigKey("checkstyle", "Checker/SuppressionCommentFilter"));
    assertNull(
        profile.getActiveRuleByConfigKey("checkstyle", "Checker/TreeWalker/FileContentsHolder"));
    assertThat(profile.getActiveRules().size()).isEqualTo(2);
    assertThat(messages.getWarnings().size()).isEqualTo(4); // no warning for FileContentsHolder
  }
  @Test
  public void testUnsupportedProperty() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    ActiveRule check =
        profile.getActiveRuleByConfigKey(
            REPOSITORY_KEY, "rulesets/codesize.xml/CyclomaticComplexity");
    // The mock rulefinder contains only one param for the rule, but the ruleset file contains 2, so
    // we should get a warning about that.
    assertThat(check.getParameter("threshold"), nullValue());
    assertThat(messages.getWarnings().size(), is(1));
  }
  @Test
  public void testImportingSimpleProfile() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertThat(profile.getActiveRules().size(), is(3));
    assertNotNull(
        profile.getActiveRuleByConfigKey(
            REPOSITORY_KEY, "rulesets/codesize.xml/CyclomaticComplexity"));
    assertNotNull(
        profile.getActiveRuleByConfigKey(REPOSITORY_KEY, "rulesets/codesize.xml/NPathComplexity"));
    assertThat(messages.hasErrors(), is(false));
  }
Пример #23
0
  @Test
  public void testCreateProfileValidationMessages() {
    ServerFileSystem fileSystem = mock(ServerFileSystem.class);
    PhpCodeSnifferRuleRepository repository =
        new PhpCodeSnifferRuleRepository(fileSystem, new XMLRuleParser(), new Settings());
    List<Rule> rules = repository.createRules();
    RuleFinder ruleFinder = new MockPhpCodeSnifferRuleFinder(rules);

    XMLProfileParser parser = new XMLProfileParser(ruleFinder);
    SonarWayProfile profile = new SonarWayProfile(parser);
    ValidationMessages messages = ValidationMessages.create();
    RulesProfile rulesProfile = profile.createProfile(messages);
    assertNotNull(rulesProfile);
    assertEquals("Sonar Way", rulesProfile.getName());
  }
  @Test
  public void shouldUseTheIdPropertyToFindRule() {
    Reader reader =
        new StringReader(
            TestUtils.getResourceContent(
                "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/shouldUseTheIdPropertyToFindRule.xml"));
    RulesProfile profile = importer.importProfile(reader, messages);

    assertNotNull(profile.getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage"));
    assertThat(
            profile
                .getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage")
                .getRule()
                .getKey())
        .isEqualTo("com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck_12345");
    assertThat(messages.getWarnings().size()).isEqualTo(0);
  }
 @Before
 public void before() {
   messages = ValidationMessages.create();
   RuleFinder finder = createRuleFinder();
   importer = new PhpmdProfileImporter(finder, new PmdRulePriorityMapper());
 }
Пример #26
0
 /**
  * @param messages
  * @param e
  * @return
  */
 protected final PmdRuleset emptyRuleSetAndLogMessages(ValidationMessages messages, Exception e) {
   String errorMessage = "The PMD configuration file is not valid";
   messages.addErrorText(errorMessage + " : " + e.getMessage());
   LOG.error(errorMessage, e);
   return new PmdRuleset();
 }
 @Test
 public void testUnvalidXML() {
   Reader reader = new StringReader("not xml");
   importer.importProfile(reader, messages);
   assertThat(messages.getErrors().size()).isEqualTo(1);
 }