/** * Print rule details * * @param rule */ private static void dumpRule(final Rule rule, final PrintStream out) { out.println("Rule: " + rule.getName()); out.println("Priority: " + rule.getPriority()); final Map<PropertyDescriptor<?>, Object> properties = rule.getPropertiesByPropertyDescriptor(); final Set<Entry<PropertyDescriptor<?>, Object>> keys = properties.entrySet(); for (final Entry<PropertyDescriptor<?>, Object> entry : keys) { out.println(" " + entry.getKey().name() + " = " + entry.getValue()); } }
private static Set<Language> getApplicableLanguages( PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<Language>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Language language = rule.getLanguage(); if (languages.contains(language)) continue; LanguageVersion version = discoverer.getDefaultLanguageVersion(language); if (RuleSet.applies(rule, version)) { languages.add(language); } } return languages; }
public void testPluginname() throws Throwable { Rule rule = new XPathRule(); rule.addProperty("xpath", "//VariableDeclaratorId[string-length(@Image) < 3]"); rule.setMessage("{0}"); rule.addProperty("pluginname", "true"); PMD p = new PMD(); RuleContext ctx = new RuleContext(); Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFilename("n/a"); RuleSet rules = new RuleSet(); rules.addRule(rule); p.processFile(new StringReader(TEST1), rules, ctx); RuleViolation rv = (RuleViolation) report.iterator().next(); assertEquals("a", rv.getDescription()); }
private MarkerInfo2 getMarkerInfo(RuleViolation violation, String type) throws PropertiesException { Rule rule = violation.getRule(); MarkerInfo2 info = new MarkerInfo2(type, 7); info.add(IMarker.MESSAGE, violation.getDescription()); info.add(IMarker.LINE_NUMBER, violation.getBeginLine()); info.add(PMDRuntimeConstants.KEY_MARKERATT_LINE2, violation.getEndLine()); info.add(PMDRuntimeConstants.KEY_MARKERATT_RULENAME, rule.getName()); info.add(PMDRuntimeConstants.KEY_MARKERATT_PRIORITY, rule.getPriority().getPriority()); switch (rule.getPriority().getPriority()) { case 1: info.add(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); info.add( IMarker.SEVERITY, projectProperties.violationsAsErrors() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING); break; case 2: if (projectProperties.violationsAsErrors()) { info.add(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); } else { info.add(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); info.add(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); } break; case 5: info.add(IMarker.SEVERITY, IMarker.SEVERITY_INFO); break; case 3: info.add(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); case 4: default: info.add(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); break; } return info; }
@Override public int compareTo(RuleDuration other) { if (other.time < time) { return -1; } else if (other.time > time) { return 1; } return rule.getName().compareTo(other.rule.getName()); }
/** * Test if 2 sets of rules are equals * * @param ruleSet1 * @param ruleSet2 * @return */ public static boolean assertRuleSetEquals( final Collection<Rule> ruleSet1, final Collection<Rule> ruleSet2, final PrintStream out) { boolean equals = true; for (final Iterator<Rule> i = ruleSet1.iterator(); i.hasNext() && equals; ) { final Rule rule = i.next(); if (!searchRule(rule, ruleSet2, out)) { equals = false; System.out.println("Rule " + rule.getName() + " is not in the second ruleset"); } } for (final Iterator<Rule> i = ruleSet2.iterator(); i.hasNext() && equals; ) { final Rule rule = i.next(); if (!searchRule(rule, ruleSet1, out)) { equals = false; System.out.println("Rule " + rule.getName() + " is not in the first ruleset"); } } return equals; }
/** * @param languageVersion LanguageVersion * @param ruleSet RuleSet * @param dataSources List<DataSource> * @param results Set<RuleDuration> * @param debug boolean * @throws PMDException * @throws IOException */ private static void stress( LanguageVersion languageVersion, RuleSet ruleSet, List<DataSource> dataSources, Set<RuleDuration> results, boolean debug) throws PMDException, IOException { for (Rule rule : ruleSet.getRules()) { if (debug) { System.out.println("Starting " + rule.getName()); } RuleSet working = new RuleSet(); working.addRule(rule); RuleSets ruleSets = new RuleSets(working); PMDConfiguration config = new PMDConfiguration(); config.setDefaultLanguageVersion(languageVersion); RuleContext ctx = new RuleContext(); long start = System.currentTimeMillis(); Reader reader = null; for (DataSource dataSource : dataSources) { reader = new InputStreamReader(dataSource.getInputStream()); ctx.setSourceCodeFilename(dataSource.getNiceFileName(false, null)); new SourceCodeProcessor(config).processSourceCode(reader, ruleSets, ctx); IOUtil.closeQuietly(reader); } long end = System.currentTimeMillis(); long elapsed = end - start; results.add(new RuleDuration(elapsed, rule)); if (debug) { System.out.println("Done timing " + rule.getName() + "; elapsed time was " + elapsed); } } }
@Test public void should_ignore_violation_on_unknown_rule() { when(projectFileSystem.getTestDirs()).thenReturn(Arrays.asList(new File("/test"))); when(pmdViolation.getFilename()).thenReturn("/test/source.java"); when(pmdViolation.getRule()).thenReturn(rule); when(rule.getName()).thenReturn("UNKNOWN"); when(context.getResource(new JavaFile("[default].source"))) .thenReturn(new JavaFile("[default].source")); PmdViolationToRuleViolation pmdViolationToRuleViolation = new PmdViolationToRuleViolation(projectFileSystem, ruleFinder); Violation violation = pmdViolationToRuleViolation.toViolation(pmdViolation, context); assertThat(violation).isNull(); }
@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"))); }
/** * Search a rule in a set of rules * * @param rule * @param set * @return */ private static boolean searchRule( final Rule rule, final Collection<Rule> set, final PrintStream out) { boolean found = false; for (final Iterator<Rule> i = set.iterator(); i.hasNext() && !found; ) { final Rule r = i.next(); if (r.getClass().getName().equals(rule.getClass().getName())) { found = r.getName().equals(rule.getName()) && propertiesMatchFor(r, rule) && r.getPriority() == rule.getPriority(); if (!found && r.getName().equals(rule.getName())) { out.println("Rules " + r.getName() + " are different because:"); out.println("Priorities are different: " + (r.getPriority() != rule.getPriority())); out.println("Properties are different: " + !propertiesMatchFor(r, rule)); out.println(); out.println("Rule to search"); dumpRule(rule, out); out.println(); out.println("Rule from set"); dumpRule(r, out); out.println(); } } } return found; }
private static boolean propertiesMatchFor(final Rule ruleA, final Rule ruleB) { return ruleA .getPropertiesByPropertyDescriptor() .equals(ruleB.getPropertiesByPropertyDescriptor()); }
private void updateMarkers(IFile file, RuleContext context, boolean fTask) throws CoreException, PropertiesException { Map<IFile, Set<MarkerInfo2>> accumulator = getAccumulator(); Set<MarkerInfo2> markerSet = new HashSet<MarkerInfo2>(); List<Review> reviewsList = findReviewedViolations(file); Review review = new Review(); Iterator<RuleViolation> iter = context.getReport().iterator(); // final IPreferences preferences = PMDPlugin.getDefault().loadPreferences(); // final int maxViolationsPerFilePerRule = preferences.getMaxViolationsPerFilePerRule(); Map<Rule, Integer> violationsByRule = new HashMap<Rule, Integer>(); Rule rule = null; while (iter.hasNext()) { RuleViolation violation = iter.next(); rule = violation.getRule(); review.ruleName = rule.getName(); review.lineNumber = violation.getBeginLine(); if (reviewsList.contains(review)) { log.debug( "Ignoring violation of rule " + rule.getName() + " at line " + violation.getBeginLine() + " because of a review."); continue; } Integer count = violationsByRule.get(rule); if (count == null) { count = NumericConstants.ZERO; violationsByRule.put(rule, count); } int maxViolations = maxAllowableViolationsFor(rule); if (count.intValue() < maxViolations) { // Ryan Gustafson 02/16/2008 - Always use PMD_MARKER, as people get confused as to why PMD // problems don't always show up on Problems view like they do when you do build. // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : // PMDRuntimeConstants.PMD_MARKER)); markerSet.add(getMarkerInfo(violation, markerTypeFor(violation))); /* if (isDfaEnabled && violation.getRule().usesDFA()) { markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_DFA_MARKER)); } else { markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER)); } */ violationsByRule.put(rule, Integer.valueOf(count.intValue() + 1)); log.debug( "Adding a violation for rule " + rule.getName() + " at line " + violation.getBeginLine()); } else { log.debug( "Ignoring violation of rule " + rule.getName() + " at line " + violation.getBeginLine() + " because maximum violations has been reached for file " + file.getName()); } } if (accumulator != null) { log.debug("Adding markerSet to accumulator for file " + file.getName()); accumulator.put(file, markerSet); } }
/** * Update markers list for the specified file * * @param file the file for which markers are to be updated * @param context a PMD context * @param fTask indicate if a task marker should be created * @param accumulator a map that contains impacted file and marker informations */ private int maxAllowableViolationsFor(Rule rule) { return rule.hasDescriptor(PMDRuntimeConstants.MAX_VIOLATIONS_DESCRIPTOR) ? rule.getProperty(PMDRuntimeConstants.MAX_VIOLATIONS_DESCRIPTOR) : PMDRuntimeConstants.MAX_VIOLATIONS_DESCRIPTOR.defaultValue(); }