1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.plugins.pmd;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.Locale;
27
28 import net.sourceforge.pmd.renderers.Renderer;
29 import org.apache.maven.model.Dependency;
30 import org.apache.maven.plugins.annotations.Component;
31 import org.apache.maven.plugins.annotations.Mojo;
32 import org.apache.maven.plugins.annotations.Parameter;
33 import org.apache.maven.plugins.annotations.ResolutionScope;
34 import org.apache.maven.plugins.pmd.exec.PmdExecutor;
35 import org.apache.maven.plugins.pmd.exec.PmdRequest;
36 import org.apache.maven.plugins.pmd.exec.PmdResult;
37 import org.apache.maven.project.DefaultProjectBuildingRequest;
38 import org.apache.maven.project.MavenProject;
39 import org.apache.maven.project.ProjectBuildingRequest;
40 import org.apache.maven.reporting.MavenReportException;
41 import org.apache.maven.shared.artifact.filter.resolve.AndFilter;
42 import org.apache.maven.shared.artifact.filter.resolve.ExclusionsFilter;
43 import org.apache.maven.shared.artifact.filter.resolve.ScopeFilter;
44 import org.apache.maven.shared.artifact.filter.resolve.TransformableFilter;
45 import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResult;
46 import org.apache.maven.shared.transfer.dependencies.resolve.DependencyResolver;
47 import org.apache.maven.toolchain.Toolchain;
48 import org.codehaus.plexus.i18n.I18N;
49 import org.codehaus.plexus.resource.ResourceManager;
50 import org.codehaus.plexus.resource.loader.FileResourceCreationException;
51 import org.codehaus.plexus.resource.loader.FileResourceLoader;
52 import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
53 import org.codehaus.plexus.util.StringUtils;
54
55
56
57
58
59
60
61
62
63 @Mojo(name = "pmd", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST)
64 public class PmdReport extends AbstractPmdReport {
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80 @Parameter(property = "targetJdk", defaultValue = "${maven.compiler.source}")
81 private String targetJdk;
82
83
84
85
86
87
88
89 @Parameter(defaultValue = "java")
90 private String language;
91
92
93
94
95
96
97 @Parameter(property = "minimumPriority", defaultValue = "5")
98 private int minimumPriority = 5;
99
100
101
102
103
104
105 @Parameter(property = "pmd.skip", defaultValue = "false")
106 private boolean skip;
107
108
109
110
111
112
113
114
115 @Parameter
116 String[] rulesets = new String[] {"/rulesets/java/maven-pmd-plugin-default.xml"};
117
118
119
120
121
122
123
124 @Parameter(property = "pmd.typeResolution", defaultValue = "true")
125 private boolean typeResolution;
126
127
128
129
130
131
132 @Parameter(property = "pmd.benchmark", defaultValue = "false")
133 private boolean benchmark;
134
135
136
137
138
139
140 @Parameter(property = "pmd.benchmarkOutputFilename", defaultValue = "${project.build.directory}/pmd-benchmark.txt")
141 private String benchmarkOutputFilename;
142
143
144
145
146
147
148
149
150 @Parameter(property = "pmd.suppressMarker")
151 private String suppressMarker;
152
153
154
155
156
157
158 @Parameter(property = "pmd.skipPmdError", defaultValue = "true")
159 private boolean skipPmdError;
160
161
162
163
164
165
166
167
168
169 @Parameter(property = "pmd.analysisCache", defaultValue = "false")
170 private boolean analysisCache;
171
172
173
174
175
176
177
178
179
180
181 @Parameter(property = "pmd.analysisCacheLocation", defaultValue = "${project.build.directory}/pmd/pmd.cache")
182 private String analysisCacheLocation;
183
184
185
186
187
188
189
190
191
192
193 @Parameter(property = "pmd.renderProcessingErrors", defaultValue = "true")
194 private boolean renderProcessingErrors = true;
195
196
197
198
199
200
201 @Parameter(property = "pmd.renderRuleViolationPriority", defaultValue = "true")
202 private boolean renderRuleViolationPriority = true;
203
204
205
206
207
208
209
210 @Parameter(property = "pmd.renderViolationsByPriority", defaultValue = "true")
211 private boolean renderViolationsByPriority = true;
212
213
214
215
216
217
218 @Parameter(property = "pmd.renderSuppressedViolations", defaultValue = "true")
219 private boolean renderSuppressedViolations = true;
220
221
222
223
224
225
226
227 @Parameter(property = "pmd.rulesetsTargetDirectory", defaultValue = "${project.build.directory}/pmd/rulesets")
228 private File rulesetsTargetDirectory;
229
230
231
232
233
234 @Component
235 private ResourceManager locator;
236
237 @Component
238 private DependencyResolver dependencyResolver;
239
240
241
242
243 @Component
244 private I18N i18n;
245
246
247
248
249
250
251 private PmdResult pmdResult;
252
253
254 public String getName(Locale locale) {
255 return getI18nString(locale, "name");
256 }
257
258
259 public String getDescription(Locale locale) {
260 return getI18nString(locale, "description");
261 }
262
263
264
265
266
267
268 protected String getI18nString(Locale locale, String key) {
269 return i18n.getString("pmd-report", locale, "report.pmd." + key);
270 }
271
272
273
274
275
276
277
278
279 public void setRulesets(String[] rulesets) {
280 this.rulesets = Arrays.copyOf(rulesets, rulesets.length);
281 }
282
283
284
285
286 @Override
287 public void executeReport(Locale locale) throws MavenReportException {
288 ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
289 try {
290 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
291
292 PmdReportRenderer r = new PmdReportRenderer(
293 getLog(),
294 getSink(),
295 i18n,
296 locale,
297 filesToProcess,
298 pmdResult.getViolations(),
299 renderRuleViolationPriority,
300 renderViolationsByPriority,
301 isAggregator());
302 if (renderSuppressedViolations) {
303 r.setSuppressedViolations(pmdResult.getSuppressedViolations());
304 }
305 if (renderProcessingErrors) {
306 r.setProcessingErrors(pmdResult.getErrors());
307 }
308
309 r.render();
310 } finally {
311 Thread.currentThread().setContextClassLoader(origLoader);
312 }
313 }
314
315 @Override
316 public boolean canGenerateReport() throws MavenReportException {
317 if (skip) {
318 return false;
319 }
320
321 boolean result = canGenerateReportInternal();
322 if (result) {
323 executePmd();
324 if (skipEmptyReport) {
325 result = pmdResult.hasViolations();
326 }
327 }
328 return result;
329 }
330
331 private void executePmd() throws MavenReportException {
332 if (pmdResult != null) {
333
334 getLog().debug("PMD has already been run - skipping redundant execution.");
335 return;
336 }
337
338 try {
339 filesToProcess = getFilesToProcess();
340
341 if (filesToProcess.isEmpty() && !"java".equals(language)) {
342 getLog().warn("No files found to process. Did you forget to add additional source directories?"
343 + " (see also build-helper-maven-plugin)");
344 }
345 } catch (IOException e) {
346 throw new MavenReportException("Can't get file list", e);
347 }
348
349 PmdRequest request = new PmdRequest();
350 request.setLanguageAndVersion(language, targetJdk);
351 request.setRulesets(resolveRulesets());
352 request.setAuxClasspath(typeResolution ? determineAuxClasspath() : null);
353 request.setSourceEncoding(getInputEncoding());
354 request.addFiles(filesToProcess.keySet());
355 request.setMinimumPriority(minimumPriority);
356 request.setSuppressMarker(suppressMarker);
357 request.setBenchmarkOutputLocation(benchmark ? benchmarkOutputFilename : null);
358 request.setAnalysisCacheLocation(analysisCache ? analysisCacheLocation : null);
359 request.setExcludeFromFailureFile(excludeFromFailureFile);
360 request.setTargetDirectory(targetDirectory.getAbsolutePath());
361 request.setOutputEncoding(getOutputEncoding());
362 request.setFormat(format);
363 request.setSkipPmdError(skipPmdError);
364 request.setIncludeXmlInReports(includeXmlInReports);
365 request.setReportOutputDirectory(getReportOutputDirectory().getAbsolutePath());
366 request.setLogLevel(determineCurrentRootLogLevel());
367
368 Toolchain tc = getToolchain();
369 if (tc != null) {
370 getLog().info("Toolchain in maven-pmd-plugin: " + tc);
371 String javaExecutable = tc.findTool("java");
372 request.setJavaExecutable(javaExecutable);
373 }
374
375 getLog().info("PMD version: " + AbstractPmdReport.getPmdVersion());
376 pmdResult = PmdExecutor.execute(request);
377 }
378
379
380
381
382
383
384
385 private List<String> resolveRulesets() throws MavenReportException {
386
387
388 locator.addSearchPath(
389 FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());
390
391 locator.addSearchPath(FileResourceLoader.ID, project.getBasedir().getAbsolutePath());
392
393
394 locator.addSearchPath(FileResourceLoader.ID, session.getRequest().getBaseDirectory());
395 locator.setOutputDirectory(rulesetsTargetDirectory);
396
397 String[] sets = new String[rulesets.length];
398 try {
399 for (int idx = 0; idx < rulesets.length; idx++) {
400 String set = rulesets[idx];
401 getLog().debug("Preparing ruleset: " + set);
402 String rulesetFilename = determineRulesetFilename(set);
403 File ruleset = locator.getResourceAsFile(rulesetFilename, getLocationTemp(set, idx + 1));
404 if (null == ruleset) {
405 throw new MavenReportException("Could not resolve " + set);
406 }
407 sets[idx] = ruleset.getAbsolutePath();
408 }
409 } catch (ResourceNotFoundException | FileResourceCreationException e) {
410 throw new MavenReportException(e.getMessage(), e);
411 }
412 return Arrays.asList(sets);
413 }
414
415 private String determineRulesetFilename(String ruleset) {
416 String result = ruleset.trim();
417 String lowercase = result.toLowerCase(Locale.ROOT);
418 if (lowercase.startsWith("http://") || lowercase.startsWith("https://") || lowercase.endsWith(".xml")) {
419 return result;
420 }
421
422
423 if (result.indexOf('/') > -1) {
424 String rulesetFilename = result.substring(0, result.lastIndexOf('/'));
425 if (rulesetFilename.toLowerCase(Locale.ROOT).endsWith(".xml")) {
426 return rulesetFilename;
427 }
428 }
429
430 int dashIndex = lowercase.indexOf('-');
431 if (dashIndex > -1 && lowercase.indexOf('-', dashIndex + 1) == -1) {
432 String language = result.substring(0, dashIndex);
433 String rulesetName = result.substring(dashIndex + 1);
434 return "rulesets/" + language + "/" + rulesetName + ".xml";
435 }
436
437 return result;
438 }
439
440
441
442
443
444
445
446
447 protected String getLocationTemp(String name, int position) {
448 String loc = name;
449 if (loc.indexOf('/') != -1) {
450 loc = loc.substring(loc.lastIndexOf('/') + 1);
451 }
452 if (loc.indexOf('\\') != -1) {
453 loc = loc.substring(loc.lastIndexOf('\\') + 1);
454 }
455
456
457
458
459
460 loc = loc.replaceAll("[\\?\\:\\&\\=\\%]", "_");
461
462 if (loc.endsWith(".xml")) {
463 loc = loc.substring(0, loc.length() - 4);
464 }
465 loc = String.format("%03d-%s.xml", position, loc);
466
467 getLog().debug("Before: " + name + " After: " + loc);
468 return loc;
469 }
470
471 private String determineAuxClasspath() throws MavenReportException {
472 try {
473 List<String> classpath = new ArrayList<>();
474 if (isAggregator()) {
475 List<String> dependencies = new ArrayList<>();
476
477
478
479
480 List<String> exclusionPatterns = new ArrayList<>();
481 for (MavenProject localProject : getAggregatedProjects()) {
482 exclusionPatterns.add(localProject.getGroupId() + ":" + localProject.getArtifactId());
483 }
484 TransformableFilter filter = new AndFilter(Arrays.asList(
485 new ExclusionsFilter(exclusionPatterns),
486 includeTests
487 ? ScopeFilter.including("compile", "provided", "test")
488 : ScopeFilter.including("compile", "provided")));
489
490 for (MavenProject localProject : getAggregatedProjects()) {
491 ProjectBuildingRequest buildingRequest =
492 new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
493
494 buildingRequest.getRemoteRepositories().addAll(localProject.getRemoteArtifactRepositories());
495
496 List<Dependency> managedDependencies = localProject.getDependencyManagement() == null
497 ? null
498 : localProject.getDependencyManagement().getDependencies();
499 Iterable<ArtifactResult> resolvedDependencies = dependencyResolver.resolveDependencies(
500 buildingRequest, localProject.getDependencies(), managedDependencies, filter);
501
502 for (ArtifactResult resolvedArtifact : resolvedDependencies) {
503 dependencies.add(
504 resolvedArtifact.getArtifact().getFile().toString());
505 }
506
507
508 classpath.addAll(
509 includeTests
510 ? localProject.getTestClasspathElements()
511 : localProject.getCompileClasspathElements());
512 }
513
514
515 classpath.addAll(dependencies);
516
517 getLog().debug("Using aggregated aux classpath: " + classpath);
518 } else {
519 classpath.addAll(
520 includeTests ? project.getTestClasspathElements() : project.getCompileClasspathElements());
521
522 getLog().debug("Using aux classpath: " + classpath);
523 }
524 String path = StringUtils.join(classpath.iterator(), File.pathSeparator);
525 return path;
526 } catch (Exception e) {
527 throw new MavenReportException(e.getMessage(), e);
528 }
529 }
530
531
532
533
534 @Override
535 public String getOutputName() {
536 return "pmd";
537 }
538
539
540
541
542
543
544
545
546 @Deprecated
547 public final Renderer createRenderer() throws MavenReportException {
548 return PmdExecutor.createRenderer(format, getOutputEncoding());
549 }
550 }