1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 package com.qulice.pmd;
32
33 import com.jcabi.log.Logger;
34 import com.qulice.spi.Environment;
35 import java.io.File;
36 import java.nio.charset.Charset;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.LinkedList;
40 import net.sourceforge.pmd.PMDConfiguration;
41 import net.sourceforge.pmd.Report;
42 import net.sourceforge.pmd.RuleContext;
43 import net.sourceforge.pmd.RulePriority;
44 import net.sourceforge.pmd.util.datasource.DataSource;
45
46
47
48
49
50
51 @SuppressWarnings("deprecation")
52 final class SourceValidator {
53
54
55
56 private final RuleContext context;
57
58
59
60
61 private final PmdListener listener;
62
63
64
65
66
67 private final PmdRenderer renderer;
68
69
70
71
72 private final PMDConfiguration config;
73
74
75
76
77 private final Charset encoding;
78
79
80
81
82
83 SourceValidator(final Environment env) {
84 this.context = new RuleContext();
85 this.listener = new PmdListener(env);
86 this.renderer = new PmdRenderer();
87 this.config = new PMDConfiguration();
88 this.encoding = env.encoding();
89 }
90
91
92
93
94
95
96
97 @SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops", "PMD.CloseResource"})
98 public Collection<PmdError> validate(
99 final Collection<DataSource> sources, final String path) {
100 this.config.setRuleSets("com/qulice/pmd/ruleset.xml");
101 this.config.setThreads(0);
102 this.config.setMinimumPriority(RulePriority.LOW);
103 this.config.setIgnoreIncrementalAnalysis(true);
104 this.config.setShowSuppressedViolations(true);
105 this.config.setSourceEncoding(this.encoding.name());
106 final Report report = new Report();
107 report.addListener(this.listener);
108 this.context.setReport(report);
109 for (final DataSource source : sources) {
110 final String name = source.getNiceFileName(false, path);
111 Logger.debug(this, "Processing file: %s", name);
112 this.context.setSourceCodeFile(new File(name));
113 this.validateOne(source);
114 }
115 this.renderer.exportTo(report);
116 report.errors().forEachRemaining(this.listener::onProcessingError);
117 report.configErrors().forEachRemaining(this.listener::onConfigError);
118 Logger.debug(
119 this,
120 "got %d errors",
121 this.listener.errors().size()
122 );
123 return this.listener.errors();
124 }
125
126
127
128
129
130 private void validateOne(final DataSource source) {
131 final net.sourceforge.pmd.RuleSetFactory factory =
132 new net.sourceforge.pmd.RuleSetFactory(
133 new net.sourceforge.pmd.util.ResourceLoader(),
134 RulePriority.LOW,
135 false,
136 true
137 );
138 net.sourceforge.pmd.PMD.processFiles(
139 this.config,
140 factory,
141 new LinkedList<>(Collections.singleton(source)),
142 this.context,
143 Collections.singletonList(this.renderer)
144 );
145 }
146 }