From 77a8d7268e648712dcc2835137e93c827ea29830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 28 Jul 2020 12:07:53 +0200 Subject: [PATCH 1/6] Remove benchmarker --- .../sourceforge/pmd/benchmark/Benchmark.java | 41 --- .../pmd/benchmark/BenchmarkReport.java | 31 --- .../pmd/benchmark/BenchmarkResult.java | 47 ---- .../pmd/benchmark/Benchmarker.java | 254 ------------------ .../pmd/benchmark/RuleDuration.java | 31 --- .../pmd/benchmark/StringBuilderCR.java | 40 --- .../sourceforge/pmd/benchmark/TextReport.java | 159 ----------- 7 files changed, 603 deletions(-) delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmark.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkReport.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkResult.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/RuleDuration.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/StringBuilderCR.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TextReport.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmark.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmark.java deleted file mode 100644 index 7cf422214a..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmark.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -/** - * Represents an execution phase for benchmarking purposes. - * - * @author Brian Remedios - */ -@Deprecated -public enum Benchmark { - // The constants must be sorted in execution order, - // the index is derived from the ordinal of the constant - Rule(null), - RuleChainRule(null), - CollectFiles("Collect files"), - LoadRules("Load rules"), - Parser("Parser"), - QualifiedNameResolution("Qualified name resolution"), - SymbolTable("Symbol table"), - DFA("DFA"), - TypeResolution("Type resolution"), - RuleChainVisit("RuleChain visit"), - Multifile("Multifile analysis"), - Reporting("Reporting"), - RuleTotal("Rule total"), - RuleChainTotal("Rule chain rule total"), - MeasuredTotal("Measured total"), - NonMeasuredTotal("Non-measured total"), - TotalPMD("Total PMD"); - - public final int index = ordinal(); - public final String name; - - - Benchmark(String theName) { - name = theName; - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkReport.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkReport.java deleted file mode 100644 index c0cdb123b0..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkReport.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -import java.io.PrintStream; -import java.util.Map; -import java.util.Set; - -/** - * - * @author Brian Remedios - */ -@Deprecated -public interface BenchmarkReport { - - /** - * - * @param stressResults the durations from the stress test run - * @param stream the report is written into this stream - */ - void generate(Set stressResults, PrintStream stream); - - /** - * - * @param benchmarksByName - * @param stream the report is written into this stream - */ - void generate(Map benchmarksByName, PrintStream stream); -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkResult.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkResult.java deleted file mode 100644 index 5f929eda3f..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/BenchmarkResult.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -@Deprecated -class BenchmarkResult implements Comparable { - - public final Benchmark type; - public final String name; - private long time; - private long count; - - BenchmarkResult(Benchmark type, String name) { - this.type = type; - this.name = name; - } - - BenchmarkResult(Benchmark type, long time, long count) { - this(type, type.name); - this.time = time; - this.count = count; - } - - public long getTime() { - return time; - } - - public long getCount() { - return count; - } - - public void update(long time, long count) { - this.time += time; - this.count += count; - } - - @Override - public int compareTo(BenchmarkResult benchmarkResult) { - int cmp = Integer.compare(type.index, benchmarkResult.type.index); - if (cmp == 0) { - cmp = Long.compare(this.time, benchmarkResult.time); - } - return cmp; - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java deleted file mode 100644 index 42baa667b6..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java +++ /dev/null @@ -1,254 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.commons.lang3.StringUtils; - -import net.sourceforge.pmd.PMD; -import net.sourceforge.pmd.PMDConfiguration; -import net.sourceforge.pmd.PMDException; -import net.sourceforge.pmd.Rule; -import net.sourceforge.pmd.RuleContext; -import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; -import net.sourceforge.pmd.RuleSetNotFoundException; -import net.sourceforge.pmd.RuleSets; -import net.sourceforge.pmd.RulesetsFactoryUtils; -import net.sourceforge.pmd.SourceCodeProcessor; -import net.sourceforge.pmd.lang.Language; -import net.sourceforge.pmd.lang.LanguageFilenameFilter; -import net.sourceforge.pmd.lang.LanguageRegistry; -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.Parser; -import net.sourceforge.pmd.util.FileUtil; -import net.sourceforge.pmd.util.datasource.DataSource; - -/** - * @deprecated use {@link TimeTracker} instead - */ -@Deprecated -public final class Benchmarker { - - private static final Map BENCHMARKS_BY_NAME = new HashMap<>(); - - private Benchmarker() { } - - /** - * @param args - * String[] - * @param name - * String - * @return boolean - */ - private static boolean findBooleanSwitch(String[] args, String name) { - for (int i = 0; i < args.length; i++) { - if (args[i].equals(name)) { - return true; - } - } - return false; - } - - /** - * - * @param args - * String[] - * @param name - * String - * @param defaultValue - * String - * @return String - */ - private static String findOptionalStringValue(String[] args, String name, String defaultValue) { - for (int i = 0; i < args.length; i++) { - if (args[i].equals(name)) { - return args[i + 1]; - } - } - return defaultValue; - } - - /** - * - * @param args - * String[] - * @throws RuleSetNotFoundException - * @throws IOException - * @throws PMDException - */ - public static void main(String[] args) throws RuleSetNotFoundException, IOException, PMDException { - - String targetjdk = findOptionalStringValue(args, "--targetjdk", "1.4"); - Language language = LanguageRegistry.getLanguage("Java"); - LanguageVersion languageVersion = language.getVersion(targetjdk); - if (languageVersion == null) { - languageVersion = language.getDefaultVersion(); - } - - String srcDir = findOptionalStringValue(args, "--source-directory", "/usr/local/java/src/java/lang/"); - List dataSources = FileUtil.collectFiles(srcDir, new LanguageFilenameFilter(language)); - - boolean debug = findBooleanSwitch(args, "--debug"); - boolean parseOnly = findBooleanSwitch(args, "--parse-only"); - - if (debug) { - System.out.println("Using " + language.getName() + " " + languageVersion.getVersion()); - } - if (parseOnly) { - Parser parser = PMD.parserFor(languageVersion, null); - parseStress(parser, dataSources, debug); - } else { - String ruleset = findOptionalStringValue(args, "--ruleset", ""); - if (debug) { - System.out.println("Checking directory " + srcDir); - } - Set results = new TreeSet<>(); - RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); - if (StringUtils.isNotBlank(ruleset)) { - stress(languageVersion, factory.createRuleSet(ruleset), dataSources, results, debug); - } else { - Iterator i = factory.getRegisteredRuleSets(); - while (i.hasNext()) { - stress(languageVersion, i.next(), dataSources, results, debug); - } - } - - TextReport report = new TextReport(); - report.generate(results, System.err); - } - } - - /** - * @param parser - * Parser - * @param dataSources - * List - * @param debug - * boolean - * @throws IOException - */ - private static void parseStress(Parser parser, List dataSources, boolean debug) throws IOException { - - long start = System.currentTimeMillis(); - - for (DataSource ds : dataSources) { - try (DataSource dataSource = ds; InputStreamReader reader = new InputStreamReader(dataSource.getInputStream())) { - parser.parse(dataSource.getNiceFileName(false, null), reader); - } - } - - if (debug) { - long end = System.currentTimeMillis(); - long elapsed = end - start; - System.out.println("That took " + elapsed + " ms"); - } - } - - /** - * @param languageVersion - * LanguageVersion - * @param ruleSet - * RuleSet - * @param dataSources - * List - * @param results - * Set - * @param debug - * boolean - * @throws PMDException - * @throws IOException - */ - private static void stress(LanguageVersion languageVersion, RuleSet ruleSet, List dataSources, - Set results, boolean debug) throws PMDException, IOException { - - final RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); - for (Rule rule: ruleSet.getRules()) { - if (debug) { - System.out.println("Starting " + rule.getName()); - } - - final RuleSet working = factory.createSingleRuleRuleSet(rule); - RuleSets ruleSets = new RuleSets(working); - - PMDConfiguration config = new PMDConfiguration(); - config.setDefaultLanguageVersion(languageVersion); - - RuleContext ctx = new RuleContext(); - long start = System.currentTimeMillis(); - for (DataSource ds : dataSources) { - try (DataSource dataSource = ds; InputStream stream = new BufferedInputStream(dataSource.getInputStream())) { - ctx.setSourceCodeFile(new File(dataSource.getNiceFileName(false, null))); - new SourceCodeProcessor(config).processSourceCode(stream, ruleSets, ctx); - } - } - 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); - } - } - } - - /** - * @param type - * Benchmark - * @param time - * long - * @param count - * long - */ - public static void mark(Benchmark type, long time, long count) { - mark(type, null, time, count); - } - - /** - * - * @param type - * Benchmark - * @param name - * String - * @param time - * long - * @param count - * long - */ - public static synchronized void mark(Benchmark type, String name, long time, long count) { - String typeName = type.name; - if (typeName != null && name != null) { - throw new IllegalArgumentException("Name cannot be given for type: " + type); - } else if (typeName == null && name == null) { - throw new IllegalArgumentException("Name is required for type: " + type); - } else if (typeName == null) { - typeName = name; - } - BenchmarkResult benchmarkResult = BENCHMARKS_BY_NAME.get(typeName); - if (benchmarkResult == null) { - benchmarkResult = new BenchmarkResult(type, typeName); - BENCHMARKS_BY_NAME.put(typeName, benchmarkResult); - } - benchmarkResult.update(time, count); - } - - public static void reset() { - BENCHMARKS_BY_NAME.clear(); - } - - public static Map values() { - return BENCHMARKS_BY_NAME; - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/RuleDuration.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/RuleDuration.java deleted file mode 100644 index 35e2e6affa..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/RuleDuration.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -import net.sourceforge.pmd.Rule; - -@Deprecated -public class RuleDuration implements Comparable { - - public Rule rule; - public long time; - - public RuleDuration(long elapsed, Rule rule) { - this.rule = rule; - this.time = elapsed; - } - - @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()); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/StringBuilderCR.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/StringBuilderCR.java deleted file mode 100644 index 36cab0443e..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/StringBuilderCR.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -/** - * A wrapped StringBuilder that appends a variable number of text segments - * efficiently and always appends the specified carriage return terminator. - * - * @author Brian Remedios - */ -@Deprecated -public class StringBuilderCR { - - private final String cr; - private final StringBuilder sb = new StringBuilder(); - - public StringBuilderCR(String theCR) { - cr = theCR; - } - - public StringBuilderCR(String initialText, String theCR) { - this(theCR); - appendLn(initialText); - } - - public void appendLn(String... chunks) { - - for (String chunk : chunks) { - sb.append(chunk); - } - sb.append(cr); - } - - @Override - public String toString() { - return sb.toString(); - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TextReport.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TextReport.java deleted file mode 100644 index 2488106790..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TextReport.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.benchmark; - -import java.io.PrintStream; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -import net.sourceforge.pmd.PMD; - -/** - * - * - */ -@Deprecated -public class TextReport implements BenchmarkReport { - - private static final int TIME_COLUMN = 48; - private static final int NAME_COLUMN_WIDTH = 50; - private static final int VALUE_COLUMN_WIDTH = 8; - - @Override - public void generate(Set stressResults, PrintStream stream) { - - stream.println("========================================================="); - stream.println("Rule\t\t\t\t\t\tTime in ms"); - stream.println("========================================================="); - - for (RuleDuration result : stressResults) { - StringBuilder buffer = new StringBuilder(result.rule.getName()); - while (buffer.length() < TIME_COLUMN) { - buffer.append(' '); - } - buffer.append(result.time); - stream.println(stream.toString()); - } - - stream.println("========================================================="); - } - - public void report(Map benchmarksByName) { - generate(benchmarksByName, System.out); - } - - @Override - public void generate(Map benchmarksByName, PrintStream stream) { - - List results = new ArrayList<>(benchmarksByName.values()); - - long[] totalTime = new long[Benchmark.TotalPMD.index + 1]; - long[] totalCount = new long[Benchmark.TotalPMD.index + 1]; - - for (BenchmarkResult benchmarkResult : results) { - totalTime[benchmarkResult.type.index] += benchmarkResult.getTime(); - totalCount[benchmarkResult.type.index] += benchmarkResult.getCount(); - if (benchmarkResult.type.index < Benchmark.MeasuredTotal.index) { - totalTime[Benchmark.MeasuredTotal.index] += benchmarkResult.getTime(); - } - } - results.add(new BenchmarkResult(Benchmark.RuleTotal, totalTime[Benchmark.RuleTotal.index], 0)); - results.add(new BenchmarkResult(Benchmark.RuleChainTotal, totalTime[Benchmark.RuleChainTotal.index], 0)); - results.add(new BenchmarkResult(Benchmark.MeasuredTotal, totalTime[Benchmark.MeasuredTotal.index], 0)); - results.add(new BenchmarkResult(Benchmark.NonMeasuredTotal, - totalTime[Benchmark.TotalPMD.index] - totalTime[Benchmark.MeasuredTotal.index], 0)); - Collections.sort(results); - - StringBuilderCR buf = new StringBuilderCR(PMD.EOL); - boolean writeRuleHeader = true; - boolean writeRuleChainRuleHeader = true; - long ruleCount = 0; - long ruleChainCount = 0; - - for (BenchmarkResult benchmarkResult : results) { - StringBuilder buf2 = new StringBuilder(benchmarkResult.name); - buf2.append(':'); - while (buf2.length() <= NAME_COLUMN_WIDTH) { - buf2.append(' '); - } - String result = MessageFormat.format("{0,number,0.000}", - Double.valueOf(benchmarkResult.getTime() / 1000000000.0)); - buf2.append(StringUtils.leftPad(result, VALUE_COLUMN_WIDTH)); - if (benchmarkResult.type.index <= Benchmark.RuleChainRule.index) { - buf2.append(StringUtils - .leftPad(MessageFormat.format("{0,number,###,###,###,###,###}", benchmarkResult.getCount()), 20)); - } - switch (benchmarkResult.type) { - case Rule: - if (writeRuleHeader) { - writeRuleHeader = false; - buf.appendLn(); - buf.appendLn("---------------------------------<<< Rules >>>---------------------------------"); - buf.appendLn("Rule name Time (secs) # of Evaluations"); - buf.appendLn(); - } - ruleCount++; - break; - case RuleChainRule: - if (writeRuleChainRuleHeader) { - writeRuleChainRuleHeader = false; - buf.appendLn(); - buf.appendLn("----------------------------<<< RuleChain Rules >>>----------------------------"); - buf.appendLn("Rule name Time (secs) # of Visits"); - buf.appendLn(); - } - ruleChainCount++; - break; - case CollectFiles: - buf.appendLn(); - buf.appendLn("--------------------------------<<< Summary >>>--------------------------------"); - buf.appendLn("Segment Time (secs)"); - buf.appendLn(); - break; - case MeasuredTotal: - String s = MessageFormat.format("{0,number,###,###,###,###,###}", ruleCount); - String t = MessageFormat.format("{0,number,0.000}", - ruleCount == 0 ? 0 : total(totalTime, Benchmark.Rule, ruleCount)); - buf.appendLn("Rule Average (", s, " rules):", StringUtils.leftPad(t, 37 - s.length())); - s = MessageFormat.format("{0,number,###,###,###,###,###}", ruleChainCount); - t = MessageFormat.format("{0,number,0.000}", - ruleChainCount == 0 ? 0 : total(totalTime, Benchmark.RuleChainRule, ruleChainCount)); - buf.appendLn("RuleChain Average (", s, " rules):", StringUtils.leftPad(t, 32 - s.length())); - - buf.appendLn(); - buf.appendLn("-----------------------------<<< Final Summary >>>-----------------------------"); - buf.appendLn("Total Time (secs)"); - buf.appendLn(); - break; - default: - // Do nothing - break; - } - buf.appendLn(buf2.toString()); - } - - stream.print(buf.toString()); - } - - /** - * - * @param timeTotals - * long[] - * @param index - * Benchmark - * @param count - * long - * @return double - */ - private static double total(long[] timeTotals, Benchmark index, long count) { - return timeTotals[index.index] / 1000000000.0d / count; - } -} From 7db6f3809c07c93729a8183cf80c19a9643d0837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 28 Jul 2020 12:13:37 +0200 Subject: [PATCH 2/6] Remove violation tree --- .../main/java/net/sourceforge/pmd/Report.java | 73 +----- .../lang/dfa/report/AbstractReportNode.java | 124 ----------- .../pmd/lang/dfa/report/ClassNode.java | 28 --- .../pmd/lang/dfa/report/PackageNode.java | 29 --- .../dfa/report/ReportHTMLPrintVisitor.java | 178 --------------- .../pmd/lang/dfa/report/ReportTree.java | 209 ------------------ .../pmd/lang/dfa/report/ReportVisitor.java | 14 -- .../pmd/lang/dfa/report/ViolationNode.java | 38 ---- .../pmd/renderers/TextColorRenderer.java | 42 +++- .../net/sourceforge/pmd/AbstractRuleTest.java | 2 +- .../java/net/sourceforge/pmd/ReportTest.java | 10 +- 11 files changed, 38 insertions(+), 709 deletions(-) delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/AbstractReportNode.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/PackageNode.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportHTMLPrintVisitor.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportTree.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportVisitor.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ViolationNode.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index ca702ec471..f70506fabf 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -15,9 +15,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.commons.lang3.StringUtils; - -import net.sourceforge.pmd.lang.dfa.report.ReportTree; import net.sourceforge.pmd.renderers.AbstractAccumulatingRenderer; import net.sourceforge.pmd.util.DateTimeUtil; import net.sourceforge.pmd.util.NumericConstants; @@ -29,13 +26,6 @@ import net.sourceforge.pmd.util.NumericConstants; */ public class Report implements Iterable { - /* - * The idea is to store the violations in a tree instead of a list, to do - * better and faster sort and filter mechanism and to visualize the result - * as tree. (ide plugins). - */ - private final ReportTree violationTree = new ReportTree(); - // Note that this and the above data structure are both being maintained for // a bit private final List violations = new ArrayList<>(); @@ -177,30 +167,6 @@ public class Report implements Iterable { } - private static String keyFor(RuleViolation rv) { - - return StringUtils.isNotBlank(rv.getPackageName()) ? rv.getPackageName() + '.' + rv.getClassName() : ""; - } - - /** - * Calculate a summary of violation counts per fully classified class name. - * - * @return violations per class name - */ - public Map getCountSummary() { - Map summary = new HashMap<>(); - for (RuleViolation rv : violationTree) { - String key = keyFor(rv); - Integer o = summary.get(key); - summary.put(key, o == null ? NumericConstants.ONE : o + 1); - } - return summary; - } - - public ReportTree getViolationTree() { - return this.violationTree; - } - /** * Calculate a summary of violations per rule. * @@ -283,7 +249,6 @@ public class Report implements Iterable { public void addRuleViolation(RuleViolation violation) { int index = Collections.binarySearch(violations, violation, RuleViolationComparator.INSTANCE); violations.add(index < 0 ? -index - 1 : index, violation); - violationTree.addRuleViolation(violation); for (ThreadSafeReportListener listener : listeners) { listener.ruleViolationAdded(violation); } @@ -333,17 +298,11 @@ public class Report implements Iterable { while (ce.hasNext()) { addConfigError(ce.next()); } - Iterator v = r.iterator(); - while (v.hasNext()) { - RuleViolation violation = v.next(); + for (RuleViolation violation : r) { int index = Collections.binarySearch(violations, violation, RuleViolationComparator.INSTANCE); violations.add(index < 0 ? -index - 1 : index, violation); - violationTree.addRuleViolation(violation); - } - Iterator s = r.getSuppressedRuleViolations().iterator(); - while (s.hasNext()) { - suppressedRuleViolations.add(s.next()); } + suppressedRuleViolations.addAll(r.getSuppressedRuleViolations()); } public boolean isEmpty() { @@ -370,25 +329,6 @@ public class Report implements Iterable { return configErrors != null && !configErrors.isEmpty(); } - /** - * Checks whether no violations have been reported. - * - * @return true if no violations have been reported, - * false otherwise - */ - public boolean treeIsEmpty() { - return !violationTree.iterator().hasNext(); - } - - /** - * Returns an iteration over the reported violations. - * - * @return an iterator - */ - public Iterator treeIterator() { - return violationTree.iterator(); - } - @Override public Iterator iterator() { return violations.iterator(); @@ -412,15 +352,6 @@ public class Report implements Iterable { return configErrors == null ? Collections.emptyIterator() : configErrors.iterator(); } - /** - * The number of violations. - * - * @return number of violations. - */ - public int treeSize() { - return violationTree.size(); - } - /** * The number of violations. * diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/AbstractReportNode.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/AbstractReportNode.java deleted file mode 100644 index bcf8866405..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/AbstractReportNode.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -import java.util.ArrayList; -import java.util.List; - -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public abstract class AbstractReportNode { - private List childNodes = new ArrayList<>(); - private AbstractReportNode parentNode = null; - - /* - * Number of all RuleViolations down to this node. At the moment it will - * only be calculated by running the ReportHTMLPrintVisitor. - */ - private int numberOfViolations; - - /** - * Should compare to nodes of the tree. - */ - public abstract boolean equalsNode(AbstractReportNode arg0); - - /** - * @return null If there isn't any child. - */ - public AbstractReportNode getFirstChild() { - if (this.isLeaf()) { - return null; - } - return this.childNodes.get(0); - } - - /** - * @return null If there isn't any sibling. - */ - public AbstractReportNode getNextSibling() { - if (parentNode == null) { - return null; - } - int index = parentNode.getChildIndex(this); - if (index < 0) { - return null; - } - if (index >= parentNode.childNodes.size() - 1) { - return null; - } - return parentNode.childNodes.get(index + 1); - } - - /** - * @return index The index of the x-th child of his parent. - */ - private int getChildIndex(AbstractReportNode child) { - for (int i = 0; i < childNodes.size(); i++) { - if (childNodes.get(i).equals(child)) { - return i; - } - } - return -1; - } - - /** - * Adds the child in front of any other childs. - */ - public void addFirst(AbstractReportNode child) { - childNodes.add(0, child); - child.parentNode = this; - } - - /** - * Adds the child at the end. - */ - public void add(AbstractReportNode child) { - childNodes.add(child); - child.parentNode = this; - } - - public void addNumberOfViolation(int number) { - numberOfViolations += number; - } - - /** - * @return The number of all violations downside the node. - */ - public int getNumberOfViolations() { - return numberOfViolations; - } - - // ---------------------------------------------------------------------------- - // visitor methods - public void childrenAccept(ReportVisitor visitor) { - for (int i = 0; i < childNodes.size(); i++) { - AbstractReportNode node = childNodes.get(i); - node.accept(visitor); - } - } - - public void accept(ReportVisitor visitor) { - visitor.visit(this); - } - - public AbstractReportNode getChildAt(int arg0) { - if (arg0 >= 0 && arg0 <= childNodes.size() - 1) { - return childNodes.get(arg0); - } - return null; - } - - public int getChildCount() { - return childNodes.size(); - } - - public AbstractReportNode getParent() { - return parentNode; - } - - public boolean isLeaf() { - return childNodes.isEmpty(); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java deleted file mode 100644 index eb6ec4d588..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public class ClassNode extends AbstractReportNode { - - private String className; - - public ClassNode(String className) { - this.className = className; - } - - public String getClassName() { - return className; - } - - @Override - public boolean equalsNode(AbstractReportNode arg0) { - if (!(arg0 instanceof ClassNode)) { - return false; - } - return ((ClassNode) arg0).getClassName().equals(className); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/PackageNode.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/PackageNode.java deleted file mode 100644 index 8ba7c1ba4c..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/PackageNode.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public class PackageNode extends AbstractReportNode { - - private String packageName; - - public PackageNode(String packageName) { - this.packageName = packageName; - } - - public String getPackageName() { - return this.packageName; - } - - @Override - public boolean equalsNode(AbstractReportNode arg0) { - if (!(arg0 instanceof PackageNode)) { - return false; - } - - return ((PackageNode) arg0).getPackageName().equals(this.packageName); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportHTMLPrintVisitor.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportHTMLPrintVisitor.java deleted file mode 100644 index 682dbbc587..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportHTMLPrintVisitor.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; - -import org.apache.commons.lang3.StringUtils; - -import net.sourceforge.pmd.PMD; -import net.sourceforge.pmd.RuleViolation; - -/** - * Uses the generated result tree instead of the result list. The - * visitor traverses the tree and creates several html files. The - * "package view" file (index.html) displays an overview of packages, - * classes and the number of * rule violations they contain. All the - * other html files represent a class * and show detailed information - * about the violations. - * - * @author raik - */ -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public class ReportHTMLPrintVisitor extends ReportVisitor { - - @SuppressWarnings("PMD.AvoidStringBufferField") - private StringBuilder packageBuf = new StringBuilder(30); - @SuppressWarnings("PMD.AvoidStringBufferField") - private StringBuilder classBuf = new StringBuilder(60); - private int length; - private String baseDir; - - private static final String FILE_SEPARATOR = System.getProperty("file.separator"); - - public ReportHTMLPrintVisitor(String baseDir) { - this.baseDir = baseDir; - } - - /** - * Writes the buffer to file. - */ - private void write(String filename, StringBuilder buf) throws IOException { - try (BufferedWriter bw = Files.newBufferedWriter(new File(baseDir + FILE_SEPARATOR + filename).toPath(), - StandardCharsets.UTF_8)) { - bw.write(buf.toString(), 0, buf.length()); - } - } - - /** - * Generates a html table with violation information. - */ - private String displayRuleViolation(RuleViolation vio) { - - StringBuilder sb = new StringBuilder(200); - sb.append(""); - renderViolationRow(sb, "Rule:", vio.getRule().getName()); - renderViolationRow(sb, "Description:", vio.getDescription()); - - if (StringUtils.isNotBlank(vio.getVariableName())) { - renderViolationRow(sb, "Variable:", vio.getVariableName()); - } - - if (vio.getEndLine() > 0) { - renderViolationRow(sb, "Line:", vio.getEndLine() + " and " + vio.getBeginLine()); - } else { - renderViolationRow(sb, "Line:", Integer.toString(vio.getBeginLine())); - } - - sb.append("
"); - return sb.toString(); - } - - // TODO - join the 21st century, include CSS attributes :) - private void renderViolationRow(StringBuilder sb, String fieldName, String fieldData) { - sb.append("").append(fieldName).append("").append(fieldData).append(""); - } - - /** - * The visit method (Visitor Pattern). There are 3 types of ReportNodes: - * RuleViolation - contains a RuleViolation, Class - represents a class and - * contains the name of the class, Package - represents a package and - * contains the name(s) of the package. - */ - @Override - public void visit(AbstractReportNode node) { - - /* - * The first node of result tree. - */ - if (node.getParent() == null) { - packageBuf.insert(0, - "" + PMD.EOL - + "" + " " + PMD.EOL + " " + PMD.EOL - + " PMD" + " " + " " + PMD.EOL - + "

Package View

" - + "" + " " - + PMD.EOL + "" + "" + "" + " " + PMD.EOL); - - length = packageBuf.length(); - } - - super.visit(node); - - if (node instanceof ViolationNode) { - renderViolation((ViolationNode) node); - } - if (node instanceof ClassNode) { - renderClass((ClassNode) node); - } - if (node instanceof PackageNode) { - renderPackage((PackageNode) node); - } - - // The first node of result tree. - if (node.getParent() == null) { - packageBuf.append("
PackageClass#
"); - try { - write("index.html", packageBuf); - } catch (Exception e) { - throw new RuntimeException("Error while writing HTML report: " + e.getMessage()); - } - } - } - - private void renderViolation(ViolationNode vnode) { - - vnode.getParent().addNumberOfViolation(1); - RuleViolation vio = vnode.getRuleViolation(); - classBuf.append("" + " " + vio.getMethodName() + "" + " " + this.displayRuleViolation(vio) - + "" + ""); - } - - private void renderPackage(PackageNode pnode) { - - String str; - - // rootNode - if (pnode.getParent() == null) { - str = "Aggregate"; - } else { // all the other nodes - str = pnode.getPackageName(); - pnode.getParent().addNumberOfViolation(pnode.getNumberOfViolations()); - } - - packageBuf.insert(length, "" + str + "" + " -" + " " - + pnode.getNumberOfViolations() + "" + "" + PMD.EOL); - } - - private void renderClass(ClassNode cnode) { - - String str = cnode.getClassName(); - - classBuf.insert(0, - "" + PMD.EOL - + "PMD - " + str + "" + PMD.EOL + "

Class View

" - + "

Class: " + str + "

" - + "" + " " + PMD.EOL - + "" + "" + " " + PMD.EOL); - - classBuf.append("
MethodViolation
" + " " + ""); - - try { - write(str + ".html", classBuf); - } catch (Exception e) { - throw new RuntimeException("Error while writing HTML report: " + e.getMessage()); - } - classBuf = new StringBuilder(); - - packageBuf.insert(this.length, "" + " -" + " " + str + "" - + " " + cnode.getNumberOfViolations() + "" + "" + PMD.EOL); - cnode.getParent().addNumberOfViolation(cnode.getNumberOfViolations()); - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportTree.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportTree.java deleted file mode 100644 index 988a29e21d..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportTree.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -import java.util.Iterator; - -import net.sourceforge.pmd.RuleViolation; - -/** - * - * @deprecated This class will be removed with PMD 7.0.0 without replacement. - * It is very specific for Java as it tries to recreate the package hierarchy - * of the analyzed classes and put the found violations in there. - * So it is of limited use for any other language. - */ -@Deprecated // will be removed with PMD 7.0.0 without replacement -public class ReportTree implements Iterable { - - private PackageNode rootNode = new PackageNode(""); - private AbstractReportNode level; - - private class TreeIterator implements Iterator { - - private AbstractReportNode iterNode = rootNode; - private boolean hasNextFlag; - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean hasNext() { - hasNextFlag = true; - return getNext() != null; - } - - @Override - public RuleViolation next() { - if (!hasNextFlag) { - getNext(); - } else { - hasNextFlag = false; - } - - if (iterNode instanceof ViolationNode) { - return ((ViolationNode) iterNode).getRuleViolation(); - } - return null; - } - - /** - * It's some kind of left-right-middle search (postorder). It always - * returns only leafs. The first node he returns is the most left handed - * leaf he can found. Now he's looking for siblings and if there are - * any, he starts searching for the next most left handed leaf. If there - * are no siblings he goes up to his parent and starts looking for - * siblings. If there are any he starts searching for the next most left - * handed leaf again. And so on ... until he wants to get the parent of - * the root node. Because there is no one, the search stops. - */ - - private AbstractReportNode getNext() { - AbstractReportNode node; - - while (true) { - if (iterNode.isLeaf()) { - - while ((node = iterNode.getNextSibling()) == null) { - - node = iterNode.getParent(); - if (node == null) { - return null; - } else { - iterNode = node; - } - } - - iterNode = node; - if (iterNode.isLeaf()) { - return iterNode; - } else { - continue; - } - } else { - iterNode = iterNode.getFirstChild(); - if (iterNode.isLeaf()) { - return iterNode; - } else { - continue; - } - } - } - } - } - - @Override - public Iterator iterator() { - return new TreeIterator(); - } - - public int size() { - int count = 0; - for (Iterator i = iterator(); i.hasNext();) { - i.next(); - count++; - } - return count; - } - - public AbstractReportNode getRootNode() { - return rootNode; - } - - /** - * Adds the RuleViolation to the tree. Splits the package name. Each - * package, class and violation gets there own tree node. - */ - public void addRuleViolation(RuleViolation violation) { - String packageName = violation.getPackageName(); - if (packageName == null) { - packageName = ""; - } - - level = rootNode; - - int endIndex = packageName.indexOf('.'); - while (true) { - String parentPackage; - if (endIndex < 0) { - parentPackage = packageName; - } else { - parentPackage = packageName.substring(0, endIndex); - } - - if (!isStringInLevel(parentPackage)) { - PackageNode node = new PackageNode(parentPackage); - level.addFirst(node); - // gotoLevel - level = node; - } - - if (endIndex < 0) { - break; - } - endIndex = packageName.indexOf('.', endIndex + 1); - } - - String cl = violation.getClassName(); - - if (!isStringInLevel(cl)) { - ClassNode node = new ClassNode(cl); - level.addFirst(node); - // gotoLevel - level = node; - } - - /* - * Filters duplicated rule violations. Like the comparator in - * RuleViolation if he already exists. - */ - ViolationNode tmp = new ViolationNode(violation); - if (!equalsNodeInLevel(level, tmp)) { - level.add(tmp); - } - } - - /** - * Checks if node is a child of the level node. - */ - private boolean equalsNodeInLevel(AbstractReportNode level, AbstractReportNode node) { - for (int i = 0; i < level.getChildCount(); i++) { - if (level.getChildAt(i).equalsNode(node)) { - return true; - } - } - return false; - } - - /** - * Checks if the packageName or the className is a child of the current - * (this.level) node. If it's true, the current node changes to the child - * node. - */ - private boolean isStringInLevel(String str) { - - for (int i = 0; i < level.getChildCount(); i++) { - final AbstractReportNode child = level.getChildAt(i); - final String tmp; - if (child instanceof PackageNode) { - tmp = ((PackageNode) child).getPackageName(); - } else if (child instanceof ClassNode) { - tmp = ((ClassNode) child).getClassName(); - } else { - return false; - } - - if (tmp != null && tmp.equals(str)) { - // goto level - level = child; - return true; - } - } - return false; - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportVisitor.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportVisitor.java deleted file mode 100644 index 0794187d13..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ReportVisitor.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public abstract class ReportVisitor { - - public void visit(AbstractReportNode node) { - node.childrenAccept(this); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ViolationNode.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ViolationNode.java deleted file mode 100644 index 4b0c7cb683..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ViolationNode.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -import net.sourceforge.pmd.RuleViolation; - -@Deprecated // will be removed with PMD 7.0.0 without replacement. See net.sourceforge.pmd.lang.dfa.report.ReportTree for details. -public class ViolationNode extends AbstractReportNode { - - private RuleViolation ruleViolation; - - public ViolationNode(RuleViolation violation) { - this.ruleViolation = violation; - } - - public RuleViolation getRuleViolation() { - return ruleViolation; - } - - @Override - public boolean equalsNode(AbstractReportNode arg0) { - if (!(arg0 instanceof ViolationNode)) { - return false; - } - - RuleViolation rv = ((ViolationNode) arg0).getRuleViolation(); - - return rv.getFilename().equals(getRuleViolation().getFilename()) - && rv.getBeginLine() == getRuleViolation().getBeginLine() - && rv.getBeginColumn() == getRuleViolation().getBeginColumn() - && rv.getEndLine() == getRuleViolation().getEndLine() - && rv.getEndColumn() == getRuleViolation().getEndColumn() - && rv.getVariableName().equals(getRuleViolation().getVariableName()); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java index 198d38cb6c..4dd4667070 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java @@ -11,14 +11,18 @@ import java.io.IOException; import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Files; +import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import org.apache.commons.lang3.StringUtils; + import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; +import net.sourceforge.pmd.util.NumericConstants; /** *

@@ -145,8 +149,7 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { } writer.write(PMD.EOL + PMD.EOL); writer.write("Summary:" + PMD.EOL + PMD.EOL); - Map summary = report.getCountSummary(); - for (Map.Entry entry : summary.entrySet()) { + for (Map.Entry entry : getCountSummary(report).entrySet()) { buf.setLength(0); String key = entry.getKey(); buf.append(key).append(" : ").append(entry.getValue()).append(PMD.EOL); @@ -181,19 +184,42 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { // adding error message count, if any if (numberOfErrors > 0) { writer.write(this.redBold + "*" + this.colorReset + " errors: " + this.whiteBold + numberOfErrors - + this.colorReset + PMD.EOL); + + this.colorReset + PMD.EOL); } writer.write(this.yellowBold + "*" + this.colorReset + " warnings: " + this.whiteBold + numberOfWarnings - + this.colorReset + PMD.EOL); + + this.colorReset + PMD.EOL); } + + /** + * Calculate a summary of violation counts per fully classified class name. + * + * @return violations per class name + */ + private static Map getCountSummary(Report report) { + Map summary = new HashMap<>(); + for (RuleViolation rv : report) { + String key = keyFor(rv); + if (key.isEmpty()) { + continue; + } + Integer o = summary.get(key); + summary.put(key, o == null ? NumericConstants.ONE : o + 1); + } + return summary; + } + + private static String keyFor(RuleViolation rv) { + return StringUtils.isNotBlank(rv.getPackageName()) ? rv.getPackageName() + '.' + rv.getClassName() : ""; + } + + /** * Retrieves the requested line from the specified file. * - * @param sourceFile - * the java or cpp source file - * @param line - * line number to extract + * @param sourceFile the java or cpp source file + * @param line line number to extract + * * @return a trimmed line of source code */ private String getLine(String sourceFile, int line) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java index bbd5c18dd3..5ee922610d 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java @@ -112,7 +112,7 @@ public class AbstractRuleTest { s.setCoords(5, 1, 6, 1); s.setImage("TestImage"); r.addViolation(ctx, s); - RuleViolation rv = ctx.getReport().getViolationTree().iterator().next(); + RuleViolation rv = ctx.getReport().iterator().next(); assertEquals("Message foo 10 ${noSuchProperty}", rv.getDescription()); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java index 446c98543f..2e22ab84e9 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java @@ -106,7 +106,7 @@ public class ReportTest implements ThreadSafeReportListener { } @Test - public void testTreeIterator() { + public void testIterator() { Report r = new Report(); RuleContext ctx = new RuleContext(); Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); @@ -122,14 +122,6 @@ public class ReportTest implements ThreadSafeReportListener { violationCount++; } assertEquals(2, violationCount); - - Iterator treeIterator = r.treeIterator(); - int treeCount = 0; - while (treeIterator.hasNext()) { - treeIterator.next(); - treeCount++; - } - assertEquals(2, treeCount); } private static Node getNode(int line, int column) { From 942493051eb3deb429b7c4a755807b5a366f2bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 28 Jul 2020 12:31:59 +0200 Subject: [PATCH 3/6] Remove some utils --- .../pmd/lang/rule/AbstractDelegateRule.java | 6 - .../pmd/lang/rule/RuleReference.java | 36 --- .../properties/AbstractPropertySource.java | 36 --- .../pmd/properties/MethodMultiProperty.java | 149 ---------- .../pmd/properties/MethodProperty.java | 120 -------- .../pmd/properties/PropertySource.java | 34 --- .../pmd/properties/PropertyTypeId.java | 5 +- .../pmd/properties/TypeMultiProperty.java | 127 -------- .../pmd/properties/TypeProperty.java | 111 ------- .../pmd/properties/ValueParserConstants.java | 137 --------- .../modules/MethodPropertyModule.java | 113 ------- .../net/sourceforge/pmd/util/ClassUtil.java | 185 ------------ .../sourceforge/pmd/util/CollectionUtil.java | 280 +----------------- .../net/sourceforge/pmd/util/StringUtil.java | 14 +- .../net/sourceforge/pmd/util/TypeMap.java | 170 ----------- .../pmd/properties/MethodPropertyTest.java | 160 ---------- .../pmd/properties/TypePropertyTest.java | 79 ----- .../net/sourceforge/pmd/util/TypeMapTest.java | 84 ------ .../rule/bestpractices/LooseCouplingRule.java | 18 +- .../UseCollectionIsEmptyRule.java | 5 +- 20 files changed, 24 insertions(+), 1845 deletions(-) delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodMultiProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeMultiProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/MethodPropertyModule.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/ClassUtil.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/TypeMap.java delete mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/properties/MethodPropertyTest.java delete mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/properties/TypePropertyTest.java delete mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/util/TypeMapTest.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractDelegateRule.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractDelegateRule.java index 5244eb6b6c..f34e442045 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractDelegateRule.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractDelegateRule.java @@ -6,7 +6,6 @@ package net.sourceforge.pmd.lang.rule; import java.util.List; import java.util.Map; -import java.util.Set; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; @@ -93,11 +92,6 @@ public abstract class AbstractDelegateRule implements Rule { return rule.dysfunctionReason(); } - @Override - public Set> ignoredProperties() { - return rule.ignoredProperties(); - } - @Override public String getName() { return rule.getName(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/RuleReference.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/RuleReference.java index e3086542b3..29dec60d4c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/RuleReference.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/RuleReference.java @@ -349,42 +349,6 @@ public class RuleReference extends AbstractDelegateRule { return propertyValues != null && propertyValues.containsKey(descriptor); } - @Override - @Deprecated - public boolean usesDefaultValues() { - - List> descriptors = getOverriddenPropertyDescriptors(); - if (!descriptors.isEmpty()) { - return false; - } - - for (PropertyDescriptor desc : descriptors) { - if (!Objects.equals(desc.defaultValue(), getProperty(desc))) { - return false; - } - } - - return getRule().usesDefaultValues(); - } - - @Override - @Deprecated - public void useDefaultValueFor(PropertyDescriptor desc) { - - // not sure if we should go all the way through to the real thing? - getRule().useDefaultValueFor(desc); - - if (propertyValues == null) { - return; - } - - propertyValues.remove(desc); - - if (propertyDescriptors != null) { - propertyDescriptors.remove(desc); - } - } - @Override public Rule deepCopy() { return new RuleReference(this); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPropertySource.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPropertySource.java index 71463940cf..3d7d7a3c95 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPropertySource.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPropertySource.java @@ -10,10 +10,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import net.sourceforge.pmd.util.CollectionUtil; /** @@ -81,12 +77,6 @@ public abstract class AbstractPropertySource implements PropertySource { return new HashMap<>(propertyValuesByDescriptor); } - @Override - @Deprecated - public Set> ignoredProperties() { - return Collections.emptySet(); - } - @Override public void definePropertyDescriptor(PropertyDescriptor propertyDescriptor) { @@ -210,32 +200,6 @@ public abstract class AbstractPropertySource implements PropertySource { } - @Override - @Deprecated - public boolean usesDefaultValues() { - - Map, Object> valuesByProperty = getPropertiesByPropertyDescriptor(); - if (valuesByProperty.isEmpty()) { - return true; - } - - for (Entry, Object> entry : valuesByProperty.entrySet()) { - if (!CollectionUtil.areEqual(entry.getKey().defaultValue(), entry.getValue())) { - return false; - } - } - - return true; - } - - - @Override - @Deprecated - public void useDefaultValueFor(PropertyDescriptor desc) { - propertyValuesByDescriptor.remove(desc); - } - - // todo Java 8 move up to interface @Override public String dysfunctionReason() { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodMultiProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodMultiProperty.java deleted file mode 100644 index 8c2c3d2a6e..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodMultiProperty.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import static net.sourceforge.pmd.properties.ValueParserConstants.METHOD_PARSER; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; - -import net.sourceforge.pmd.properties.builders.MultiPackagedPropertyBuilder; -import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper; -import net.sourceforge.pmd.properties.modules.MethodPropertyModule; - - -/** - * Defines a property type that can specify multiple methods to use as part of a rule. - * - * Rule developers can limit the rules to those within designated packages per the 'legalPackages' argument in the - * constructor which can be an array of partial package names, i.e., ["java.lang", "com.mycompany" ]. - * - * @author Brian Remedios - * @version Refactored June 2017 (6.0.0) - * @deprecated Will be removed with 7.0.0 with no scheduled replacement - */ -@Deprecated -public final class MethodMultiProperty extends AbstractMultiPackagedProperty { - - - /** - * Constructor for MethodMultiProperty using an array of defaults. - * - * @param theName String - * @param theDescription String - * @param theDefaults Method[] - * @param legalPackageNames String[] - * @param theUIOrder float - */ - public MethodMultiProperty(String theName, String theDescription, Method[] theDefaults, - String[] legalPackageNames, float theUIOrder) { - this(theName, theDescription, Arrays.asList(theDefaults), legalPackageNames, theUIOrder); - } - - - /** - * Constructor for MethodProperty using a list of defaults. - * - * @param theName String - * @param theDescription String - * @param theDefaults Method[] - * @param legalPackageNames String[] - * @param theUIOrder float - * - * @throws IllegalArgumentException - */ - public MethodMultiProperty(String theName, String theDescription, List theDefaults, - String[] legalPackageNames, float theUIOrder) { - this(theName, theDescription, theDefaults, legalPackageNames, theUIOrder, false); - } - - - /** Master constructor. */ - private MethodMultiProperty(String theName, String theDescription, List theDefaults, - String[] legalPackageNames, float theUIOrder, boolean isDefinedExternally) { - super(theName, theDescription, theDefaults, theUIOrder, isDefinedExternally, - new MethodPropertyModule(legalPackageNames, theDefaults)); - } - - - /** - * Constructor for MethodProperty. - * - * @param theName String - * @param theDescription String - * @param methodDefaults String - * @param legalPackageNames String[] - * @param theUIOrder float - * - * @throws IllegalArgumentException - * @deprecated will be removed in 7.O.O - */ - public MethodMultiProperty(String theName, String theDescription, String methodDefaults, - String[] legalPackageNames, float theUIOrder) { - this(theName, theDescription, - methodsFrom(methodDefaults), - legalPackageNames, theUIOrder, - false); - } - - - @Override - public String asString(Method value) { - return MethodPropertyModule.asString(value); - } - - - @Override - protected Method createFrom(String toParse) { - return METHOD_PARSER.valueOf(toParse); - } - - - @Override - public Class type() { - return Method.class; - } - - - @Override - public List valueFrom(String valueString) throws IllegalArgumentException { - return methodsFrom(valueString); - } - - - private static List methodsFrom(String valueString) { - return ValueParserConstants.parsePrimitives(valueString, MULTI_VALUE_DELIMITER, METHOD_PARSER); - } - - - static PropertyDescriptorBuilderConversionWrapper.MultiValue.Packaged extractor() { - return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Packaged(Method.class, ValueParserConstants.METHOD_PARSER) { - @Override - protected MethodMultiPBuilder newBuilder(String name) { - return new MethodMultiPBuilder(name); - } - }; - } - - - public static MethodMultiPBuilder named(String name) { - return new MethodMultiPBuilder(name); - } - - - public static final class MethodMultiPBuilder extends MultiPackagedPropertyBuilder { - private MethodMultiPBuilder(String name) { - super(name); - } - - - @Override - public MethodMultiProperty build() { - return new MethodMultiProperty(name, description, defaultValues, legalPackageNames, uiOrder, isDefinedInXML); - } - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodProperty.java deleted file mode 100644 index f42768eedb..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/MethodProperty.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - - -import static net.sourceforge.pmd.properties.ValueParserConstants.METHOD_PARSER; - -import java.lang.reflect.Method; -import java.util.Collections; - -import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper; -import net.sourceforge.pmd.properties.builders.SinglePackagedPropertyBuilder; -import net.sourceforge.pmd.properties.modules.MethodPropertyModule; - - -/** - * Defines a property type that can specify a single method to use as part of a rule. - * - *

Rule developers can limit the rules to those within designated packages per the 'legalPackages' argument in the - * constructor which can be an array of partial package names, i.e., ["java.lang", "com.mycompany" ].

- * - * @deprecated Not useful, will be remove by 7.0.0 - * @author Brian Remedios - * @version Refactored June 2017 (6.0.0) - * @deprecated Will be removed with 7.0.0 with no scheduled replacement - */ -@Deprecated -public final class MethodProperty extends AbstractPackagedProperty { - - - /** - * Constructor for MethodProperty. - * - * @param theName Name of the property - * @param theDescription Description - * @param theDefault Default value - * @param legalPackageNames Legal packages - * @param theUIOrder UI order - */ - public MethodProperty(String theName, String theDescription, Method theDefault, String[] legalPackageNames, - float theUIOrder) { - this(theName, theDescription, theDefault, legalPackageNames, theUIOrder, false); - } - - - /** Master constructor. */ - private MethodProperty(String theName, String theDescription, Method theDefault, String[] legalPackageNames, - float theUIOrder, boolean isDefinedExternally) { - super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally, - new MethodPropertyModule(legalPackageNames, Collections.singletonList(theDefault))); - } - - - /** - * Constructor for MethodProperty using a string as a default value. - * - * @param theName Name of the property - * @param theDescription Description - * @param defaultMethodStr Default value, that will be parsed into a Method object - * @param legalPackageNames Legal packages - * @param theUIOrder UI order - * - * @deprecated will be removed in 7.0.0 - */ - public MethodProperty(String theName, String theDescription, String defaultMethodStr, String[] legalPackageNames, - float theUIOrder) { - this(theName, theDescription, METHOD_PARSER.valueOf(defaultMethodStr), - legalPackageNames, theUIOrder, false); - } - - - @Override - protected String asString(Method value) { - return MethodPropertyModule.asString(value); - } - - - @Override - public Class type() { - return Method.class; - } - - - @Override - public Method createFrom(String valueString) throws IllegalArgumentException { - return METHOD_PARSER.valueOf(valueString); - } - - - static PropertyDescriptorBuilderConversionWrapper.SingleValue.Packaged extractor() { - return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Packaged(Method.class, ValueParserConstants.METHOD_PARSER) { - @Override - protected MethodPBuilder newBuilder(String name) { - return new MethodPBuilder(name); - } - }; - } - - - public static MethodPBuilder named(String name) { - return new MethodPBuilder(name); - } - - - public static final class MethodPBuilder extends SinglePackagedPropertyBuilder { - private MethodPBuilder(String name) { - super(name); - } - - - @Override - public MethodProperty build() { - return new MethodProperty(name, description, defaultValue, legalPackageNames, uiOrder, isDefinedInXML); - } - } - - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertySource.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertySource.java index 7a516714bd..66c9251299 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertySource.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertySource.java @@ -6,7 +6,6 @@ package net.sourceforge.pmd.properties; import java.util.List; import java.util.Map; -import java.util.Set; /** @@ -154,39 +153,6 @@ public interface PropertySource { boolean hasDescriptor(PropertyDescriptor descriptor); - /** - * Returns whether this Rule uses default values for properties. - * - * @return boolean true if the properties all have default values, false otherwise. - * - * @deprecated Has no real utility, will be removed by 7.0.0 - */ - @Deprecated - boolean usesDefaultValues(); - - - /** - * Clears out any user-specified value for the property allowing it to use the default value in the descriptor. - * - * @param desc the property to clear out - * - * @deprecated Has no real utility, and the name is confusing, will be removed by 7.0.0 - */ - @Deprecated - void useDefaultValueFor(PropertyDescriptor desc); - - - /** - * Return the properties that are effectively ignored due to the configuration of the rule and values held by other - * properties. This can be used to disable corresponding widgets in a UI. - * - * @return the properties that are ignored - * @deprecated Has no real utility, will be removed by 7.0.0 - */ - @Deprecated - Set> ignoredProperties(); - - /** * Returns a description of why the receiver may be dysfunctional. * Usually due to missing property values or some kind of conflict diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java index f6984d9efa..31fc29be43 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java @@ -57,10 +57,7 @@ public enum PropertyTypeId { DOUBLE_LIST("List[Double]", DoubleMultiProperty.extractor(), ValueParserConstants.DOUBLE_PARSER), // ENUM("Enum", EnumeratedProperty.FACTORY), // TODO:cf we need new syntax in the xml to support that // ENUM_LIST("List[Enum]", EnumeratedMultiProperty.FACTORY), - @Deprecated - CLASS("Class", TypeProperty.extractor(), ValueParserConstants.CLASS_PARSER), - @Deprecated - CLASS_LIST("List[Class]", TypeMultiProperty.extractor(), ValueParserConstants.CLASS_PARSER); + ; private static final Map CONSTANTS_BY_MNEMONIC; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeMultiProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeMultiProperty.java deleted file mode 100644 index 9899e00538..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeMultiProperty.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import java.util.List; - -import net.sourceforge.pmd.properties.builders.MultiPackagedPropertyBuilder; -import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper; -import net.sourceforge.pmd.properties.modules.TypePropertyModule; - - -/** - * Defines a property that supports multiple class types, even for primitive values! - * - * TODO - untested for array types - * @deprecated Will be removed with 7.0.0 with no scheduled replacement yet - * @author Brian Remedios - */ -@Deprecated -public final class TypeMultiProperty extends AbstractMultiPackagedProperty { - - - /** - * Constructor for TypeProperty. - * - * @param theName String - * @param theDescription String - * @param theDefaults Class[] - * @param legalPackageNames String[] - * @param theUIOrder float - * - * @throws IllegalArgumentException - */ - public TypeMultiProperty(String theName, String theDescription, List theDefaults, - String[] legalPackageNames, float theUIOrder) { - this(theName, theDescription, theDefaults, legalPackageNames, theUIOrder, false); - - } - - - /** Master constructor. */ - private TypeMultiProperty(String theName, String theDescription, List theTypeDefaults, - String[] legalPackageNames, float theUIOrder, boolean isDefinedExternally) { - super(theName, theDescription, theTypeDefaults, theUIOrder, isDefinedExternally, - new TypePropertyModule(legalPackageNames, theTypeDefaults)); - } - - - /** - * Constructor for TypeProperty. - * - * @param theName String - * @param theDescription String - * @param theTypeDefaults String - * @param legalPackageNames String[] - * @param theUIOrder float - * - * @throws IllegalArgumentException - */ - public TypeMultiProperty(String theName, String theDescription, String theTypeDefaults, - String[] legalPackageNames, float theUIOrder) { - this(theName, theDescription, typesFrom(theTypeDefaults), - legalPackageNames, - theUIOrder, false); - - } - - - @Override - public Class type() { - return Class.class; - } - - - @Override - public String asString(Class value) { - return value == null ? "" : value.getName(); - } - - - @Override - protected Class createFrom(String toParse) { - return ValueParserConstants.CLASS_PARSER.valueOf(toParse); - } - - - @Override - public List valueFrom(String valueString) { - return typesFrom(valueString); - } - - - private static List typesFrom(String valueString) { - return ValueParserConstants.parsePrimitives(valueString, MULTI_VALUE_DELIMITER, ValueParserConstants.CLASS_PARSER); - } - - - public static PropertyDescriptorBuilderConversionWrapper.MultiValue.Packaged extractor() { - return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Packaged(Class.class, ValueParserConstants.CLASS_PARSER) { - @Override - protected TypeMultiPBuilder newBuilder(String name) { - return new TypeMultiPBuilder(name); - } - }; - } - - - public static TypeMultiPBuilder named(String name) { - return new TypeMultiPBuilder(name); - } - - - public static final class TypeMultiPBuilder extends MultiPackagedPropertyBuilder { - - private TypeMultiPBuilder(String name) { - super(name); - } - - - @Override - public TypeMultiProperty build() { - return new TypeMultiProperty(name, description, defaultValues, legalPackageNames, uiOrder, isDefinedInXML); - } - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeProperty.java deleted file mode 100644 index 9b6cfc1113..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/TypeProperty.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import java.util.Collections; - -import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper; -import net.sourceforge.pmd.properties.builders.SinglePackagedPropertyBuilder; -import net.sourceforge.pmd.properties.modules.TypePropertyModule; - - -/** - * Defines a property that supports single class types, even for primitive values! - * - * TODO - untested for array types - * - * @author Brian Remedios - * @deprecated Will be removed with 7.0.0 with no scheduled replacement yet - */ -@Deprecated -public final class TypeProperty extends AbstractPackagedProperty { - - /** - * Constructor for TypeProperty using a string as default value. - * - * @param theName String - * @param theDescription String - * @param defaultTypeStr String - * @param legalPackageNames String[] - * @param theUIOrder float - * - * @throws IllegalArgumentException if the default string could not be parsed into a Class - * @deprecated will be removed in 7.0.0 - */ - public TypeProperty(String theName, String theDescription, String defaultTypeStr, String[] legalPackageNames, - float theUIOrder) { - this(theName, theDescription, ValueParserConstants.CLASS_PARSER.valueOf(defaultTypeStr), legalPackageNames, theUIOrder, false); - } - - - /** Master constructor. */ - private TypeProperty(String theName, String theDescription, Class theDefault, String[] legalPackageNames, - float theUIOrder, boolean isDefinedExternally) { - super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally, - new TypePropertyModule(legalPackageNames, Collections.singletonList(theDefault))); - } - - - /** - * Constructor for TypeProperty. - * - * @param theName String - * @param theDescription String - * @param theDefault Class - * @param legalPackageNames String[] - * @param theUIOrder float - */ - public TypeProperty(String theName, String theDescription, Class theDefault, String[] legalPackageNames, - float theUIOrder) { - this(theName, theDescription, theDefault, legalPackageNames, theUIOrder, false); - } - - - @Override - public Class type() { - return Class.class; - } - - - @Override - protected String asString(Class value) { - return value == null ? "" : value.getName(); - } - - - @Override - public Class createFrom(String valueString) { - return ValueParserConstants.CLASS_PARSER.valueOf(valueString); - } - - - static PropertyDescriptorBuilderConversionWrapper.SingleValue.Packaged extractor() { - return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Packaged(Class.class, ValueParserConstants.CLASS_PARSER) { - @Override - protected TypePBuilder newBuilder(String name) { - return new TypePBuilder(name); - } - }; - } - - - public static TypePBuilder named(String name) { - return new TypePBuilder(name); - } - - - public static final class TypePBuilder extends SinglePackagedPropertyBuilder { - private TypePBuilder(String name) { - super(name); - } - - - @Override - public TypeProperty build() { - return new TypeProperty(name, description, defaultValue, legalPackageNames, uiOrder, isDefinedInXML); - } - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParserConstants.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParserConstants.java index 17b18c5db7..8884cb156a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParserConstants.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParserConstants.java @@ -4,14 +4,7 @@ package net.sourceforge.pmd.properties; -import static net.sourceforge.pmd.properties.modules.MethodPropertyModule.ARRAY_FLAG; -import static net.sourceforge.pmd.properties.modules.MethodPropertyModule.CLASS_METHOD_DELIMITER; -import static net.sourceforge.pmd.properties.modules.MethodPropertyModule.METHOD_ARG_DELIMITER; -import static net.sourceforge.pmd.properties.modules.MethodPropertyModule.METHOD_GROUP_DELIMITERS; - import java.io.File; -import java.lang.reflect.Array; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -21,7 +14,6 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.annotation.InternalApi; -import net.sourceforge.pmd.util.ClassUtil; /** @@ -37,114 +29,6 @@ import net.sourceforge.pmd.util.ClassUtil; public final class ValueParserConstants { - /** Extracts methods. */ - static final ValueParser METHOD_PARSER = new ValueParser() { - @Override - public Method valueOf(String value) throws IllegalArgumentException { - return methodFrom(value, CLASS_METHOD_DELIMITER, METHOD_ARG_DELIMITER); - } - - - /** - * Returns the method specified within the string argument after parsing out - * its source class and any optional arguments. Callers need to specify the - * delimiters expected between the various elements. I.e.: - * - *

"String#isEmpty()" "String#indexOf(int)" "String#substring(int,int)" - * - *

If a method isn't part of the specified class we will walk up any - * superclasses to Object to try and find it. - * - *

If the classes are listed in the ClassUtil class within in Typemaps then - * you likely can avoid specifying fully-qualified class names per the above - * example. - * - *

Returns null if a matching method cannot be found. - * - * @param methodNameAndArgTypes Method name (with its declaring class and arguments) - * @param classMethodDelimiter Delimiter between the class and method names - * @param methodArgDelimiter Method arguments delimiter - * - * @return Method - */ - Method methodFrom(String methodNameAndArgTypes, char classMethodDelimiter, char methodArgDelimiter) { - - // classname#methodname(arg1,arg2) - // 0 1 2 - - int delimPos0 = -1; - if (methodNameAndArgTypes != null) { - delimPos0 = methodNameAndArgTypes.indexOf(classMethodDelimiter); - } else { - return null; - } - - if (delimPos0 < 0) { - return null; - } - - String className = methodNameAndArgTypes.substring(0, delimPos0); - Class type = ClassUtil.getTypeFor(className); - if (type == null) { - return null; - } - - int delimPos1 = methodNameAndArgTypes.indexOf(METHOD_GROUP_DELIMITERS[0]); - if (delimPos1 < 0) { - String methodName = methodNameAndArgTypes.substring(delimPos0 + 1); - return ClassUtil.methodFor(type, methodName, ClassUtil.EMPTY_CLASS_ARRAY); - } - - String methodName = methodNameAndArgTypes.substring(delimPos0 + 1, delimPos1); - if (StringUtils.isBlank(methodName)) { - return null; - } // missing method name? - - int delimPos2 = methodNameAndArgTypes.indexOf(METHOD_GROUP_DELIMITERS[1]); - if (delimPos2 < 0) { - return null; - } // error! - - String argTypesStr = methodNameAndArgTypes.substring(delimPos1 + 1, delimPos2); - if (StringUtils.isBlank(argTypesStr)) { - return ClassUtil.methodFor(type, methodName, ClassUtil.EMPTY_CLASS_ARRAY); - } // no arg(s) - - String[] argTypeNames = StringUtils.split(argTypesStr, methodArgDelimiter); - Class[] argTypes = new Class[argTypeNames.length]; - for (int i = 0; i < argTypes.length; i++) { - argTypes[i] = typeFor(argTypeNames[i]); - } - - return ClassUtil.methodFor(type, methodName, argTypes); - } - - - private Class typeFor(String typeName) { - - Class type; - - if (typeName.endsWith(ARRAY_FLAG)) { - String arrayTypeName = typeName.substring(0, typeName.length() - ARRAY_FLAG.length()); - type = typeFor(arrayTypeName); // recurse - return Array.newInstance(type, 0).getClass(); // TODO is there a - // better way to get - // an array type? - } - - type = ClassUtil.getTypeFor(typeName); // try shortcut first - if (type != null) { - return type; - } - - try { - return Class.forName(typeName); - } catch (ClassNotFoundException ex) { - return null; - } - } - - }; /** Extracts characters. */ static final ValueParser CHARACTER_PARSER = new ValueParser() { @Override @@ -213,27 +97,6 @@ public final class ValueParserConstants { } }; - /** Extract classes. */ - static final ValueParser CLASS_PARSER = new ValueParser() { - @Override - public Class valueOf(String value) throws IllegalArgumentException { - if (StringUtils.isBlank(value)) { - return null; - } - - Class cls = ClassUtil.getTypeFor(value); - if (cls != null) { - return cls; - } - - try { - return Class.forName(value); - } catch (ClassNotFoundException ex) { - throw new IllegalArgumentException(value); - } - } - }; - private ValueParserConstants() { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/MethodPropertyModule.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/MethodPropertyModule.java deleted file mode 100644 index bbca8d8a02..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/MethodPropertyModule.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties.modules; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; - -import net.sourceforge.pmd.util.ClassUtil; - - -/** - * Factorises common functionality for method properties. - * - * @author Clément Fournier - */ -@Deprecated -public class MethodPropertyModule extends PackagedPropertyModule { - - public static final char CLASS_METHOD_DELIMITER = '#'; - public static final char METHOD_ARG_DELIMITER = ','; - public static final char[] METHOD_GROUP_DELIMITERS = {'(', ')'}; - public static final String ARRAY_FLAG = "[]"; - private static final Map, String> TYPE_SHORTCUTS = ClassUtil.getClassShortNames(); - - - public MethodPropertyModule(String[] legalPackageNames, List defaults) { - super(legalPackageNames, defaults); - } - - - @Override - protected String packageNameOf(Method method) { - return method.getDeclaringClass().getName() + '.' + method.getName(); - } - - - @Override - protected String itemTypeName() { - return "method"; - } - - - public static String asString(Method method) { - return method == null ? "" : asStringFor(method); - } - - - /** - * Return the value of `method' as a string that can be easily recognized and parsed when we see it again. - * - * @param method the method to convert - * - * @return the string value - */ - private static String asStringFor(Method method) { - StringBuilder sb = new StringBuilder(); - asStringOn(method, sb); - return sb.toString(); - } - - - /** - * Serializes the method signature onto the specified buffer. - * - * @param method Method - * @param sb StringBuilder - */ - private static void asStringOn(Method method, StringBuilder sb) { - - Class clazz = method.getDeclaringClass(); - - sb.append(shortestNameFor(clazz)); - sb.append(CLASS_METHOD_DELIMITER); - sb.append(method.getName()); - - sb.append(METHOD_GROUP_DELIMITERS[0]); - - Class[] argTypes = method.getParameterTypes(); - if (argTypes.length == 0) { - sb.append(METHOD_GROUP_DELIMITERS[1]); - return; - } - - serializedTypeIdOn(argTypes[0], sb); - for (int i = 1; i < argTypes.length; i++) { - sb.append(METHOD_ARG_DELIMITER); - serializedTypeIdOn(argTypes[i], sb); - } - sb.append(METHOD_GROUP_DELIMITERS[1]); - } - - - private static String shortestNameFor(Class cls) { - String compactName = TYPE_SHORTCUTS.get(cls); - return compactName == null ? cls.getName() : compactName; - } - - - private static void serializedTypeIdOn(Class type, StringBuilder sb) { - - Class arrayType = type.getComponentType(); - if (arrayType == null) { - sb.append(shortestNameFor(type)); - return; - } - sb.append(shortestNameFor(arrayType)).append(ARRAY_FLAG); - } - - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/ClassUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/ClassUtil.java deleted file mode 100644 index 3e7ea1eb37..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/ClassUtil.java +++ /dev/null @@ -1,185 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import java.lang.reflect.Method; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Various class-related utility methods intended for mapping common java.lang - * types to their short short forms allowing end users to enter these names in - * UIs without the package prefixes. - * - * @author Brian Remedios - * @deprecated Is internal API - */ -@Deprecated -public final class ClassUtil { - - public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - - @SuppressWarnings("PMD.AvoidUsingShortType") - private static final TypeMap PRIMITIVE_TYPE_NAMES = new TypeMap(new Class[] { int.class, byte.class, long.class, - short.class, float.class, double.class, char.class, boolean.class, }); - - private static final TypeMap TYPES_BY_NAME = new TypeMap( - new Class[] { Integer.class, Byte.class, Long.class, Short.class, Float.class, Double.class, - Character.class, Boolean.class, BigDecimal.class, String.class, Object.class, Class.class, }); - - private static final Map, String> SHORT_NAMES_BY_TYPE = computeClassShortNames(); - - private ClassUtil() { - } - - /** - * Returns the type(class) for the name specified or null if not found. - * - * @param name - * String - * @return Class - */ - public static Class getPrimitiveTypeFor(String name) { - return PRIMITIVE_TYPE_NAMES.typeFor(name); - } - - /** - * Return a map of all the short names of classes we maintain mappings for. - * The names are keyed by the classes themselves. - * - * @return Map - */ - private static Map, String> computeClassShortNames() { - - Map, String> map = new HashMap<>(); - map.putAll(PRIMITIVE_TYPE_NAMES.asInverseWithShortName()); - map.putAll(TYPES_BY_NAME.asInverseWithShortName()); - return map; - } - - public static Map, String> getClassShortNames() { - return SHORT_NAMES_BY_TYPE; - } - - /** - * Attempt to determine the actual class given the short name. - * - * @param shortName - * String - * @return Class - */ - public static Class getTypeFor(String shortName) { - Class type = TYPES_BY_NAME.typeFor(shortName); - if (type != null) { - return type; - } - - type = PRIMITIVE_TYPE_NAMES.typeFor(shortName); - if (type != null) { - return type; - } - - return CollectionUtil.getCollectionTypeFor(shortName); - } - - /** - * Return the name of the type in its short form if its known to us - * otherwise return its name fully packaged. - * - * @param type - * @return String - */ - public static String asShortestName(Class type) { - - String name = SHORT_NAMES_BY_TYPE.get(type); - return name == null ? type.getName() : name; - } - - /** - * Returns the abbreviated name of the type, without the package name - * - * @param fullTypeName - * @return String - */ - - public static String withoutPackageName(String fullTypeName) { - int dotPos = fullTypeName.lastIndexOf('.'); - return dotPos > 0 ? fullTypeName.substring(dotPos + 1) : fullTypeName; - } - - /** - * Attempts to return the specified method from the class provided but will - * walk up its superclasses until it finds a match. Returns null if it - * doesn't. - * - * @param clasz - * Class - * @param methodName - * String - * @param paramTypes - * Class[] - * @return Method - */ - public static Method methodFor(Class clasz, String methodName, Class[] paramTypes) { - Method method = null; - Class current = clasz; - while (current != Object.class) { - try { - method = current.getDeclaredMethod(methodName, paramTypes); - } catch (NoSuchMethodException ex) { - current = current.getSuperclass(); - } - if (method != null) { - return method; - } - } - return null; - } - - /** - * Return the methods as a map keyed by their common declaration types. - * - * @param methods - * @return methods grouped by declaring type name - */ - public static Map> asMethodGroupsByTypeName(Method[] methods) { - - Map> methodGroups = new HashMap<>(methods.length); - - for (int i = 0; i < methods.length; i++) { - String clsName = asShortestName(methods[i].getDeclaringClass()); - if (!methodGroups.containsKey(clsName)) { - methodGroups.put(clsName, new ArrayList()); - } - methodGroups.get(clsName).add(methods[i]); - } - return methodGroups; - } - - - /** - * Return the methods as a map keyed by their common declaration types. - * - * @param methods - * - * @return methods grouped by declaring type name - */ - public static Map> asMethodGroupsByTypeName(List methods) { - - Map> methodGroups = new HashMap<>(methods.size()); - - for (Method m : methods) { - String clsName = asShortestName(m.getDeclaringClass()); - if (!methodGroups.containsKey(clsName)) { - methodGroups.put(clsName, new ArrayList()); - } - methodGroups.get(clsName).add(m); - } - return methodGroups; - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java index a6c2d4c36c..82c19c936e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java @@ -8,7 +8,6 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; -import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -19,7 +18,6 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; @@ -53,55 +51,28 @@ public final class CollectionUtil { private static final int UNKNOWN_SIZE = -1; @SuppressWarnings("PMD.UnnecessaryFullyQualifiedName") - public static final TypeMap COLLECTION_INTERFACES_BY_NAMES = new TypeMap(List.class, Collection.class, Map.class, Set.class); + public static final Set COLLECTION_INTERFACES_BY_NAMES = collectionTypes(List.class, Collection.class, Map.class, Set.class); - @SuppressWarnings({"PMD.LooseCoupling", "PMD.UnnecessaryFullyQualifiedName" }) - public static final TypeMap COLLECTION_CLASSES_BY_NAMES - = new TypeMap(ArrayList.class, java.util.LinkedList.class, java.util.Vector.class, HashMap.class, - java.util.LinkedHashMap.class, java.util.TreeMap.class, java.util.TreeSet.class, - HashSet.class, java.util.LinkedHashSet.class, java.util.Hashtable.class); + @SuppressWarnings( {"PMD.LooseCoupling", "PMD.UnnecessaryFullyQualifiedName"}) + public static final Set COLLECTION_CLASSES_BY_NAMES + = collectionTypes(ArrayList.class, java.util.LinkedList.class, java.util.Vector.class, HashMap.class, + java.util.LinkedHashMap.class, java.util.TreeMap.class, java.util.TreeSet.class, + HashSet.class, java.util.LinkedHashSet.class, java.util.Hashtable.class); private CollectionUtil() { } - /** - * Add elements from the source to the target as long as they don't already - * exist there. Return the number of items actually added. - * - * @param source - * @param target - * @return int - */ - public static int addWithoutDuplicates(Collection source, Collection target) { + private static Set collectionTypes(Class... types) { + Set set = new HashSet<>(); - int added = 0; - - for (T item : source) { - if (target.contains(item)) { - continue; + for (Class type : types) { + if (!set.add(type.getSimpleName()) || !set.add(type.getName())) { + throw new IllegalArgumentException("Duplicate or name collision for " + type); } - target.add(item); - added++; } - return added; - } - - /** - * Returns the collection type if we recognize it by its short name. - * - * @param shortName - * String - * @return Class - */ - public static Class getCollectionTypeFor(String shortName) { - Class cls = COLLECTION_CLASSES_BY_NAMES.typeFor(shortName); - if (cls != null) { - return cls; - } - - return COLLECTION_INTERFACES_BY_NAMES.typeFor(shortName); + return set; } /** @@ -123,25 +94,6 @@ public final class CollectionUtil { return includeInterfaces && COLLECTION_INTERFACES_BY_NAMES.contains(typeName); } - /** - * Return whether we can identify the typeName as a java.util collection - * class or interface as specified. - * - * @param clazzType - * Class - * @param includeInterfaces - * boolean - * @return boolean - */ - public static boolean isCollectionType(Class clazzType, boolean includeInterfaces) { - - if (COLLECTION_CLASSES_BY_NAMES.contains(clazzType)) { - return true; - } - - return includeInterfaces && COLLECTION_INTERFACES_BY_NAMES.contains(clazzType); - } - /** * Returns the items as a populated set. * @@ -191,125 +143,6 @@ public final class CollectionUtil { } - /** - * Consumes all the elements of the iterator and - * returns a list containing them. The iterator is - * then unusable - * - * @param it An iterator - * - * @return a list containing the elements remaining - * on the iterator - */ - public static List toList(Iterator it) { - List list = new ArrayList<>(); - while (it.hasNext()) { - list.add(it.next()); - } - return list; - } - - /** - * Returns true if the objects are array instances and each of their - * elements compares via equals as well. - * - * @param value - * Object - * @param otherValue - * Object - * @return boolean - * @deprecated {@link Objects#deepEquals(Object, Object)} - */ - @Deprecated - public static boolean arraysAreEqual(Object value, Object otherValue) { - if (value instanceof Object[]) { - if (otherValue instanceof Object[]) { - return valuesAreTransitivelyEqual((Object[]) value, (Object[]) otherValue); - } - return false; - } - return false; - } - - /** - * Returns whether the arrays are equal by examining each of their elements, - * even if they are arrays themselves. - * - * @param thisArray - * Object[] - * @param thatArray - * Object[] - * @return boolean - * @deprecated {@link Arrays#deepEquals(Object[], Object[])} - */ - @Deprecated - public static boolean valuesAreTransitivelyEqual(Object[] thisArray, Object[] thatArray) { - if (thisArray == thatArray) { - return true; - } - if (thisArray == null || thatArray == null) { - return false; - } - if (thisArray.length != thatArray.length) { - return false; - } - for (int i = 0; i < thisArray.length; i++) { - if (!areEqual(thisArray[i], thatArray[i])) { - return false; // recurse if req'd - } - } - return true; - } - - /** - * A comprehensive isEqual method that handles nulls and arrays safely. - * - * @param value - * Object - * @param otherValue - * Object - * @return boolean - * @deprecated {@link Objects#deepEquals(Object, Object)} - */ - @Deprecated - @SuppressWarnings("PMD.CompareObjectsWithEquals") - public static boolean areEqual(Object value, Object otherValue) { - if (value == otherValue) { - return true; - } - if (value == null) { - return false; - } - if (otherValue == null) { - return false; - } - - if (value.getClass().getComponentType() != null) { - return arraysAreEqual(value, otherValue); - } - return value.equals(otherValue); - } - - /** - * Returns whether the items array is null or has zero length. - * - * @param items - * @return boolean - */ - public static boolean isEmpty(Object[] items) { - return items == null || items.length == 0; - } - - /** - * Returns whether the items array is non-null and has at least one entry. - * - * @param items - * @return boolean - */ - public static boolean isNotEmpty(Object[] items) { - return !isEmpty(items); - } - /** * Returns the set union of the given collections. * @@ -654,95 +487,6 @@ public final class CollectionUtil { : list.subList(0, n); } - /** - * Returns true if both arrays are if both are null or have zero-length, - * otherwise return the false if their respective elements are not equal by - * position. - * - * @param - * @param a - * @param b - * @return boolean - * @deprecated {@link Arrays#deepEquals(Object[], Object[])} - */ - @Deprecated - public static boolean areSemanticEquals(T[] a, T[] b) { - if (a == null) { - return b == null || b.length == 0; - } - if (b == null) { - return a.length == 0; - } - - if (a.length != b.length) { - return false; - } - - for (int i = 0; i < a.length; i++) { - if (!areEqual(a[i], b[i])) { - return false; - } - } - - return true; - } - - - /** - * If the newValue is already held within the values array then the values - * array is returned, otherwise a new array is created appending the - * newValue to the end. - * - * @param - * @param values - * @param newValue - * @return an array containing the union of values and newValue - */ - @Deprecated - public static T[] addWithoutDuplicates(T[] values, T newValue) { - - for (T value : values) { - if (value.equals(newValue)) { - return values; - } - } - - T[] largerOne = (T[]) Array.newInstance(values.getClass().getComponentType(), values.length + 1); - System.arraycopy(values, 0, largerOne, 0, values.length); - largerOne[values.length] = newValue; - return largerOne; - } - - /** - * Returns an array of values as a union set of the two input arrays. - * - * @param - * @param values - * @param newValues - * @return the union of the two arrays - */ - @Deprecated - public static T[] addWithoutDuplicates(T[] values, T[] newValues) { - - Set originals = new HashSet<>(values.length); - for (T value : values) { - originals.add(value); - } - List newOnes = new ArrayList<>(newValues.length); - for (T value : newValues) { - if (originals.contains(value)) { - continue; - } - newOnes.add(value); - } - - T[] largerOne = (T[]) Array.newInstance(values.getClass().getComponentType(), values.length + newOnes.size()); - System.arraycopy(values, 0, largerOne, 0, values.length); - for (int i = values.length; i < largerOne.length; i++) { - largerOne[i] = newOnes.get(i - values.length); - } - return largerOne; - } public static List listOfNotNull(T t) { return t == null ? emptyList() : singletonList(t); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java index 6df736ace3..95765777ba 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java @@ -562,9 +562,7 @@ public final class StringUtil { * leading characters can be removed to shift all the text in the strings to * the left without misaligning them. * - * @param strings String[] - * - * @return int + * @throws NullPointerException If the parameter is null */ public static int maxCommonLeadingWhitespaceForAll(String[] strings) { @@ -575,14 +573,12 @@ public final class StringUtil { char[] matches = new char[shortest]; - String str; for (int m = 0; m < matches.length; m++) { matches[m] = strings[0].charAt(m); if (!Character.isWhitespace(matches[m])) { return m; } - for (int i = 0; i < strings.length; i++) { - str = strings[i]; + for (String str : strings) { if (str.charAt(m) != matches[m]) { return m; } @@ -597,13 +593,11 @@ public final class StringUtil { * Return the length of the shortest string in the array. If the collection * is empty or any one of them is null then it returns 0. * - * @param strings String[] - * - * @return int + * @throws NullPointerException If the parameter is null */ public static int lengthOfShortestIn(String[] strings) { - if (CollectionUtil.isEmpty(strings)) { + if (strings.length == 0) { return 0; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/TypeMap.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/TypeMap.java deleted file mode 100644 index c1e598d710..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/TypeMap.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.sourceforge.pmd.annotation.InternalApi; - -/** - * A specialized map that stores types by both their full and short (without - * package prefixes) names. If an incoming type shares the same name (but - * different package/prefix) with a type already in the map then an - * IllegalArgumentException will be thrown since any subsequent retrievals by - * said short name could be in error. - * - * @author Brian Remedios - * @deprecated Is internal API - */ -@Deprecated -@InternalApi -public class TypeMap { - - private Map> typesByName; - - /** - * Constructor for TypeMap. - * - * @param initialSize - * int - */ - public TypeMap(int initialSize) { - typesByName = new HashMap<>(initialSize); - } - - /** - * Constructor for TypeMap that takes in an initial set of types. - * - * @param types - * Class[] - */ - public TypeMap(Class... types) { - this(types.length); - add(types); - } - - /** - * Adds a type to the receiver and stores it keyed by both its full and - * short names. Throws an exception if the short name of the argument - * matches an existing one already in the map for a different class. - * - * @param type - * Class - * @throws IllegalArgumentException - */ - @SuppressWarnings("PMD.CompareObjectsWithEquals") - public void add(Class type) { - final String shortName = ClassUtil.withoutPackageName(type.getName()); - Class existingType = typesByName.get(shortName); - if (existingType == null) { - typesByName.put(type.getName(), type); - typesByName.put(shortName, type); - return; - } - - if (existingType != type) { - throw new IllegalArgumentException( - "Short name collision between existing " + existingType + " and new " + type); - } - } - - /** - * Returns whether the type is known to the receiver. - * - * @param type - * Class - * @return boolean - */ - public boolean contains(Class type) { - return typesByName.containsValue(type); - } - - /** - * Returns whether the typeName is known to the receiver. - * - * @param typeName - * String - * @return boolean - */ - public boolean contains(String typeName) { - return typesByName.containsKey(typeName); - } - - /** - * Returns the type for the typeName specified. - * - * @param typeName - * String - * @return Class - */ - public Class typeFor(String typeName) { - return typesByName.get(typeName); - } - - /** - * Adds an array of types to the receiver at once. - * - * @param types - * Class[] - */ - public void add(Class... types) { - for (Class element : types) { - add(element); - } - } - - /** - * Creates and returns a map of short type names (without the package - * prefixes) keyed by the classes themselves. - * - * @return Map - */ - public Map, String> asInverseWithShortName() { - Map, String> inverseMap = new HashMap<>(typesByName.size() / 2); - - Iterator>> iter = typesByName.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry> entry = iter.next(); - storeShortest(inverseMap, entry.getValue(), entry.getKey()); - } - - return inverseMap; - } - - /** - * Returns the total number of entries in the receiver. This will be exactly - * twice the number of types added. - * - * @return the total number of entries in the receiver - */ - public int size() { - return typesByName.size(); - } - - /** - * Store the shorter of the incoming value or the existing value in the map - * at the key specified. - * - * @param map - * @param key - * @param value - */ - private void storeShortest(Map, String> map, Class key, String value) { - String existingValue = map.get(key); - - if (existingValue == null) { - map.put(key, value); - return; - } - - if (existingValue.length() < value.length()) { - return; - } - - map.put(key, value); - } -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/properties/MethodPropertyTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/properties/MethodPropertyTest.java deleted file mode 100644 index 8e39e7da90..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/properties/MethodPropertyTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Assume; -import org.junit.Test; - -import net.sourceforge.pmd.properties.modules.MethodPropertyModule; -import net.sourceforge.pmd.util.ClassUtil; - - -/** - * Evaluates the functionality of the MethodProperty descriptor by testing its - * ability to catch creation errors (illegal args), flag invalid methods per the - * allowable packages, and serialize/deserialize groups of methods onto/from a - * string buffer. - * - * We're using methods from java.lang classes for 'normal' constructors and - * applying ones from java.util types as ones we expect to fail. - * - * @author Brian Remedios - */ -public class MethodPropertyTest extends AbstractPackagedPropertyDescriptorTester { - - private static final Method[] ALL_METHODS; - - private static final String[] METHOD_SIGNATURES = {"String#indexOf(int)", "String#substring(int,int)", - "java.lang.String#substring(int,int)", "Integer#parseInt(String)", "java.util.HashMap#put(Object,Object)", - "HashMap#containsKey(Object)", }; - - static { - List allMethods = new ArrayList<>(); - for (Method m : String.class.getDeclaredMethods()) { - // exclude String.resolveConstantDesc to avoid random test failure with java12 - // there are two methods with the same signature available, but different return types... - if (!m.getName().equals("resolveConstantDesc")) { - allMethods.add(m); - } - } - ALL_METHODS = allMethods.toArray(new Method[0]); - } - - public MethodPropertyTest() { - super("Method"); - } - - - @Override - @Test - public void testMissingPackageNames() { - Map attributes = getPropertyDescriptorValues(); - attributes.remove(PropertyDescriptorField.LEGAL_PACKAGES); - new MethodProperty("p", "d", ALL_METHODS[1], null, 1.0f); // no exception, null is ok - new MethodMultiProperty("p", "d", new Method[]{ALL_METHODS[2], ALL_METHODS[3]}, null, 1.0f); // no exception, null is ok - } - - - @Test - public void testAsStringOn() { - - Method method; - - for (String methodSignature : METHOD_SIGNATURES) { - method = ValueParserConstants.METHOD_PARSER.valueOf(methodSignature); - assertNotNull("Unable to identify method: " + methodSignature, method); - } - } - - - @Test - public void testAsMethodOn() { - - Method[] methods = new Method[METHOD_SIGNATURES.length]; - - for (int i = 0; i < METHOD_SIGNATURES.length; i++) { - methods[i] = ValueParserConstants.METHOD_PARSER.valueOf(METHOD_SIGNATURES[i]); - assertNotNull("Unable to identify method: " + METHOD_SIGNATURES[i], methods[i]); - } - - String translatedMethod; - for (int i = 0; i < methods.length; i++) { - translatedMethod = MethodPropertyModule.asString(methods[i]); - assertTrue("Translated method does not match", ClassUtil.withoutPackageName(METHOD_SIGNATURES[i]) - .equals(ClassUtil.withoutPackageName(translatedMethod))); - } - } - - - @Override - protected Method createValue() { - return randomChoice(ALL_METHODS); - } - - - @Override - protected Method createBadValue() { - return randomChoice(HashMap.class.getDeclaredMethods()); - } - - - @Override - protected PropertyDescriptor createProperty() { - return new MethodProperty("methodProperty", "asdf", ALL_METHODS[1], new String[]{"java.lang", "org.apache"}, - 1.0f); - } - - - @Override - protected PropertyDescriptor> createMultiProperty() { - return new MethodMultiProperty("methodProperty", "asdf", new Method[]{ALL_METHODS[2], ALL_METHODS[3]}, - new String[]{"java.lang"}, 1.0f); - } - - - @Override - protected PropertyDescriptor createBadProperty() { - return new MethodProperty("methodProperty", "asdf", ALL_METHODS[1], new String[]{"java.util"}, 1.0f); - - } - - - @Override - protected PropertyDescriptor> createBadMultiProperty() { - return new MethodMultiProperty("methodProperty", "asdf", new Method[]{ALL_METHODS[2], ALL_METHODS[3]}, - new String[]{"java.util"}, 1.0f); - } - - - @Override - @Test - public void testFactorySingleValue() { - Assume.assumeTrue("MethodProperty cannot be built from XPath (#762)", false); - } - - - @Override - @Test - public void testFactoryMultiValueCustomDelimiter() { - Assume.assumeTrue("MethodProperty cannot be built from XPath (#762)", false); - } - - - @Override - @Test - public void testFactoryMultiValueDefaultDelimiter() { - Assume.assumeTrue("MethodProperty cannot be built from XPath (#762)", false); - } - -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/properties/TypePropertyTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/properties/TypePropertyTest.java deleted file mode 100644 index bb82bbea48..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/properties/TypePropertyTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Observer; -import java.util.Set; - -/** - * Evaluates the functionality of the TypeProperty descriptor by testing its - * ability to catch creation errors (illegal args), flag invalid Type values per - * the allowable packages, and serialize/deserialize groups of types onto/from a - * string buffer. - * - * We're using java.lang classes for 'normal' constructors and applying - * java.util types as ones we expect to fail. - * - * @author Brian Remedios - */ -public class TypePropertyTest extends AbstractPackagedPropertyDescriptorTester { - - private static final List JAVA_LANG_CLASSES = Arrays.asList(String.class, Integer.class, Thread.class, - Object.class, Runtime.class); - private static final List JAVA_UTIL_CLASSES = Arrays.asList(HashMap.class, Map.class, - Comparator.class, Set.class, - Observer.class); - - - public TypePropertyTest() { - super("Class"); - } - - - @Override - protected Class createBadValue() { - return JAVA_UTIL_CLASSES.get(randomInt(0, JAVA_UTIL_CLASSES.size())); - } - - - @Override - protected PropertyDescriptor createProperty() { - return new TypeProperty("testType", "Test type property", createValue(), new String[] {"java.lang"}, - 1.0f); - } - - - @Override - protected Class createValue() { - return JAVA_LANG_CLASSES.get(randomInt(0, JAVA_LANG_CLASSES.size())); - } - - - @Override - protected PropertyDescriptor> createMultiProperty() { - return new TypeMultiProperty("testType", "Test type property", JAVA_LANG_CLASSES, new String[] {"java.lang"}, - 1.0f); - } - - - @Override - protected PropertyDescriptor createBadProperty() { - return new TypeProperty("testType", "Test type property", createValue(), new String[] {"java.util"}, - 1.0f); - } - - - @Override - protected PropertyDescriptor> createBadMultiProperty() { - return new TypeMultiProperty("testType", "Test type property", Collections.singletonList(Set.class), - new String[] {"java.lang"}, 1.0f); - } -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/TypeMapTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/TypeMapTest.java deleted file mode 100644 index 08d277ee73..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/util/TypeMapTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import static org.junit.Assert.fail; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - -/** - * Evaluates all major functionality of the TypeMap class. - * - * @author Brian Remedios - */ -public class TypeMapTest { - - @Test - public void testAddClassOfQ() { - - TypeMap map = new TypeMap(2); - map.add(List.class); - - try { - map.add(java.awt.List.class); - } catch (IllegalArgumentException ex) { - return; // caught ok - } - - fail("Uncaught error inserting type with same root names"); - } - - @Test - public void testContainsClassOfQ() { - - TypeMap map = new TypeMap(2); - map.add(String.class); - map.add(List.class); - - Assert.assertTrue(map.contains(String.class)); - Assert.assertTrue(map.contains(List.class)); - Assert.assertFalse(map.contains(Map.class)); - } - - @Test - public void testContainsString() { - - TypeMap map = new TypeMap(2); - map.add(String.class); - map.add(List.class); - - Assert.assertTrue(map.contains("String")); - Assert.assertTrue(map.contains("java.lang.String")); - } - - @Test - public void testTypeFor() { - - TypeMap map = new TypeMap(2); - map.add(String.class); - map.add(List.class); - - Assert.assertTrue(map.typeFor("String") == String.class); - Assert.assertTrue(map.typeFor("java.lang.String") == String.class); - Assert.assertTrue(map.typeFor("List") == List.class); - Assert.assertTrue(map.typeFor("java.util.List") == List.class); - } - - @Test - public void testSize() { - - TypeMap map = new TypeMap(4); - map.add(String.class); - map.add(HashMap.class); - map.add(Integer.class); - - Assert.assertTrue(map.size() == 6); - } -} diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java index 38eb211aa9..b4081add3a 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java @@ -4,6 +4,8 @@ package net.sourceforge.pmd.lang.java.rule.bestpractices; +import java.util.Collection; + import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration; @@ -14,29 +16,17 @@ import net.sourceforge.pmd.lang.java.ast.ASTMarkerAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.ASTResultType; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; -import net.sourceforge.pmd.util.CollectionUtil; +import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper; public class LooseCouplingRule extends AbstractJavaRule { - // TODO - these should be brought in via external properties - // private static final Set implClassNames = CollectionUtil.asSet( new - // Object[] { - // "ArrayList", "HashSet", "HashMap", "LinkedHashMap", "LinkedHashSet", - // "TreeSet", "TreeMap", "Vector", - // "java.util.ArrayList", "java.util.HashSet", "java.util.HashMap", - // "java.util.LinkedHashMap", "java.util.LinkedHashSet", - // "java.util.TreeSet", - // "java.util.TreeMap", "java.util.Vector" - // }); - @Override public Object visit(ASTClassOrInterfaceType node, Object data) { if (methodHasOverride(node)) { return data; } Node parent = node.getNthParent(3); - Class clazzType = node.getType(); - boolean isType = CollectionUtil.isCollectionType(clazzType, false); + boolean isType = TypeHelper.isA(node, Collection.class); if (isType && (parent instanceof ASTFieldDeclaration || parent instanceof ASTFormalParameter || parent instanceof ASTResultType)) { addViolation(data, node, node.getImage()); diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseCollectionIsEmptyRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseCollectionIsEmptyRule.java index 552d1116a7..190e51c20a 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseCollectionIsEmptyRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseCollectionIsEmptyRule.java @@ -7,6 +7,7 @@ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -25,6 +26,7 @@ import net.sourceforge.pmd.lang.java.rule.AbstractInefficientZeroCheck; import net.sourceforge.pmd.lang.java.symboltable.ClassScope; import net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence; import net.sourceforge.pmd.lang.java.symboltable.MethodNameDeclaration; +import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper; import net.sourceforge.pmd.lang.symboltable.NameOccurrence; import net.sourceforge.pmd.util.CollectionUtil; @@ -87,8 +89,7 @@ public class UseCollectionIsEmptyRule extends AbstractInefficientZeroCheck { if (calledOnType == null) { calledOnType = getTypeOfMethodCall(primarySuffix); } - return calledOnType != null - && CollectionUtil.isCollectionType(calledOnType.getType(), true); + return calledOnType != null && TypeHelper.isA(calledOnType, Collection.class); } private ASTClassOrInterfaceType getTypeOfVariable(ASTPrimarySuffix primarySuffix) { From d650c87d8d4a60d4ad6fe2a514524d952a50bd94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 28 Jul 2020 12:38:00 +0200 Subject: [PATCH 4/6] Remove more utils --- .../main/java/net/sourceforge/pmd/Report.java | 23 +- .../lang/rule/ParametricRuleViolation.java | 11 +- .../pmd/lang/symboltable/Applier.java | 7 +- .../lang/symboltable/ImageFinderFunction.java | 7 +- .../AbstractMultiPackagedProperty.java | 78 ---- .../properties/AbstractPackagedProperty.java | 71 ---- .../PackagedPropertyDescriptor.java | 30 -- .../pmd/properties/PropertyTypeId.java | 13 - .../modules/PackagedPropertyModule.java | 181 --------- .../modules/TypePropertyModule.java | 34 -- .../pmd/renderers/TextColorRenderer.java | 3 +- .../sourceforge/pmd/util/CollectionUtil.java | 21 +- .../sourceforge/pmd/util/DateTimeUtil.java | 59 --- .../sourceforge/pmd/util/FileIterable.java | 88 ---- .../pmd/util/NumericConstants.java | 21 - .../sourceforge/pmd/util/SearchFunction.java | 18 - .../net/sourceforge/pmd/util/StringUtil.java | 380 ------------------ .../pmd/lang/symboltable/ApplierTest.java | 7 +- .../pmd/util/DateTimeUtilTest.java | 38 -- .../sourceforge/pmd/util/StringUtilTest.java | 26 -- .../rule/documentation/CommentSizeRule.java | 6 +- .../errorprone/MoreThanOneLoggerRule.java | 3 +- .../DeclarationFinderFunction.java | 7 +- .../symboltable/ImageFinderFunctionTest.java | 4 +- .../pmd/lang/jsp/ast/OpenTagRegister.java | 7 +- .../rule/design/NPathComplexityVisitor.java | 7 +- .../plsql/rule/design/TooManyFieldsRule.java | 3 +- .../pmd/lang/vf/ast/OpenTagRegister.java | 7 +- 28 files changed, 65 insertions(+), 1095 deletions(-) delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiPackagedProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPackagedProperty.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/PackagedPropertyDescriptor.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/PackagedPropertyModule.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/TypePropertyModule.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/DateTimeUtil.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/FileIterable.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/NumericConstants.java delete mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/util/SearchFunction.java delete mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/util/DateTimeUtilTest.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index f70506fabf..0bc70cdb51 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -8,6 +8,7 @@ import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -16,8 +17,6 @@ import java.util.List; import java.util.Map; import net.sourceforge.pmd.renderers.AbstractAccumulatingRenderer; -import net.sourceforge.pmd.util.DateTimeUtil; -import net.sourceforge.pmd.util.NumericConstants; /** * A {@link Report} collects all informations during a PMD execution. This @@ -79,7 +78,23 @@ public class Report implements Iterable { * @return human readable representation of the duration */ public String getTime() { - return DateTimeUtil.asHoursMinutesSeconds(duration); + assert this.duration >= 0; + Duration duration = Duration.ofMillis(this.duration); + long seconds = duration.getSeconds(); + + long hours = seconds / 3600; + long minutes = seconds / 60; + + StringBuilder res = new StringBuilder(); + if (hours > 0) { + res.append(hours).append("h "); + } + if (hours > 0 || minutes > 0) { + res.append(minutes).append("m "); + } + res.append(seconds).append('s'); + + return res.toString(); } } @@ -178,7 +193,7 @@ public class Report implements Iterable { for (RuleViolation rv : violations) { String name = rv.getRule().getName(); if (!summary.containsKey(name)) { - summary.put(name, NumericConstants.ZERO); + summary.put(name, 0); } Integer count = summary.get(name); summary.put(name, count + 1); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java index 8e8073aced..ae4999b152 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java @@ -11,7 +11,6 @@ import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.properties.PropertyDescriptor; -import net.sourceforge.pmd.util.StringUtil; public class ParametricRuleViolation implements RuleViolation { @@ -66,19 +65,15 @@ public class ParametricRuleViolation implements RuleViolation { final int endIndex = buf.indexOf("}", startIndex); if (endIndex >= 0) { final String name = buf.substring(startIndex + 2, endIndex); - if (isVariable(name)) { - buf.replace(startIndex, endIndex + 1, getVariableValue(name)); + String variableValue = getVariableValue(name); + if (variableValue != null) { + buf.replace(startIndex, endIndex + 1, variableValue); } } } return buf.toString(); } - protected boolean isVariable(String name) { - return StringUtil.isAnyOf(name, "variableName", "methodName", "className", "packageName") - || rule.getPropertyDescriptor(name) != null; - } - protected String getVariableValue(String name) { if ("variableName".equals(name)) { return variableName; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Applier.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Applier.java index e8c93403db..e42b0cc8c0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Applier.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Applier.java @@ -5,8 +5,7 @@ package net.sourceforge.pmd.lang.symboltable; import java.util.Iterator; - -import net.sourceforge.pmd.util.SearchFunction; +import java.util.function.Predicate; public final class Applier { @@ -14,8 +13,8 @@ public final class Applier { // utility class } - public static void apply(SearchFunction f, Iterator i) { - while (i.hasNext() && f.applyTo(i.next())) { + public static void apply(Predicate f, Iterator i) { + while (i.hasNext() && f.test(i.next())) { // Nothing to do } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ImageFinderFunction.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ImageFinderFunction.java index b9e14141a5..5b8dcfd944 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ImageFinderFunction.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ImageFinderFunction.java @@ -8,10 +8,9 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.Predicate; -import net.sourceforge.pmd.util.SearchFunction; - -public class ImageFinderFunction implements SearchFunction { +public class ImageFinderFunction implements Predicate { private final Set images; private NameDeclaration decl; @@ -25,7 +24,7 @@ public class ImageFinderFunction implements SearchFunction { } @Override - public boolean applyTo(NameDeclaration nameDeclaration) { + public boolean test(NameDeclaration nameDeclaration) { if (images.contains(nameDeclaration.getImage())) { decl = nameDeclaration; return false; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiPackagedProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiPackagedProperty.java deleted file mode 100644 index 31882c325e..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiPackagedProperty.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import java.util.List; -import java.util.Map; - -import net.sourceforge.pmd.properties.modules.PackagedPropertyModule; - - -/** - * Multi-valued property restricting the type of its values to some packages. - * - * @param The type of the values - * - * @author Brian Remedios - * @author Clément Fournier - * @version Refactored June 2017 (6.0.0) - */ -@Deprecated -/* default */ abstract class AbstractMultiPackagedProperty extends AbstractMultiValueProperty - implements PackagedPropertyDescriptor> { - - - protected final PackagedPropertyModule module; - - - /** - * Create a packaged property. - * - * @param theName Name - * @param theDescription Description - * @param theDefault Default value - * @param theUIOrder UI order - * @param module - * - * @throws IllegalArgumentException - */ - protected AbstractMultiPackagedProperty(String theName, String theDescription, List theDefault, - float theUIOrder, boolean isDefinedExternally, - PackagedPropertyModule module) { - super(theName, theDescription, theDefault, theUIOrder, MULTI_VALUE_DELIMITER, isDefinedExternally); - this.module = module; - } - - - @Override - protected void addAttributesTo(Map attributes) { - super.addAttributesTo(attributes); - module.addAttributesTo(attributes); - } - - - @Override - protected String valueErrorFor(T value) { - if (value == null) { - String err = super.valueErrorFor(null); - if (err != null) { - return err; - } - } - - return module.valueErrorFor(value); - } - - - @Override - public String[] legalPackageNames() { - return module.legalPackageNames(); - } - - - protected String[] packageNamesIn(Map params) { - return module.packageNamesIn(params); - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPackagedProperty.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPackagedProperty.java deleted file mode 100644 index 94921e7eae..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPackagedProperty.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -import java.util.Map; - -import net.sourceforge.pmd.properties.modules.PackagedPropertyModule; - - -/** - * Property which restricts the type of its values to some packages. If the legalPackageNames value is set to null then - * no restrictions are made. - * - * @param The type of the values - * - * @author Brian Remedios - * @author Clément Fournier - * @version Refactored June 2017 (6.0.0) - */ -@Deprecated -/* default */ abstract class AbstractPackagedProperty extends AbstractSingleValueProperty - implements PackagedPropertyDescriptor { - - protected final PackagedPropertyModule module; - - - /** - * Create a packaged property. - * - * @param theName Name - * @param theDescription Description - * @param theDefault Default value - * @param theUIOrder UI order - * @param module - * - * @throws IllegalArgumentException - */ - protected AbstractPackagedProperty(String theName, String theDescription, T theDefault, - float theUIOrder, boolean isDefinedExternally, - PackagedPropertyModule module) { - super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally); - this.module = module; - } - - - @Override - protected void addAttributesTo(Map attributes) { - super.addAttributesTo(attributes); - module.addAttributesTo(attributes); - } - - - @Override - protected String valueErrorFor(T value) { - return module.valueErrorFor(value); - } - - - @Override - public String[] legalPackageNames() { - return module.legalPackageNames(); - } - - - protected String[] packageNamesIn(Map params) { - return module.packageNamesIn(params); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PackagedPropertyDescriptor.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PackagedPropertyDescriptor.java deleted file mode 100644 index e650d9a9b9..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PackagedPropertyDescriptor.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties; - -/** - * Defines a property descriptor type whose values can be described by qualified names and thus restricted to only some - * packages. These typically use values such as {@link Class} and {@link java.lang.reflect.Method}. - * - * @param type of the property value - * - * @author Clément Fournier - */ -@Deprecated -public interface PackagedPropertyDescriptor extends PropertyDescriptor { - - /** Delimiter used to separate package names. */ - char PACKAGE_NAME_DELIMITER = ' '; - /** Delimiter used to separate multiple values if this descriptor is multi valued. */ - char MULTI_VALUE_DELIMITER = '|'; - - - /** - * Returns the legal package names. - * - * @return The legal package names - */ - String[] legalPackageNames(); -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java index 31fc29be43..0ac9b4a361 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java @@ -116,19 +116,6 @@ public enum PropertyTypeId { } - /** - * Returns true if the property corresponding to this factory is packaged, - * which means it can be safely cast to a {@link PackagedPropertyDescriptor}. - * - * @return whether the property is packaged - */ - @Deprecated - public boolean isPropertyPackaged() { - return factory instanceof PropertyDescriptorBuilderConversionWrapper.SingleValue.Packaged - || factory instanceof PropertyDescriptorBuilderConversionWrapper.MultiValue.Packaged; - } - - /** * Returns true if the property corresponding to this factory takes * lists of values as its value. diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/PackagedPropertyModule.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/PackagedPropertyModule.java deleted file mode 100644 index 5e90f6f4cc..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/PackagedPropertyModule.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties.modules; - -import static net.sourceforge.pmd.properties.PackagedPropertyDescriptor.PACKAGE_NAME_DELIMITER; -import static net.sourceforge.pmd.properties.PropertyDescriptorField.LEGAL_PACKAGES; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; - -import net.sourceforge.pmd.properties.PropertyDescriptorField; - - -/** - * Factorises common functionality for packaged properties. - * - * @author Clément Fournier - */ -@Deprecated -public abstract class PackagedPropertyModule { - - private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("(\\w+)(\\.\\w+)*"); - - private final String[] legalPackageNames; - - - public PackagedPropertyModule(String[] legalPackageNames, List defaults) { - - checkValidPackages(legalPackageNames); - checkValidDefaults(defaults, legalPackageNames); - - this.legalPackageNames = legalPackageNames; - } - - - /** - * Checks that the legal packages are okay. - * - * @param legalNamePrefixes Prefixes to check. Can be null, but not contain null - * - * @throws IllegalArgumentException If the prefixes contain null - * @throws IllegalArgumentException If one name that does not look like a package name - */ - private void checkValidPackages(String[] legalNamePrefixes) throws IllegalArgumentException { - if (legalNamePrefixes == null) { - return; - } - - for (String name : legalNamePrefixes) { - if (name == null) { - throw new IllegalArgumentException("Null is not allowed in the legal package names:" - + Arrays.toString(legalNamePrefixes)); - } else if (!PACKAGE_NAME_PATTERN.matcher(name).matches()) { - throw new IllegalArgumentException("One name is not a package: '" + name + "'"); - - } - } - } - - - /** - * Evaluates the names of the items against the allowable name prefixes. If one or more do not have valid prefixes - * then an exception will be thrown. - * - * @param items Items to check - * @param legalNamePrefixes Legal name prefixes - * - * @throws IllegalArgumentException if some items are not allowed - */ - private void checkValidDefaults(List items, String[] legalNamePrefixes) { - - if (legalNamePrefixes == null) { // valid value, matches everything - return; - } - - Set nameSet = new HashSet<>(); - - for (T item : items) { - if (item == null) { - continue; - } - nameSet.add(packageNameOf(item)); - } - - Set notAllowed = new HashSet<>(nameSet); - - - for (String name : nameSet) { - for (String prefix : legalNamePrefixes) { - if (name.startsWith(prefix)) { - notAllowed.remove(name); - break; - } - } - } - - if (notAllowed.isEmpty()) { - return; - } - - throw new IllegalArgumentException("Invalid items: " + notAllowed); - } - - - /** - * Returns the package name of the item. - * - * @param item Item (not null) - * - * @return Package name of the item - */ - protected abstract String packageNameOf(T item); - - - public String valueErrorFor(T value) { - - if (legalPackageNames == null) { - return null; // no restriction - } - - String name = packageNameOf(value); - - for (int i = 0; i < legalPackageNames.length; i++) { - if (name.startsWith(legalPackageNames[i])) { - return null; - } - } - - return "Disallowed " + itemTypeName() + ": " + name; - } - - - /** - * Returns the name of the type of item. - * - * @return The name of the type of item - */ - protected abstract String itemTypeName(); - - - public String[] legalPackageNames() { - return Arrays.copyOf(legalPackageNames, legalPackageNames.length); - } - - - public void addAttributesTo(Map attributes) { - attributes.put(LEGAL_PACKAGES, delimitedPackageNames()); - } - - - private String delimitedPackageNames() { - - if (legalPackageNames == null || legalPackageNames.length == 0) { - return ""; - } - if (legalPackageNames.length == 1) { - return legalPackageNames[0]; - } - - StringBuilder sb = new StringBuilder(); - sb.append(legalPackageNames[0]); - for (int i = 1; i < legalPackageNames.length; i++) { - sb.append(PACKAGE_NAME_DELIMITER).append(legalPackageNames[i]); - } - return sb.toString(); - } - - - public String[] packageNamesIn(Map params) { - return StringUtils.split(params.get(LEGAL_PACKAGES), PACKAGE_NAME_DELIMITER); - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/TypePropertyModule.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/TypePropertyModule.java deleted file mode 100644 index 52e4f5d87f..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/TypePropertyModule.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.properties.modules; - -import java.util.List; - - -/** - * Factorises common functionality for type properties. - * - * @author Clément Fournier - */ -@Deprecated -public class TypePropertyModule extends PackagedPropertyModule { - - public TypePropertyModule(String[] legalPackageNames, List defaults) { - super(legalPackageNames, defaults); - } - - - @Override - protected String packageNameOf(Class item) { - return item.getName(); - } - - - @Override - protected String itemTypeName() { - return "type"; - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java index 4dd4667070..208a03261f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java @@ -22,7 +22,6 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; -import net.sourceforge.pmd.util.NumericConstants; /** *

@@ -204,7 +203,7 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { continue; } Integer o = summary.get(key); - summary.put(key, o == null ? NumericConstants.ONE : o + 1); + summary.put(key, o == null ? 1 : o + 1); } return summary; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java index 82c19c936e..80498daf7c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java @@ -84,7 +84,10 @@ public final class CollectionUtil { * @param includeInterfaces * boolean * @return boolean + * + * @deprecated Will be replaced with type resolution */ + @Deprecated public static boolean isCollectionType(String typeName, boolean includeInterfaces) { if (COLLECTION_CLASSES_BY_NAMES.contains(typeName)) { @@ -94,18 +97,6 @@ public final class CollectionUtil { return includeInterfaces && COLLECTION_INTERFACES_BY_NAMES.contains(typeName); } - /** - * Returns the items as a populated set. - * - * @param items - * Object[] - * @return Set - */ - public static Set asSet(T[] items) { - - return new HashSet<>(Arrays.asList(items)); - } - /** * Creates and returns a map populated with the keyValuesSets where the * value held by the tuples are they key and value in that order. @@ -115,7 +106,10 @@ public final class CollectionUtil { * @param values * V[] * @return Map + * + * @deprecated Used by deprecated property types */ + @Deprecated public static Map mapFrom(K[] keys, V[] values) { if (keys.length != values.length) { throw new RuntimeException("mapFrom keys and values arrays have different sizes"); @@ -133,7 +127,10 @@ public final class CollectionUtil { * @param source * Map * @return Map + * + * @deprecated Used by deprecated property types */ + @Deprecated public static Map invertedMapFrom(Map source) { Map map = new HashMap<>(source.size()); for (Map.Entry entry : source.entrySet()) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/DateTimeUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/DateTimeUtil.java deleted file mode 100644 index 4a374ce3a1..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/DateTimeUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import net.sourceforge.pmd.annotation.InternalApi; - -/** - * - * @author Brian Remedios - */ -@InternalApi -@Deprecated -public final class DateTimeUtil { - - private DateTimeUtil() { - } - - /** - * - * @param milliseconds - * @return String - */ - public static String asHoursMinutesSeconds(long milliseconds) { - - if (milliseconds < 0) { - throw new IllegalArgumentException(); - } - - long seconds = 0; - long minutes = 0; - long hours = 0; - - if (milliseconds > 1000) { - seconds = milliseconds / 1000; - } - - if (seconds > 60) { - minutes = seconds / 60; - seconds = seconds % 60; - } - - if (minutes > 60) { - hours = minutes / 60; - minutes = minutes % 60; - } - - StringBuilder res = new StringBuilder(); - if (hours > 0) { - res.append(hours).append("h "); - } - if (hours > 0 || minutes > 0) { - res.append(minutes).append("m "); - } - res.append(seconds).append('s'); - return res.toString(); - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/FileIterable.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/FileIterable.java deleted file mode 100644 index fdd4a1f8f3..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/FileIterable.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import java.io.File; -import java.io.IOException; -import java.io.LineNumberReader; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Iterator; - -/** - * - *

- * Handy class to easily iterate over a file, line by line, using a Java 5 for - * loop. - *

- * - * @author Romain Pelisse <belaran@gmail.com> - * @deprecated Just use {@link Files#readAllLines(Path, Charset)} or {@code lines} on Java 8 - */ -@Deprecated -public class FileIterable implements Iterable { - - private LineNumberReader lineReader = null; - - public FileIterable(File file) { - try { - lineReader = new LineNumberReader(Files.newBufferedReader(file.toPath(), Charset.defaultCharset())); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - protected void finalize() throws Throwable { - try { - if (lineReader != null) { - lineReader.close(); - } - } catch (IOException e) { - throw new IllegalStateException(e); - } - super.finalize(); - } - - @Override - public Iterator iterator() { - return new FileIterator(); - } - - class FileIterator implements Iterator { - - private boolean hasNext = true; - - @Override - public boolean hasNext() { - return hasNext; - } - - @Override - public String next() { - String line = null; - try { - if (hasNext) { - line = lineReader.readLine(); - if (line == null) { - hasNext = false; - line = ""; - } - } - return line; - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove is not supported by " + this.getClass().getName()); - } - - } - -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/NumericConstants.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/NumericConstants.java deleted file mode 100644 index fc37a21165..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/NumericConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -/** - * @deprecated These constants were only useful before autoboxing was - * introduced, just use a literal or define your own constants - */ -@Deprecated -public final class NumericConstants { - - public static final Integer ZERO = 0; - - public static final Integer ONE = 1; - - public static final Float FLOAT_ZERO = 0.0f; - - private NumericConstants() { } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/SearchFunction.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/SearchFunction.java deleted file mode 100644 index 709aa57325..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/SearchFunction.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -/** - * @deprecated Will be replaced with standard java.util.function.Predicate with 7.0.0 - */ -@Deprecated -public interface SearchFunction { - /** - * Applies the search function over a single element. - * @param o The element to analyze. - * @return True if the search should continue, false otherwhise. - */ - boolean applyTo(E o); -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java index 95765777ba..6b94dd6b64 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java @@ -4,9 +4,6 @@ package net.sourceforge.pmd.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; @@ -167,44 +164,6 @@ public final class StringUtil { } - /** - * Return whether the non-null text arg starts with any of the prefix - * values. - * - * @return boolean - * - * @deprecated {@link StringUtils#startsWithAny(CharSequence, CharSequence...)} - */ - @Deprecated - public static boolean startsWithAny(String text, String... prefixes) { - - for (String prefix : prefixes) { - if (text.startsWith(prefix)) { - return true; - } - } - - return false; - } - - - /** - * Returns whether the non-null text arg matches any of the test values. - * - * @return boolean - */ - public static boolean isAnyOf(String text, String... tests) { - - for (String test : tests) { - if (text.equals(test)) { - return true; - } - } - - return false; - } - - /** * Checks for the existence of any of the listed prefixes on the non-null * text and removes them. @@ -223,100 +182,6 @@ public final class StringUtil { } - /** - * @param value String - * - * @return boolean - * - * @deprecated {@link StringUtils#isNotBlank(CharSequence)} - */ - @Deprecated - public static boolean isNotEmpty(String value) { - return !isEmpty(value); - } - - - /** - * Returns true if the value arg is either null, empty, or full of - * whitespace characters. More efficient that calling - * (string).trim().length() == 0. - * - * @param value String to test - * - * @return true if the value is empty, false otherwise. - * - * @deprecated {@link StringUtils#isBlank(CharSequence)} - */ - @Deprecated - public static boolean isEmpty(String value) { - return StringUtils.isBlank(value); - } - - - /** - * Returns true if the argument is null or the empty string. - * - * @param value String to test - * - * @return True if the argument is null or the empty string - * - * @deprecated {@link StringUtils#isEmpty(CharSequence)} - */ - @Deprecated - public static boolean isMissing(String value) { - return StringUtils.isEmpty(value); - } - - - /** - * Returns true if both strings are effectively null or whitespace, returns - * false otherwise if they have actual text that differs. - * - * @return boolean - */ - @Deprecated - public static boolean areSemanticEquals(String a, String b) { - - if (a == null) { - return isEmpty(b); - } - if (b == null) { - return isEmpty(a); - } - - return a.equals(b); - } - - - /** - * @param original String - * @param oldString String - * @param newString String - * - * @return String - * - * @deprecated {@link StringUtils#replace(String, String, String)} - */ - @Deprecated - public static String replaceString(final String original, final String oldString, final String newString) { - int index = original.indexOf(oldString); - if (index < 0) { - return original; - } else { - final String replace = newString == null ? "" : newString; - final StringBuilder buf = new StringBuilder(Math.max(16, original.length() + replace.length())); - int last = 0; - while (index != -1) { - buf.append(original.substring(last, index)); - buf.append(replace); - last = index + oldString.length(); - index = original.indexOf(oldString, last); - } - buf.append(original.substring(last)); - return buf.toString(); - } - } - /** * @param supportUTF8 override the default setting, whether special characters should be replaced with entities ( * false) or should be included as is ( true). @@ -387,174 +252,6 @@ public final class StringUtil { return s; } - /** - * @param original String - * @param oldChar char - * @param newString String - * - * @return String - * - * @deprecated {@link StringUtils#replace(String, String, String)} or {@link StringUtils#replaceChars(String, char, char)} - */ - @Deprecated - public static String replaceString(final String original, char oldChar, final String newString) { - int index = original.indexOf(oldChar); - if (index < 0) { - return original; - } else { - final String replace = newString == null ? "" : newString; - final StringBuilder buf = new StringBuilder(Math.max(16, original.length() + replace.length())); - int last = 0; - while (index != -1) { - buf.append(original.substring(last, index)); - buf.append(replace); - last = index + 1; - index = original.indexOf(oldChar, last); - } - buf.append(original.substring(last)); - return buf.toString(); - } - } - - - /** - * Parses the input source using the delimiter specified. This method is - * much faster than using the StringTokenizer or String.split(char) approach - * and serves as a replacement for String.split() for JDK1.3 that doesn't - * have it. - * - * @param source String - * @param delimiter char - * - * @return String[] - * - * @deprecated {@link StringUtils#split(String, char)} - */ - @Deprecated - public static String[] substringsOf(String source, char delimiter) { - - if (source == null || source.length() == 0) { - return EMPTY_STRINGS; - } - - int delimiterCount = 0; - int length = source.length(); - char[] chars = source.toCharArray(); - - for (int i = 0; i < length; i++) { - if (chars[i] == delimiter) { - delimiterCount++; - } - } - - if (delimiterCount == 0) { - return new String[] {source}; - } - - String[] results = new String[delimiterCount + 1]; - - int i = 0; - int offset = 0; - - while (offset <= length) { - int pos = source.indexOf(delimiter, offset); - if (pos < 0) { - pos = length; - } - results[i++] = pos == offset ? "" : source.substring(offset, pos); - offset = pos + 1; - } - - return results; - } - - - /** - * Much more efficient than StringTokenizer. - * - * @param str String - * @param separator char - * - * @return String[] - * - * @deprecated {@link StringUtils#split(String, String)} - */ - @Deprecated - public static String[] substringsOf(String str, String separator) { - - if (str == null || str.length() == 0) { - return EMPTY_STRINGS; - } - - int index = str.indexOf(separator); - if (index == -1) { - return new String[] {str}; - } - - List list = new ArrayList<>(); - int currPos = 0; - int len = separator.length(); - while (index != -1) { - list.add(str.substring(currPos, index)); - currPos = index + len; - index = str.indexOf(separator, currPos); - } - list.add(str.substring(currPos)); - return list.toArray(new String[0]); - } - - - /** - * Copies the elements returned by the iterator onto the string buffer each - * delimited by the separator. - * - * @param sb StringBuffer - * @param iter Iterator - * @param separator String - * - * @deprecated {@link StringUtils#join(Iterator, String)} - */ - @Deprecated - public static void asStringOn(StringBuffer sb, Iterator iter, String separator) { - - if (!iter.hasNext()) { - return; - } - - sb.append(iter.next()); - - while (iter.hasNext()) { - sb.append(separator); - sb.append(iter.next()); - } - } - - - /** - * Copies the array items onto the string builder each delimited by the - * separator. Does nothing if the array is null or empty. - * - * @param sb StringBuilder - * @param items Object[] - * @param separator String - * - * @deprecated {@link StringUtils#join(Iterable, String)} - */ - @Deprecated - public static void asStringOn(StringBuilder sb, Object[] items, String separator) { - - if (items == null || items.length == 0) { - return; - } - - sb.append(items[0]); - - for (int i = 1; i < items.length; i++) { - sb.append(separator); - sb.append(items[i]); - } - } - /** * Determine the maximum number of common leading whitespace characters the @@ -634,28 +331,6 @@ public final class StringUtil { } - /** - * Left pads a string. - * - * @param s The String to pad - * @param length The desired minimum length of the resulting padded String - * - * @return The resulting left padded String - * - * @deprecated {@link StringUtils#leftPad(String, int)} - */ - @Deprecated - public static String lpad(String s, int length) { - String res = s; - if (length - s.length() > 0) { - char[] arr = new char[length - s.length()]; - Arrays.fill(arr, ' '); - res = new StringBuilder(length).append(arr).append(s).toString(); - } - return res; - } - - /** * Are the two String values the same. The Strings can be optionally trimmed * before checking. The Strings can be optionally compared ignoring case. @@ -729,61 +404,6 @@ public final class StringUtil { } - /** - * Converts the given string to Camel case, - * that is, removing all spaces, and capitalising - * the first letter of each word except the first. - * - *

If the first word starts with an uppercase - * letter, it's kept as is. This method can thus - * be used for Pascal case too. - * - * @param name The string to convert - * - * @return The string converted to Camel case - * - * @deprecated Use {@link CaseConvention} - */ - @Deprecated - public static String toCamelCase(String name) { - return toCamelCase(name, false); - } - - - /** - * Converts the given string to Camel case, - * that is, removing all spaces, and capitalising - * the first letter of each word except the first. - * - *

The second parameter can be used to force the - * words to be converted to lowercase before capitalising. - * This can be useful if eg the first word contains - * several uppercase letters. - * - * @param name The string to convert - * @param forceLowerCase Whether to force removal of all upper - * case letters except on word start - * - * @return The string converted to Camel case - * - * @deprecated Use {@link CaseConvention} - */ - @Deprecated - public static String toCamelCase(String name, boolean forceLowerCase) { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - for (String word : name.trim().split("\\s++")) { - String pretreated = forceLowerCase ? word.toLowerCase(Locale.ROOT) : word; - if (isFirst) { - sb.append(pretreated); - isFirst = false; - } else { - sb.append(StringUtils.capitalize(pretreated)); - } - } - return sb.toString(); - } - /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/symboltable/ApplierTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/symboltable/ApplierTest.java index e3dc8558ad..934ab5edb0 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/symboltable/ApplierTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/symboltable/ApplierTest.java @@ -8,14 +8,13 @@ import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; +import java.util.function.Predicate; import org.junit.Test; -import net.sourceforge.pmd.util.SearchFunction; - public class ApplierTest { - private static class MyFunction implements SearchFunction { + private static class MyFunction implements Predicate { private int numCallbacks = 0; private final int maxCallbacks; @@ -24,7 +23,7 @@ public class ApplierTest { } @Override - public boolean applyTo(Object o) { + public boolean test(Object o) { this.numCallbacks++; return numCallbacks < maxCallbacks; } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/DateTimeUtilTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/DateTimeUtilTest.java deleted file mode 100644 index 61d66292cb..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/util/DateTimeUtilTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.util; - -import static org.junit.Assert.assertEquals; - -import java.util.Collection; - -import org.junit.Test; - -import net.sourceforge.pmd.ReadableDurationTest; - -/** - * - * @author Brian Remedios - */ -public class DateTimeUtilTest { - - @Test - public void testConversions() { - - Collection stringNumberPairs = ReadableDurationTest.data(); - - for (Object[] stringAndNumber : stringNumberPairs) { - String result = (String) stringAndNumber[0]; - Integer milliseconds = (Integer) stringAndNumber[1]; - - assertEquals(result, DateTimeUtil.asHoursMinutesSeconds(milliseconds)); - } - - } - - public static junit.framework.Test suite() { - return new junit.framework.JUnit4TestAdapter(DateTimeUtilTest.class); - } -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java index 9362373baf..f03e7ce6ca 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java @@ -10,11 +10,6 @@ import org.junit.Test; public class StringUtilTest { - @Test - public void testReplaceWithOneChar() { - assertEquals("faa", StringUtil.replaceString("foo", 'o', "a")); - } - @Test public void testColumnNumber() { assertEquals(-1, StringUtil.columnNumberAt("f\rah\nb", -1)); @@ -52,27 +47,6 @@ public class StringUtilTest { assertEquals(-1, StringUtil.columnNumberAt("", 1)); } - @Test - public void testReplaceWithMultipleChars() { - assertEquals("faaaa", StringUtil.replaceString("foo", 'o', "aa")); - } - - @Test - public void testReplaceStringWithString() { - assertEquals("foo]]>bar", StringUtil.replaceString("foo]]>bar", "]]>", "]]>")); - } - - @Test - public void testReplaceStringWithString2() { - assertEquals("replaceString didn't work with a >", "foobar", - StringUtil.replaceString("foobar", "]]>", "]]>")); - } - - @Test - public void testReplaceWithNull() { - assertEquals("replaceString didn't work with a char", "f", StringUtil.replaceString("foo", 'o', null)); - } - @Test public void testUTF8NotSupported() { StringBuilder sb = new StringBuilder(); diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeRule.java index 4f27e3ee66..eeb80497cd 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeRule.java @@ -5,9 +5,11 @@ package net.sourceforge.pmd.lang.java.rule.documentation; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; +import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.ArrayList; import java.util.List; +import java.util.Set; import org.apache.commons.lang3.StringUtils; @@ -36,6 +38,8 @@ public class CommentSizeRule extends AbstractCommentRule { private static final String CR = "\n"; + static final Set IGNORED_LINES = setOf("//", "/*", "/**", "*", "*/"); + public CommentSizeRule() { definePropertyDescriptor(MAX_LINES); definePropertyDescriptor(MAX_LINE_LENGTH); @@ -47,7 +51,7 @@ public class CommentSizeRule extends AbstractCommentRule { return false; } - return !StringUtil.isAnyOf(line.trim(), "//", "/*", "/**", "*", "*/"); + return !IGNORED_LINES.contains(line.trim()); } private boolean hasTooManyLines(Comment comment) { diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/MoreThanOneLoggerRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/MoreThanOneLoggerRule.java index 4a12afe969..e45d885fd5 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/MoreThanOneLoggerRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/MoreThanOneLoggerRule.java @@ -17,7 +17,6 @@ import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper; -import net.sourceforge.pmd.util.NumericConstants; public class MoreThanOneLoggerRule extends AbstractJavaRule { @@ -47,7 +46,7 @@ public class MoreThanOneLoggerRule extends AbstractJavaRule { private Object init(JavaNode node, Object data) { stack.push(count); - count = NumericConstants.ZERO; + count = 0; node.children().forEach(it -> it.acceptVisitor(this, data)); diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symboltable/DeclarationFinderFunction.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symboltable/DeclarationFinderFunction.java index b513294028..5d70064a45 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symboltable/DeclarationFinderFunction.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symboltable/DeclarationFinderFunction.java @@ -4,12 +4,13 @@ package net.sourceforge.pmd.lang.java.symboltable; +import java.util.function.Predicate; + import net.sourceforge.pmd.lang.java.ast.ASTMethodReference; import net.sourceforge.pmd.lang.symboltable.NameDeclaration; import net.sourceforge.pmd.lang.symboltable.NameOccurrence; -import net.sourceforge.pmd.util.SearchFunction; -public class DeclarationFinderFunction implements SearchFunction { +public class DeclarationFinderFunction implements Predicate { private NameOccurrence occurrence; private NameDeclaration decl; @@ -19,7 +20,7 @@ public class DeclarationFinderFunction implements SearchFunction tagList = new ArrayList<>(); public void openTag(ASTElement elm) { - if (elm == null || StringUtil.isEmpty(elm.getName())) { + if (elm == null || StringUtils.isBlank(elm.getName())) { throw new IllegalStateException("Tried to open a tag with empty name"); } @@ -40,7 +41,7 @@ class OpenTagRegister { * was ever opened ( or registered ) */ public boolean closeTag(String closingTagName) { - if (StringUtil.isEmpty(closingTagName)) { + if (StringUtils.isBlank(closingTagName)) { throw new IllegalStateException("Tried to close a tag with empty name"); } diff --git a/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityVisitor.java b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityVisitor.java index 4ea35c76f7..f895ca4cdb 100644 --- a/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityVisitor.java +++ b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityVisitor.java @@ -27,7 +27,6 @@ import net.sourceforge.pmd.lang.plsql.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode; import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode; import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapter; -import net.sourceforge.pmd.util.NumericConstants; /** * @author Clément Fournier @@ -220,7 +219,7 @@ class NPathComplexityVisitor extends PLSQLParserVisitorAdapter { ASTExpression expr = node.getFirstChildOfType(ASTExpression.class); if (expr == null) { - return NumericConstants.ONE; + return 1; } int boolCompReturn = NPathComplexityRule.sumExpressionComplexity(expr); @@ -233,7 +232,7 @@ class NPathComplexityVisitor extends PLSQLParserVisitorAdapter { if (boolCompReturn > 0) { return boolCompReturn; } - return NumericConstants.ONE; + return 1; } @Override @@ -278,7 +277,7 @@ class NPathComplexityVisitor extends PLSQLParserVisitorAdapter { @Override public Object visit(ASTConditionalOrExpression node, Object data) { - return NumericConstants.ONE; + return 1; } } diff --git a/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsRule.java b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsRule.java index 094f47c3ef..30f7f1b0a9 100644 --- a/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsRule.java +++ b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsRule.java @@ -19,7 +19,6 @@ import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode; import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; -import net.sourceforge.pmd.util.NumericConstants; public class TooManyFieldsRule extends AbstractPLSQLRule { @@ -91,7 +90,7 @@ public class TooManyFieldsRule extends AbstractPLSQLRule { private void bumpCounterFor(PLSQLNode clazz) { String key = clazz.getImage(); if (!stats.containsKey(key)) { - stats.put(key, NumericConstants.ZERO); + stats.put(key, 0); nodes.put(key, clazz); } Integer i = stats.get(key) + 1; diff --git a/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegister.java b/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegister.java index 910c21db2a..0c8eca2519 100644 --- a/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegister.java +++ b/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegister.java @@ -7,8 +7,9 @@ package net.sourceforge.pmd.lang.vf.ast; import java.util.ArrayList; import java.util.List; +import org.apache.commons.lang3.StringUtils; + import net.sourceforge.pmd.annotation.InternalApi; -import net.sourceforge.pmd.util.StringUtil; /** * Utility class to keep track of unclosed tags. The mechanism is rather simple. @@ -26,7 +27,7 @@ class OpenTagRegister { private List tagList = new ArrayList<>(); public void openTag(ASTElement elm) { - if (elm == null || StringUtil.isEmpty(elm.getName())) { + if (elm == null || StringUtils.isBlank(elm.getName())) { throw new IllegalStateException("Tried to open a tag with empty name"); } @@ -40,7 +41,7 @@ class OpenTagRegister { * was ever opened ( or registered ) */ public boolean closeTag(String closingTagName) { - if (StringUtil.isEmpty(closingTagName)) { + if (StringUtils.isBlank(closingTagName)) { throw new IllegalStateException("Tried to close a tag with empty name"); } From e0de46652b00bc95378e8fbb3ff8913edb1673e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 28 Jul 2020 12:54:07 +0200 Subject: [PATCH 5/6] Fix tests --- .../main/java/net/sourceforge/pmd/Report.java | 2 + .../lang/rule/ParametricRuleViolation.java | 2 +- .../pmd/renderers/TextColorRenderer.java | 10 +- .../pmd/lang/DummyLanguageModule.java | 5 +- .../lang/dfa/report/ViolationNodeTest.java | 115 ------------------ .../pmd/renderers/PapariTextRendererTest.java | 4 +- 6 files changed, 15 insertions(+), 123 deletions(-) delete mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/lang/dfa/report/ViolationNodeTest.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index 0bc70cdb51..9f98fc680d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -83,7 +83,9 @@ public class Report implements Iterable { long seconds = duration.getSeconds(); long hours = seconds / 3600; + seconds -= hours * 3600; long minutes = seconds / 60; + seconds -= minutes * 60; StringBuilder res = new StringBuilder(); if (hours > 0) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java index ae4999b152..285d27ae8b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java @@ -85,7 +85,7 @@ public class ParametricRuleViolation implements RuleViolation { return packageName; } else { final PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(name); - return String.valueOf(rule.getProperty(propertyDescriptor)); + return propertyDescriptor == null ? null : String.valueOf(rule.getProperty(propertyDescriptor)); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java index 208a03261f..31472045cb 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java @@ -183,10 +183,10 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { // adding error message count, if any if (numberOfErrors > 0) { writer.write(this.redBold + "*" + this.colorReset + " errors: " + this.whiteBold + numberOfErrors - + this.colorReset + PMD.EOL); + + this.colorReset + PMD.EOL); } writer.write(this.yellowBold + "*" + this.colorReset + " warnings: " + this.whiteBold + numberOfWarnings - + this.colorReset + PMD.EOL); + + this.colorReset + PMD.EOL); } @@ -216,8 +216,10 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { /** * Retrieves the requested line from the specified file. * - * @param sourceFile the java or cpp source file - * @param line line number to extract + * @param sourceFile + * the java or cpp source file + * @param line + * line number to extract * * @return a trimmed line of source code */ diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/DummyLanguageModule.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/DummyLanguageModule.java index b7c49de123..fa2e8a3062 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/DummyLanguageModule.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/DummyLanguageModule.java @@ -97,9 +97,12 @@ public class DummyLanguageModule extends BaseLanguageModule { protected RuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message, int beginLine, int endLine) { ParametricRuleViolation rv = new ParametricRuleViolation(rule, ruleContext, node, message) { + { + this.packageName = "foo"; // just for testing variable expansion + } + @Override public String getPackageName() { - this.packageName = "foo"; // just for testing variable expansion return super.getPackageName(); } }; diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/dfa/report/ViolationNodeTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/dfa/report/ViolationNodeTest.java deleted file mode 100644 index 4d5ffcdbe0..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/dfa/report/ViolationNodeTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.dfa.report; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Test; - -import net.sourceforge.pmd.RuleViolation; - -/** - * @author Philip Graf - */ -public final class ViolationNodeTest { - - /** - * Verifies that two violations nodes with equal - * {@code filename, beginLine, endLine, beginColumn, endColumn} and - * {@code variableName} are equal. - */ - @Test - public void testEqualsNodeWithTwoEqualViolations() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - assertTrue("Two equal violations should result in equal nodes", node1.equalsNode(node2)); - } - - /** - * Verifies that two violations nodes with different {@code filename} are - * not equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentFilename() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Bar.java", 1, 1, 5, 15, ""); - assertFalse("Two violations with different filename should result in not equal nodes", node1.equalsNode(node2)); - } - - /** - * Verifies that two violations nodes with different {@code beginLine} are - * not equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentBeginLine() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 2, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Foo.java", 2, 2, 5, 15, ""); - assertFalse("Two violations with different beginLine should result in not equal nodes", - node1.equalsNode(node2)); - } - - /** - * Verifies that two violations nodes with different {@code endLine} are not - * equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentEndLine() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Foo.java", 1, 2, 5, 15, ""); - assertFalse("Two violations with different endLine should result in not equal nodes", node1.equalsNode(node2)); - } - - /** - * Verifies that two violations nodes with different {@code beginColumn} are - * not equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentBeginColumn() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Foo.java", 1, 1, 7, 15, ""); - assertFalse("Two violations with different beginColumn should result in not equal nodes", - node1.equalsNode(node2)); - } - - /** - * Verifies that two violations nodes with different {@code endColumn} are - * not equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentEndColumn() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, ""); - final ViolationNode node2 = createViolationNode("Foo.java", 1, 1, 5, 17, ""); - assertFalse("Two violations with different end column should result in not equal nodes", - node1.equalsNode(node2)); - } - - /** - * Verifies that two violations with different {@code variableName} are not - * equal. - */ - @Test - public void testEqualsNodeWithTwoDifferentViolationsDifferentVariableName() { - final ViolationNode node1 = createViolationNode("Foo.java", 1, 1, 5, 15, "a"); - final ViolationNode node2 = createViolationNode("Foo.java", 1, 1, 5, 15, "b"); - assertFalse("Two violations with different variableName should result in not equal nodes", - node1.equalsNode(node2)); - } - - private ViolationNode createViolationNode(final String filename, final int beginLine, final int endLine, - final int beginColumn, final int endColumn, final String variableName) { - final RuleViolation violation = mock(RuleViolation.class); - when(violation.getFilename()).thenReturn(filename); - when(violation.getBeginLine()).thenReturn(beginLine); - when(violation.getEndLine()).thenReturn(endLine); - when(violation.getBeginColumn()).thenReturn(beginColumn); - when(violation.getEndColumn()).thenReturn(endColumn); - when(violation.getVariableName()).thenReturn(variableName); - return new ViolationNode(violation); - } - -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/PapariTextRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/PapariTextRendererTest.java index 43d9651595..7047e79d46 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/PapariTextRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/PapariTextRendererTest.java @@ -30,7 +30,7 @@ public class PapariTextRendererTest extends AbstractRendererTest { public String getExpected() { return "* file: " + getSourceCodeFilename() + PMD.EOL + " src: " + getSourceCodeFilename() + ":1:1" + PMD.EOL + " rule: Foo" + PMD.EOL + " msg: blah" + PMD.EOL + " code: public class Foo {}" + PMD.EOL + PMD.EOL + PMD.EOL + PMD.EOL - + "Summary:" + PMD.EOL + PMD.EOL + " : 1" + PMD.EOL + "* warnings: 1" + PMD.EOL; + + "Summary:" + PMD.EOL + PMD.EOL + "* warnings: 1" + PMD.EOL; } @Override @@ -44,7 +44,7 @@ public class PapariTextRendererTest extends AbstractRendererTest { + " msg: blah" + PMD.EOL + " code: public class Foo {}" + PMD.EOL + PMD.EOL + " src: " + getSourceCodeFilename() + ":1:1" + PMD.EOL + " rule: Foo" + PMD.EOL + " msg: blah" + PMD.EOL + " code: public class Foo {}" + PMD.EOL + PMD.EOL + PMD.EOL + PMD.EOL + "Summary:" + PMD.EOL - + PMD.EOL + " : 2" + PMD.EOL + "* warnings: 2" + PMD.EOL; + + PMD.EOL + "* warnings: 2" + PMD.EOL; } @Override From ae9e416095b8926fcf91037a0c75e715a85fe452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Wed, 29 Jul 2020 00:08:46 +0200 Subject: [PATCH 6/6] Checkstyle --- .../java/net/sourceforge/pmd/properties/PropertyTypeId.java | 5 +---- .../main/java/net/sourceforge/pmd/util/CollectionUtil.java | 2 +- .../pmd/lang/java/rule/bestpractices/LooseCouplingRule.java | 5 ++++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java index 0ac9b4a361..7122fbb28a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java @@ -54,10 +54,7 @@ public enum PropertyTypeId { @Deprecated FLOAT_LIST("List[Float]", FloatMultiProperty.extractor(), ValueParserConstants.FLOAT_PARSER), DOUBLE("Double", DoubleProperty.extractor(), ValueParserConstants.DOUBLE_PARSER), - DOUBLE_LIST("List[Double]", DoubleMultiProperty.extractor(), ValueParserConstants.DOUBLE_PARSER), - // ENUM("Enum", EnumeratedProperty.FACTORY), // TODO:cf we need new syntax in the xml to support that - // ENUM_LIST("List[Enum]", EnumeratedMultiProperty.FACTORY), - ; + DOUBLE_LIST("List[Double]", DoubleMultiProperty.extractor(), ValueParserConstants.DOUBLE_PARSER); private static final Map CONSTANTS_BY_MNEMONIC; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java index 80498daf7c..d1077b49ac 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java @@ -53,7 +53,7 @@ public final class CollectionUtil { @SuppressWarnings("PMD.UnnecessaryFullyQualifiedName") public static final Set COLLECTION_INTERFACES_BY_NAMES = collectionTypes(List.class, Collection.class, Map.class, Set.class); - @SuppressWarnings( {"PMD.LooseCoupling", "PMD.UnnecessaryFullyQualifiedName"}) + @SuppressWarnings({"PMD.LooseCoupling", "PMD.UnnecessaryFullyQualifiedName"}) public static final Set COLLECTION_CLASSES_BY_NAMES = collectionTypes(ArrayList.class, java.util.LinkedList.class, java.util.Vector.class, HashMap.class, java.util.LinkedHashMap.class, java.util.TreeMap.class, java.util.TreeSet.class, diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java index b4081add3a..bb4fe662dc 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java @@ -5,6 +5,7 @@ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.Collection; +import java.util.Map; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; @@ -26,7 +27,9 @@ public class LooseCouplingRule extends AbstractJavaRule { return data; } Node parent = node.getNthParent(3); - boolean isType = TypeHelper.isA(node, Collection.class); + boolean isType = (TypeHelper.isA(node, Collection.class) || TypeHelper.isA(node, Map.class)) + && !(node.getType() != null && node.getType().isInterface()); + if (isType && (parent instanceof ASTFieldDeclaration || parent instanceof ASTFormalParameter || parent instanceof ASTResultType)) { addViolation(data, node, node.getImage());