1 package org.codehaus.mojo.jaxb2;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.plugin.AbstractMojo;
23 import org.apache.maven.plugin.MojoExecution;
24 import org.apache.maven.plugin.MojoExecutionException;
25 import org.apache.maven.plugin.MojoFailureException;
26 import org.apache.maven.plugin.logging.Log;
27 import org.apache.maven.plugins.annotations.Component;
28 import org.apache.maven.plugins.annotations.Parameter;
29 import org.apache.maven.project.MavenProject;
30 import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities;
31 import org.codehaus.mojo.jaxb2.shared.Validate;
32 import org.codehaus.mojo.jaxb2.shared.environment.EnvironmentFacet;
33 import org.codehaus.mojo.jaxb2.shared.filters.Filter;
34 import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter;
35 import org.codehaus.mojo.jaxb2.shared.version.DependencyInfo;
36 import org.codehaus.mojo.jaxb2.shared.version.DependsFileParser;
37 import org.sonatype.plexus.build.incremental.BuildContext;
38
39 import java.io.File;
40 import java.io.IOException;
41 import java.net.URL;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.List;
46 import java.util.Locale;
47 import java.util.Map;
48 import java.util.SortedMap;
49 import java.util.TreeMap;
50 import java.util.regex.Pattern;
51
52
53
54
55
56
57
58 public abstract class AbstractJaxbMojo extends AbstractMojo {
59
60
61
62
63 public static final String STANDARD_EPISODE_FILENAME = "sun-jaxb.episode";
64
65
66
67
68
69 public static final String PACKAGE_INFO_FILENAME = "package-info.java";
70
71
72
73
74 public static final String NEWLINE = System.getProperty("line.separator");
75
76
77
78
79 public static final Pattern CONTAINS_WHITESPACE = Pattern.compile("(\\S*\\s+\\S*)+", Pattern.UNICODE_CASE);
80
81
82
83
84
85 public static final List<Filter<File>> STANDARD_EXCLUDE_FILTERS;
86
87 private static final List<String> RELEVANT_GROUPIDS =
88 Arrays.asList("org.glassfish.jaxb", "javax.xml.bind");
89 private static final String OWN_ARTIFACT_ID = "jaxb2-maven-plugin";
90 private static final String SYSTEM_FILE_ENCODING_PROPERTY = "file.encoding";
91 private static final String[] STANDARD_EXCLUDE_SUFFIXES = {"README.*", "\\.xml", "\\.txt"};
92
93 static {
94
95
96 final List<Filter<File>> tmp = new ArrayList<Filter<File>>();
97 tmp.add(new PatternFileFilter(Arrays.asList(STANDARD_EXCLUDE_SUFFIXES), true));
98
99
100 STANDARD_EXCLUDE_FILTERS = Collections.unmodifiableList(tmp);
101 }
102
103
104
105
106
107 @Component
108 private BuildContext buildContext;
109
110
111
112
113 @Parameter(defaultValue = "${project}", readonly = true)
114 private MavenProject project;
115
116
117
118
119
120
121
122 @Parameter(defaultValue = "${mojoExecution}", readonly = true)
123 private MojoExecution execution;
124
125
126
127
128
129
130
131
132
133
134 @Parameter(defaultValue = "${project.build.directory}/jaxb2", readonly = true, required = true)
135 protected File staleFileDirectory;
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152 @Parameter(defaultValue = "${project.build.sourceEncoding}")
153 private String encoding;
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175 @Parameter(required = false)
176 protected String locale;
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 @Parameter(required = false)
203 protected List<EnvironmentFacet> extraFacets;
204
205
206
207
208
209
210
211 protected final BuildContext getBuildContext() {
212 return getInjectedObject(buildContext, "buildContext");
213 }
214
215
216
217
218 protected final MavenProject getProject() {
219 return getInjectedObject(project, "project");
220 }
221
222
223
224
225 public MojoExecution getExecution() {
226 return getInjectedObject(execution, "execution");
227 }
228
229
230
231
232 @Override
233 public final void execute() throws MojoExecutionException, MojoFailureException {
234
235
236 final Log log = getLog();
237 final boolean isDebugEnabled = log.isDebugEnabled();
238 final boolean isInfoEnabled = log.isInfoEnabled();
239
240
241 if (shouldExecutionBeSkipped()) {
242
243 if (isDebugEnabled) {
244 log.debug("Skipping execution, as instructed.");
245 }
246 return;
247 }
248
249
250 if (isDebugEnabled) {
251 logPluginAndJaxbDependencyInfo();
252 }
253
254
255 if (isReGenerationRequired()) {
256
257 if (performExecution()) {
258
259
260
261 updateStaleFileTimestamp();
262
263
264 buildContext.refresh(getOutputDirectory());
265
266 } else if (isInfoEnabled) {
267 log.info("Not updating staleFile timestamp as instructed.");
268 }
269 } else if (isInfoEnabled) {
270 log.info("No changes detected in schema or binding files - skipping JAXB generation.");
271 }
272
273
274 if(getOutputDirectory().exists() && getOutputDirectory().isDirectory()) {
275
276 final String canonicalPathToOutputDirectory = FileSystemUtilities.getCanonicalPath(getOutputDirectory());
277
278 if(log.isDebugEnabled()) {
279 log.debug("Adding existing JAXB outputDirectory [" + canonicalPathToOutputDirectory
280 + "] to Maven's sources.");
281 }
282
283
284 getProject().addCompileSourceRoot(canonicalPathToOutputDirectory);
285 }
286 }
287
288
289
290
291
292
293 protected abstract boolean shouldExecutionBeSkipped();
294
295
296
297
298
299 protected abstract boolean isReGenerationRequired();
300
301
302
303
304
305
306
307
308
309
310
311 protected abstract boolean performExecution() throws MojoExecutionException, MojoFailureException;
312
313
314
315
316
317
318
319
320 protected abstract List<URL> getSources();
321
322
323
324
325
326
327 protected abstract File getOutputDirectory();
328
329
330
331
332
333
334
335
336
337 protected abstract List<String> getClasspath() throws MojoExecutionException;
338
339
340
341
342
343
344
345
346 @SuppressWarnings("all")
347 protected void warnAboutIncorrectPluginConfiguration(final String propertyName, final String description) {
348
349 final StringBuilder builder = new StringBuilder();
350 builder.append("\n+=================== [Incorrect Plugin Configuration Detected]\n");
351 builder.append("|\n");
352 builder.append("| Property : " + propertyName + "\n");
353 builder.append("| Problem : " + description + "\n");
354 builder.append("|\n");
355 builder.append("+=================== [End Incorrect Plugin Configuration Detected]\n\n");
356 getLog().warn(builder.toString().replace("\n", NEWLINE));
357 }
358
359
360
361
362
363
364 protected final String[] logAndReturnToolArguments(final String[] arguments, final String toolName) {
365
366
367 Validate.notNull(arguments, "arguments");
368
369 if (getLog().isDebugEnabled()) {
370
371 final StringBuilder argBuilder = new StringBuilder();
372 argBuilder.append("\n+=================== [" + arguments.length + " " + toolName + " Arguments]\n");
373 argBuilder.append("|\n");
374 for (int i = 0; i < arguments.length; i++) {
375 argBuilder.append("| [").append(i).append("]: ").append(arguments[i]).append("\n");
376 }
377 argBuilder.append("|\n");
378 argBuilder.append("+=================== [End " + arguments.length + " " + toolName + " Arguments]\n\n");
379 getLog().debug(argBuilder.toString().replace("\n", NEWLINE));
380 }
381
382
383 return arguments;
384 }
385
386
387
388
389
390
391
392
393
394 protected abstract String getStaleFileName();
395
396
397
398
399
400
401 protected final File getStaleFile() {
402 final String staleFileName = "."
403 + (getExecution() == null ? "nonExecutionJaxb" : getExecution().getExecutionId())
404 + "-" + getStaleFileName();
405 return new File(staleFileDirectory, staleFileName);
406 }
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424 protected final String getEncoding(final boolean warnIfConfiguredEncodingDiffersFromFileEncoding) {
425
426
427 final boolean configuredEncoding = encoding != null;
428 final String fileEncoding = System.getProperty(SYSTEM_FILE_ENCODING_PROPERTY);
429 final String effectiveEncoding = configuredEncoding ? encoding : fileEncoding;
430
431
432 if (warnIfConfiguredEncodingDiffersFromFileEncoding
433 && !fileEncoding.equalsIgnoreCase(effectiveEncoding)
434 && getLog().isWarnEnabled()) {
435 getLog().warn("Configured encoding [" + effectiveEncoding
436 + "] differs from encoding given in system property '" + SYSTEM_FILE_ENCODING_PROPERTY
437 + "' [" + fileEncoding + "]");
438 }
439
440 if (getLog().isDebugEnabled()) {
441 getLog().debug("Using " + (configuredEncoding ? "explicitly configured" : "system property")
442 + " encoding [" + effectiveEncoding + "]");
443 }
444
445
446 return effectiveEncoding;
447 }
448
449
450
451
452
453
454
455
456
457
458 protected File getEpisodeFile(final String customEpisodeFileName) throws MojoExecutionException {
459
460
461 final String effectiveEpisodeFileName = customEpisodeFileName == null
462 ? "sun-jaxb.episode"
463 : customEpisodeFileName;
464 Validate.notEmpty(effectiveEpisodeFileName, "effectiveEpisodeFileName");
465
466
467 final File generatedMetaInfDirectory = new File(getOutputDirectory(), "META-INF");
468
469 if (!generatedMetaInfDirectory.exists()) {
470
471 FileSystemUtilities.createDirectory(generatedMetaInfDirectory, false);
472 if (getLog().isDebugEnabled()) {
473 getLog().debug("Created episode directory ["
474 + FileSystemUtilities.getCanonicalPath(generatedMetaInfDirectory) + "]: "
475 + generatedMetaInfDirectory.exists());
476 }
477 }
478
479
480 return new File(generatedMetaInfDirectory, effectiveEpisodeFileName);
481 }
482
483
484
485
486
487 private void logPluginAndJaxbDependencyInfo() {
488
489 if (getLog().isDebugEnabled()) {
490 final StringBuilder builder = new StringBuilder();
491 builder.append("\n+=================== [Brief Plugin Build Dependency Information]\n");
492 builder.append("|\n");
493 builder.append("| Note: These dependencies pertain to what was used to build *the plugin*.\n");
494 builder.append("| Check project dependencies to see the ones used in *your build*.\n");
495 builder.append("|\n");
496
497
498 final SortedMap<String, String> versionMap = DependsFileParser.getVersionMap(OWN_ARTIFACT_ID);
499
500 builder.append("|\n");
501 builder.append("| Plugin's own information\n");
502 builder.append("| GroupId : " + versionMap.get(DependsFileParser.OWN_GROUPID_KEY) + "\n");
503 builder.append("| ArtifactID : " + versionMap.get(DependsFileParser.OWN_ARTIFACTID_KEY) + "\n");
504 builder.append("| Version : " + versionMap.get(DependsFileParser.OWN_VERSION_KEY) + "\n");
505 builder.append("| Buildtime : " + versionMap.get(DependsFileParser.BUILDTIME_KEY) + "\n");
506 builder.append("|\n");
507 builder.append("| Plugin's JAXB-related dependencies\n");
508 builder.append("|\n");
509
510 final SortedMap<String, DependencyInfo> diMap = DependsFileParser.createDependencyInfoMap(versionMap);
511
512 int dependencyIndex = 0;
513 for (Map.Entry<String, DependencyInfo> current : diMap.entrySet()) {
514
515 final String key = current.getKey().trim();
516 for (String currentRelevantGroupId : RELEVANT_GROUPIDS) {
517 if (key.startsWith(currentRelevantGroupId)) {
518
519 final DependencyInfo di = current.getValue();
520 builder.append("| " + (++dependencyIndex) + ") [" + di.getArtifactId() + "]\n");
521 builder.append("| GroupId : " + di.getGroupId() + "\n");
522 builder.append("| ArtifactID : " + di.getArtifactId() + "\n");
523 builder.append("| Version : " + di.getVersion() + "\n");
524 builder.append("| Scope : " + di.getScope() + "\n");
525 builder.append("| Type : " + di.getType() + "\n");
526 builder.append("|\n");
527 }
528 }
529 }
530
531 builder.append("+=================== [End Brief Plugin Build Dependency Information]\n\n");
532 getLog().debug(builder.toString().replace("\n", NEWLINE));
533 }
534 }
535
536 private <T> T getInjectedObject(final T objectOrNull, final String objectName) {
537
538 if (objectOrNull == null) {
539 getLog().error(
540 "Found null '" + objectName + "', implying that Maven @Component injection was not done properly.");
541 }
542
543 return objectOrNull;
544 }
545
546 private void updateStaleFileTimestamp() throws MojoExecutionException {
547
548 final File staleFile = getStaleFile();
549 if (!staleFile.exists()) {
550
551
552 FileSystemUtilities.createDirectory(staleFile.getParentFile(), false);
553
554 try {
555 staleFile.createNewFile();
556
557 if (getLog().isDebugEnabled()) {
558 getLog().debug("Created staleFile [" + FileSystemUtilities.getCanonicalPath(staleFile) + "]");
559 }
560 } catch (IOException e) {
561 throw new MojoExecutionException("Could not create staleFile.", e);
562 }
563
564 } else {
565 if (!staleFile.setLastModified(System.currentTimeMillis())) {
566 getLog().warn("Failed updating modification time of staleFile ["
567 + FileSystemUtilities.getCanonicalPath(staleFile) + "]");
568 }
569 }
570 }
571
572
573
574
575 protected void logSystemPropertiesAndBasedir() {
576 if (getLog().isDebugEnabled()) {
577
578 final StringBuilder builder = new StringBuilder();
579
580 builder.append("\n+=================== [System properties]\n");
581 builder.append("|\n");
582
583
584 final SortedMap<String, Object> props = new TreeMap<String, Object>();
585 props.put("basedir", FileSystemUtilities.getCanonicalPath(getProject().getBasedir()));
586
587 for (Map.Entry<Object, Object> current : System.getProperties().entrySet()) {
588 props.put("" + current.getKey(), current.getValue());
589 }
590 for (Map.Entry<String, Object> current : props.entrySet()) {
591 builder.append("| [" + current.getKey() + "]: " + current.getValue() + "\n");
592 }
593
594 builder.append("|\n");
595 builder.append("+=================== [End System properties]\n");
596
597
598 getLog().debug(builder.toString().replace("\n", NEWLINE));
599 }
600 }
601 }