This repository has been archived by the owner on Jul 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathAbstractProcessorMojo.java
528 lines (451 loc) · 18.2 KB
/
AbstractProcessorMojo.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*
* Copyright (c) 2009 Mysema Ltd.
* All rights reserved.
*
*/
package com.mysema.maven.apt;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.base.Joiner;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.Scanner;
import org.codehaus.plexus.util.StringUtils;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* Base class for AnnotationProcessorMojo implementations
*
* @author tiwe
*
*/
public abstract class AbstractProcessorMojo extends AbstractMojo {
private static final String JAVA_FILE_FILTER = "/*.java";
private static final String[] ALL_JAVA_FILES_FILTER = new String[] { "**" + JAVA_FILE_FILTER };
/**
* @component
*/
private BuildContext buildContext;
/**
* @parameter expression="${project}" readonly=true required=true
*/
private MavenProject project;
/**
* @parameter
*/
private String[] processors;
/**
* @parameter
*/
private String processor;
/**
* @parameter expression="${project.build.sourceEncoding}" required=true
*/
private String sourceEncoding;
/**
* @parameter
*/
private Map<String, String> options;
/**
* @parameter
*/
private Map<String, String> compilerOptions;
/**
* A list of inclusion package filters for the apt processor.
*
* If not specified all sources will be used for apt processor
*
* <pre>
* e.g.:
* <includes>
* <include>com.mypackge.**.bo.**</include>
* </includes>
* </pre>
*
* will include all files which match com/mypackge/ ** /bo/ ** / *.java
*
* @parameter
*/
private Set<String> includes = new HashSet<String>();
/**
* @parameter
*/
private boolean showWarnings = false;
/**
* @parameter
*/
private boolean logOnlyOnError = false;
/**
* @parameter expression="${plugin.artifacts}" readonly=true required=true
*/
private List<Artifact> pluginArtifacts;
/**
* A list of additional source roots for the apt processor
*
* @parameter required=false
*/
private List<String> additionalSourceRoots;
/**
* A list of additional test source roots for the apt processor
*
* @parameter required=false
*/
private List<String> additionalTestSourceRoots;
/**
* @parameter
*/
private boolean ignoreDelta = true;
@SuppressWarnings("unchecked")
private String buildCompileClasspath() {
List<String> pathElements = null;
try {
if (isForTest()) {
pathElements = project.getTestClasspathElements();
} else {
pathElements = project.getCompileClasspathElements();
}
} catch (DependencyResolutionRequiredException e) {
super.getLog().warn("exception calling getCompileClasspathElements", e);
return null;
}
if (pluginArtifacts != null) {
for (Artifact a : pluginArtifacts) {
if (a.getFile() != null) {
pathElements.add(a.getFile().getAbsolutePath());
}
}
}
if (pathElements.isEmpty()) {
return null;
}
StringBuilder result = new StringBuilder();
int i = 0;
for (i = 0; i < pathElements.size() - 1; ++i) {
result.append(pathElements.get(i)).append(File.pathSeparatorChar);
}
result.append(pathElements.get(i));
return result.toString();
}
private String buildProcessor() {
if (processors != null) {
StringBuilder result = new StringBuilder();
for (String processor : processors) {
if (result.length() > 0) {
result.append(",");
}
result.append(processor);
}
return result.toString();
} else if (processor != null) {
return processor;
} else {
String error = "Either processor or processors need to be given";
getLog().error(error);
throw new IllegalArgumentException(error);
}
}
private List<String> buildCompilerOptions(String processor, String compileClassPath,
String outputDirectory) throws IOException {
Map<String, String> compilerOpts = new LinkedHashMap<String, String>();
// Default options
compilerOpts.put("cp", compileClassPath);
if (sourceEncoding != null) {
compilerOpts.put("encoding", sourceEncoding);
}
compilerOpts.put("proc:only", null);
compilerOpts.put("processor", processor);
if (options != null) {
for (Map.Entry<String, String> entry : options.entrySet()) {
if (entry.getValue() != null) {
compilerOpts.put("A" + entry.getKey() + "=" + entry.getValue(), null);
} else {
compilerOpts.put("A" + entry.getKey() + "=", null);
}
}
}
if (outputDirectory != null) {
compilerOpts.put("s", outputDirectory);
}
if (!showWarnings) {
compilerOpts.put("nowarn", null);
}
StringBuilder builder = new StringBuilder();
for (File file : getSourceDirectories()) {
if (builder.length() > 0) {
builder.append(";");
}
builder.append(file.getCanonicalPath());
}
compilerOpts.put("sourcepath", builder.toString());
// User options override default options
if (compilerOptions != null) {
compilerOpts.putAll(compilerOptions);
}
List<String> opts = new ArrayList<String>(compilerOpts.size() * 2);
for (Map.Entry<String, String> compilerOption : compilerOpts.entrySet()) {
opts.add("-" + compilerOption.getKey());
String value = compilerOption.getValue();
if (StringUtils.isNotBlank(value)) {
opts.add(value);
}
}
return opts;
}
/**
* Filter files for apt processing based on the {@link #includes} filter and
* also taking into account m2e {@link BuildContext} to filter-out unchanged
* files when invoked as incremental build
*
* @param directories
* source directories in which files are located for apt processing
*
* @return files for apt processing. Returns empty set when there is no
* files to process
*/
private Set<File> filterFiles(Set<File> directories) {
String[] filters = ALL_JAVA_FILES_FILTER;
if (includes != null && !includes.isEmpty()) {
filters = includes.toArray(new String[includes.size()]);
for (int i = 0; i < filters.length; i++) {
filters[i] = filters[i].replace('.', '/') + JAVA_FILE_FILTER;
}
}
Set<File> files = new HashSet<File>();
for (File directory : directories) {
// support for incremental build in m2e context
Scanner scanner = buildContext.newScanner(directory, false);
scanner.setIncludes(filters);
scanner.scan();
String[] includedFiles = scanner.getIncludedFiles();
// check also for possible deletions
if (buildContext.isIncremental() && (includedFiles == null || includedFiles.length == 0)) {
scanner = buildContext.newDeleteScanner(directory);
scanner.setIncludes(filters);
scanner.scan();
includedFiles = scanner.getIncludedFiles();
}
// get all sources if ignoreDelta and at least one source file has changed
if (ignoreDelta && buildContext.isIncremental() && includedFiles != null && includedFiles.length > 0) {
scanner = buildContext.newScanner(directory, true);
scanner.setIncludes(filters);
scanner.scan();
includedFiles = scanner.getIncludedFiles();
}
if (includedFiles != null) {
for (String includedFile : includedFiles) {
files.add(new File(scanner.getBasedir(), includedFile));
}
}
}
return files;
}
/**
* Add messages through the buildContext:
* <ul>
* <li>cli build creates log output</li>
* <li>m2e build creates markers for eclipse</li>
* </ul>
* @param diagnostics
*/
private void processDiagnostics(final List<Diagnostic<? extends JavaFileObject>> diagnostics) {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
JavaFileObject javaFileObject = diagnostic.getSource();
if (javaFileObject != null) { // message was created without element parameter
File file = new File(javaFileObject.toUri().getPath());
Kind kind = diagnostic.getKind();
int lineNumber = (int) diagnostic.getLineNumber();
int columnNumber = (int) diagnostic.getColumnNumber();
String message = diagnostic.getMessage(Locale.getDefault());
switch (kind) {
case ERROR:
buildContext.addMessage(file, lineNumber, columnNumber, message, BuildContext.SEVERITY_ERROR, null);
break;
case WARNING:
case MANDATORY_WARNING:
buildContext.addMessage(file, lineNumber, columnNumber, message, BuildContext.SEVERITY_WARNING, null);
break;
case NOTE:
case OTHER:
default:
break;
}
}
}
}
public void execute() throws MojoExecutionException {
if (getOutputDirectory() == null) {
return;
}
if ("true".equals(System.getProperty("maven.apt.skip"))) {
return;
}
if (!getOutputDirectory().exists()) {
getOutputDirectory().mkdirs();
}
// make sure to add compileSourceRoots also during configuration build in m2e context
if (isForTest()) {
project.addTestCompileSourceRoot(getOutputDirectory().getAbsolutePath());
} else {
project.addCompileSourceRoot(getOutputDirectory().getAbsolutePath());
}
Set<File> sourceDirectories = getSourceDirectories();
getLog().debug("Using build context: " + buildContext);
StandardJavaFileManager fileManager = null;
try {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new MojoExecutionException("You need to run build with JDK or have tools.jar on the classpath."
+ "If this occures during eclipse build make sure you run eclipse under JDK as well");
}
Set<File> files = filterFiles(sourceDirectories);
if (files.isEmpty()) {
getLog().debug("No Java sources found (skipping)");
return;
}
fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files);
// clean all markers
for (JavaFileObject javaFileObject : compilationUnits1) {
buildContext.removeMessages(new File(javaFileObject.toUri().getPath()));
}
String compileClassPath = buildCompileClasspath();
String processor = buildProcessor();
String outputDirectory = getOutputDirectory().getPath();
File tempDirectory = null;
if (buildContext.isIncremental()) {
tempDirectory = new File(project.getBuild().getDirectory(), "apt"+System.currentTimeMillis());
tempDirectory.mkdirs();
outputDirectory = tempDirectory.getAbsolutePath();
}
List<String> compilerOptions = buildCompilerOptions(processor, compileClassPath, outputDirectory);
Writer out = null;
if (logOnlyOnError) {
out = new StringWriter();
}
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(out, fileManager, diagnosticCollector, compilerOptions, null, compilationUnits1);
Future<Boolean> future = executor.submit(task);
Boolean rv = future.get();
if (Boolean.FALSE.equals(rv) && logOnlyOnError) {
getLog().error(out.toString());
}
processDiagnostics(diagnosticCollector.getDiagnostics());
} finally {
executor.shutdown();
if (tempDirectory != null) {
FileSync.syncFiles(tempDirectory, getOutputDirectory());
FileUtils.deleteDirectory(tempDirectory);
}
}
buildContext.refresh(getOutputDirectory());
} catch (Exception e1) {
getLog().error("execute error", e1);
throw new MojoExecutionException(e1.getMessage(), e1);
} finally {
if (fileManager != null) {
try {
fileManager.close();
} catch (Exception e) {
getLog().warn("Unable to close fileManager", e);
}
}
}
}
protected abstract File getOutputDirectory();
@SuppressWarnings("unchecked")
protected Set<File> getSourceDirectories() {
File outputDirectory = getOutputDirectory();
String outputPath = outputDirectory.getAbsolutePath();
Set<File> directories = new HashSet<File>();
List<String> directoryNames = isForTest() ? getTestCompileSourceRoots()
: getCompileSourceRoots();
for (String name : directoryNames) {
File file = new File(name);
if (!file.getAbsolutePath().equals(outputPath) && file.exists() && file.isDirectory()) {
directories.add(file);
}
}
return directories;
}
private List<String> getTestCompileSourceRoots() {
@SuppressWarnings("unchecked")
final List<String> testCompileSourceRoots = project.getTestCompileSourceRoots();
if (additionalTestSourceRoots == null) {
return testCompileSourceRoots;
}
if (getLog().isDebugEnabled()) {
getLog().debug("Adding additional test source roots: " + Joiner.on(", ").skipNulls().join(additionalTestSourceRoots));
}
List<String> sourceRoots = new ArrayList<String>(testCompileSourceRoots);
sourceRoots.addAll(additionalTestSourceRoots);
return sourceRoots;
}
private List<String> getCompileSourceRoots() {
@SuppressWarnings("unchecked")
final List<String> compileSourceRoots = project.getCompileSourceRoots();
if (additionalSourceRoots == null) {
return compileSourceRoots;
}
if (getLog().isDebugEnabled()) {
getLog().debug("Adding additional source roots: " + Joiner.on(", ").skipNulls().join(additionalSourceRoots));
}
List<String> sourceRoots = new ArrayList<String>(compileSourceRoots);
sourceRoots.addAll(additionalSourceRoots);
return sourceRoots;
}
protected boolean isForTest() {
return false;
}
public void setBuildContext(BuildContext buildContext) {
this.buildContext = buildContext;
}
public void setProject(MavenProject project) {
this.project = project;
}
public void setProcessors(String[] processors) {
this.processors = processors;
}
public void setProcessor(String processor) {
this.processor = processor;
}
public void setSourceEncoding(String sourceEncoding) {
this.sourceEncoding = sourceEncoding;
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
public void setCompilerOptions(Map<String, String> compilerOptions) {
this.compilerOptions = compilerOptions;
}
public void setIncludes(Set<String> includes) {
this.includes = includes;
}
public void setShowWarnings(boolean showWarnings) {
this.showWarnings = showWarnings;
}
public void setLogOnlyOnError(boolean logOnlyOnError) {
this.logOnlyOnError = logOnlyOnError;
}
public void setPluginArtifacts(List<Artifact> pluginArtifacts) {
this.pluginArtifacts = pluginArtifacts;
}
}