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; }
/** Rule was deactivated in parent profile. */ public void deactivated(int parentProfileId, int deactivatedRuleId, String userName) { ActiveRule parentActiveRule = getSession().getEntity(ActiveRule.class, deactivatedRuleId); RulesProfile profile = getSession().getEntity(RulesProfile.class, parentProfileId); ruleDisabled(profile, parentActiveRule, userName); for (RulesProfile child : getChildren(parentProfileId)) { deactivate(child, parentActiveRule.getRule(), userName); } getSession().commit(); }
/** * Get the active rules of a specific repository. Only enabled rules are selected. Disabled rules * are excluded. */ public List<ActiveRule> getActiveRulesByRepository(String repositoryKey) { List<ActiveRule> result = new ArrayList<>(); for (ActiveRule activeRule : activeRules) { if (repositoryKey.equals(activeRule.getRepositoryKey()) && activeRule.isEnabled()) { result.add(activeRule); } } return result; }
private void appendRuleParameters(ActiveRule activeRule, Writer writer) throws IOException { if (activeRule.getActiveRuleParams() != null && !activeRule.getActiveRuleParams().isEmpty()) { writer.append("<parameters>"); for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) { appendRuleParameter(writer, activeRuleParam); } writer.append("</parameters>"); } }
/** * Note: disabled rules are excluded. * * @return the list of active rules for a given severity */ public List<ActiveRule> getActiveRules(RulePriority severity) { List<ActiveRule> result = new ArrayList<>(); for (ActiveRule activeRule : activeRules) { if (activeRule.getSeverity().equals(severity) && activeRule.isEnabled()) { result.add(activeRule); } } return result; }
@Test public void testImportingDefaultPriority() { Reader reader = new StringReader( TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule activeRule = profile.getActiveRuleByConfigKey(REPOSITORY_KEY, "rulesets/codesize.xml/NPathComplexity"); assertThat(activeRule.getSeverity(), is(RulePriority.MAJOR)); // reuse the rule default priority }
/** Note: disabled rules are excluded. */ @CheckForNull public ActiveRule getActiveRuleByConfigKey(String repositoryKey, String configKey) { for (ActiveRule activeRule : activeRules) { if (StringUtils.equals(activeRule.getRepositoryKey(), repositoryKey) && StringUtils.equals(activeRule.getConfigKey(), configKey) && activeRule.isEnabled()) { return activeRule; } } return null; }
/** Rule was activated/changed in parent profile. */ private void activatedOrChanged(int parentProfileId, int activeRuleId, String userName) { ActiveRule parentActiveRule = getSession().getEntity(ActiveRule.class, activeRuleId); if (parentActiveRule.isInherited()) { parentActiveRule.setInheritance(ActiveRule.OVERRIDES); getSession().saveWithoutFlush(parentActiveRule); } for (RulesProfile child : getChildren(parentProfileId)) { activateOrChange(child, parentActiveRule, userName); } getSession().commit(); }
/** @return the list of active rules */ public List<ActiveRule> getActiveRules(boolean acceptDisabledRules) { if (acceptDisabledRules) { return activeRules; } List<ActiveRule> result = new ArrayList<>(); for (ActiveRule activeRule : activeRules) { if (activeRule.isEnabled()) { result.add(activeRule); } } return result; }
@Test public void importPriorities() { Reader reader = new StringReader( TestUtils.getResourceContent( "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/simple.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule javadocCheck = profile.getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage"); assertThat(javadocCheck.getSeverity()).isEqualTo(RulePriority.BLOCKER); }
@Test public void priorityIsOptional() { Reader reader = new StringReader( TestUtils.getResourceContent( "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/simple.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule activeRule = profile.getActiveRuleByConfigKey("checkstyle", "Checker/TreeWalker/EqualsHashCode"); assertThat(activeRule.getSeverity()) .isEqualTo(RulePriority.BLOCKER); // reuse the rule default priority }
@Test public void properties_should_be_inherited() { Reader reader = new StringReader( TestUtils.getResourceContent( "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/inheritance_of_properties.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule activeRule = profile.getActiveRuleByConfigKey("checkstyle", "Checker/TreeWalker/MissingOverride"); assertThat(activeRule.getSeverity()).isEqualTo(RulePriority.BLOCKER); assertThat(activeRule.getParameter("javaFiveCompatibility")).isEqualTo("true"); }
@Test public void testImportingParameters() { Reader reader = new StringReader( TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule activeRule = profile.getActiveRuleByConfigKey( REPOSITORY_KEY, "rulesets/codesize.xml/CyclomaticComplexity"); assertThat(activeRule.getActiveRuleParams().size(), is(1)); assertThat(activeRule.getParameter("reportLevel"), is("30")); }
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()); } } } } }
private void activateOrChange( RulesProfile profile, ActiveRule parentActiveRule, String userName) { ActiveRule oldActiveRule = profile.getActiveRule(parentActiveRule.getRule()); if (oldActiveRule != null) { if (oldActiveRule.isInherited()) { removeActiveRule(profile, oldActiveRule); } else { oldActiveRule.setInheritance(ActiveRule.OVERRIDES); getSession().saveWithoutFlush(oldActiveRule); return; // no need to change in children } } ActiveRule newActiveRule = (ActiveRule) parentActiveRule.clone(); newActiveRule.setRulesProfile(profile); newActiveRule.setInheritance(ActiveRule.INHERITED); profile.addActiveRule(newActiveRule); getSession().saveWithoutFlush(newActiveRule); if (oldActiveRule != null) { ruleChanged(profile, oldActiveRule, newActiveRule, userName); } else { ruleEnabled(profile, newActiveRule, userName); } for (RulesProfile child : getChildren(profile)) { activateOrChange(child, newActiveRule, userName); } }
private void appendRule(ActiveRule activeRule, Writer writer) throws IOException { writer.append("<rule><repositoryKey>"); writer.append(activeRule.getRepositoryKey()); writer.append("</repositoryKey><key>"); StringEscapeUtils.escapeXml(writer, activeRule.getRuleKey()); writer.append("</key>"); if (activeRule.getSeverity() != null) { writer.append("<priority>"); writer.append(activeRule.getSeverity().name()); writer.append("</priority>"); } appendRuleParameters(activeRule, writer); writer.append("</rule>"); }
/** Rule severity was changed */ public void ruleSeverityChanged( int profileId, int activeRuleId, RulePriority oldSeverity, RulePriority newSeverity, String userName) { ActiveRule activeRule = getSession().getEntity(ActiveRule.class, activeRuleId); RulesProfile profile = getSession().getEntity(RulesProfile.class, profileId); ruleSeverityChanged(profile, activeRule.getRule(), oldSeverity, newSeverity, userName); // Notify child profiles activatedOrChanged(profileId, activeRuleId, userName); }
/** Deal with creation of ActiveRuleChange item when a rule is disabled on a profile */ private void ruleDisabled(RulesProfile profile, ActiveRule disabledRule, String userName) { incrementProfileVersionIfNeeded(profile); ActiveRuleChange rc = new ActiveRuleChange(userName, profile, disabledRule.getRule()); rc.setEnabled(false); rc.setOldSeverity(disabledRule.getSeverity()); if (disabledRule.getRule().getParams() != null) { for (RuleParam p : disabledRule.getRule().getParams()) { String oldParam = disabledRule.getParameter(p.getKey()); if (oldParam != null) { rc.setParameterChange(p.getKey(), oldParam, null); } } } getSession().saveWithoutFlush(rc); }
/** Rule param was changed */ public void ruleParamChanged( int profileId, int activeRuleId, String paramKey, String oldValue, String newValue, String userName) { ActiveRule activeRule = getSession().getEntity(ActiveRule.class, activeRuleId); RulesProfile profile = getSession().getEntity(RulesProfile.class, profileId); ruleParamChanged(profile, activeRule.getRule(), paramKey, oldValue, newValue, userName); // Notify child profiles activatedOrChanged(profileId, activeRuleId, userName); }
private LintProfile createLintProfile(List<ActiveRule> activeRules) { LintProfile profile = new LintProfile(); Map<String, RulePriority> activeKeys = new HashMap<>(); List<LintIssue> issues = Lists.newArrayList(); for (ActiveRule rule : activeRules) { activeKeys.put(rule.getRuleKey(), rule.getSeverity()); } for (String ruleKey : ruleKeys) { issues.add(getLintIssue(ruleKey, activeKeys)); } // ensure order of issues in output, sort by key. Collections.sort(issues, new IssueComparator()); profile.issues = issues; return profile; }
@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)); }
/** Deal with creation of ActiveRuleChange item when a rule is enabled on a profile */ private void ruleEnabled(RulesProfile profile, ActiveRule newActiveRule, String userName) { incrementProfileVersionIfNeeded(profile); ActiveRuleChange rc = new ActiveRuleChange(userName, profile, newActiveRule.getRule()); rc.setEnabled(true); rc.setNewSeverity(newActiveRule.getSeverity()); if (newActiveRule.getRule().getParams() != null) { for (RuleParam p : newActiveRule.getRule().getParams()) { String newParam = newActiveRule.getParameter(p.getKey()); if (newParam != null) { rc.setParameterChange(p.getKey(), null, newParam); } } } getSession().saveWithoutFlush(rc); }
@Test public void importParameters() { Reader reader = new StringReader( TestUtils.getResourceContent( "/org/sonar/plugins/checkstyle/CheckstyleProfileImporterTest/simple.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule javadocCheck = profile.getActiveRuleByConfigKey("checkstyle", "Checker/JavadocPackage"); assertThat(javadocCheck.getActiveRuleParams()).hasSize(2); assertThat(javadocCheck.getParameter("format")).isEqualTo("abcde"); assertThat(javadocCheck.getParameter("ignore")).isEqualTo("true"); assertThat(javadocCheck.getParameter("severity")).isNull(); // checkstyle internal parameter }
protected Object createCheck(ActiveRule activeRule) { Class clazz = checkClassesByKey.get(activeRule.getConfigKey()); if (clazz != null) { return instantiate(activeRule, clazz); } return null; }
@Test public void testImportingPriority() { Reader reader = new StringReader( TestUtils.getResourceContent("/org/sonar/plugins/php/pmd/simple-ruleset.xml")); RulesProfile profile = importer.importProfile(reader, messages); ActiveRule activeRule = profile.getActiveRuleByConfigKey( REPOSITORY_KEY, "rulesets/codesize.xml/CyclomaticComplexity"); assertThat(activeRule.getSeverity(), is(RulePriority.MINOR)); activeRule = profile.getActiveRuleByConfigKey( REPOSITORY_KEY, "rulesets/codesize.xml/ExcessiveMethodLength"); assertThat(activeRule.getSeverity(), is(RulePriority.CRITICAL)); }
private void deactivate(RulesProfile profile, Rule rule, String userName) { ActiveRule activeRule = profile.getActiveRule(rule); if (activeRule != null) { if (activeRule.isInherited()) { ruleDisabled(profile, activeRule, userName); removeActiveRule(profile, activeRule); } else { activeRule.setInheritance(null); getSession().saveWithoutFlush(activeRule); return; // no need to change in children } for (RulesProfile child : getChildren(profile)) { deactivate(child, rule, userName); } } }
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; }
private void processProperties(SMInputCursor ruleCursor, ActiveRule activeRule) throws XMLStreamException { SMInputCursor propertyCursor = ruleCursor.childElementCursor(PROPERTY_NODE); while (propertyCursor.getNext() != null) { String key = propertyCursor.getAttrValue(PROPERTY_NAME_ATTR); String value = propertyCursor.getAttrValue(PROPERTY_VALUE_ATTR); activeRule.setParameter(key, value); } }
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; }
/** * Matches to something like: (ATOM:ATOM/NUMBER)(WHITESPACES)(SOMETHING NOT * WHITESPACES)(:WHITESPACES)(NUMBER,NUMBER-NUMBER,NUMBER) like: game:start/0 * /home/dev/project/erlang/game.erl: 4,1-5,12 means: 'application name':'function name'/'number * of parameters' 'URL to the file': 'starting row','starting col'-'ending row','ending col' */ public ViolationReport refactorErl(Project project, RulesProfile profile) { ViolationReport report = new ViolationReport(); List<ActiveRule> activeRules = profile.getActiveRulesByRepository("Erlang"); /** Read refactorErl results */ File basedir = new File( project.getFileSystem().getBasedir() + File.separator + ((Erlang) project.getLanguage()).getEunitFolder()); LOG.debug("Parsing refactorErl reports from folder {}", basedir.getAbsolutePath()); String refactorErlPattern = ((Erlang) project.getLanguage()).getRefactorErlFilenamePattern(); String[] list = getFileNamesByPattern(basedir, refactorErlPattern); if (list.length == 0) { LOG.warn("no file matches to : ", refactorErlPattern); return report; } for (String file : list) { try { List<ViolationReportUnit> units = readRefactorErlReportUnits(basedir, file); for (ViolationReportUnit refactorErlReportUnit : units) { ActiveRule activeRule = ActiveRuleFilter.getActiveRuleByRuleName( activeRules, refactorErlReportUnit.getMetricKey()); if (activeRule != null && ViolationUtil.checkIsValid(activeRule, refactorErlReportUnit.getMetricValue())) { refactorErlReportUnit.setDescription( ViolationUtil.getMessageForMetric( activeRule, refactorErlReportUnit.getMetricValue())); /** Replace key coming from activeProfile because it contains the name originaly */ refactorErlReportUnit.setMetricKey(activeRule.getRuleKey()); report.addUnit(refactorErlReportUnit); } } } catch (FileNotFoundException e) { } catch (IOException e) { } } return report; }