View Javadoc
1   package org.codehaus.mojo.jaxb2;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
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   * Abstract Mojo which collects common infrastructure, required and needed
54   * by all subclass Mojos in the JAXB2 maven plugin codebase.
55   *
56   * @author <a href="mailto:lj@jguru.se">Lennart J&ouml;relid</a>
57   */
58  public abstract class AbstractJaxbMojo extends AbstractMojo {
59  
60      /**
61       * Standard name of the generated JAXB episode file.
62       */
63      public static final String STANDARD_EPISODE_FILENAME = "sun-jaxb.episode";
64  
65      /**
66       * Standard name of the package-info.java file which may contain
67       * JAXB annotations and Package JavaDoc.
68       */
69      public static final String PACKAGE_INFO_FILENAME = "package-info.java";
70  
71      /**
72       * Platform-independent newline control string.
73       */
74      public static final String NEWLINE = System.getProperty("line.separator");
75  
76      /**
77       * Pattern matching strings containing whitespace (or consisting only of whitespace).
78       */
79      public static final Pattern CONTAINS_WHITESPACE = Pattern.compile("(\\S*\\s+\\S*)+", Pattern.UNICODE_CASE);
80  
81      /**
82       * Standard excludes Filters for all Java generator Mojos.
83       * The List is unmodifiable.
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          // The standard exclude filters contain simple, exclude pattern filters.
96          final List<Filter<File>> tmp = new ArrayList<Filter<File>>();
97          tmp.add(new PatternFileFilter(Arrays.asList(STANDARD_EXCLUDE_SUFFIXES), true));
98  
99          // Make STANDARD_EXCLUDE_FILTERS be unmodifiable.
100         STANDARD_EXCLUDE_FILTERS = (List<Filter<File>>) Collections.unmodifiableList(tmp);
101     }
102 
103     /**
104      * The Plexus BuildContext is used to identify files or directories modified since last build,
105      * implying functionality used to define if java generation must be performed again.
106      */
107     @Component
108     private BuildContext buildContext;
109 
110     /**
111      * The injected Maven project.
112      */
113     @Parameter(defaultValue = "${project}", readonly = true)
114     private MavenProject project;
115 
116     /**
117      * Note that the execution parameter will be injected ONLY if this plugin is executed as part
118      * of a maven standard lifecycle - as opposed to directly invoked with a direct invocation.
119      * When firing this mojo directly (i.e. {@code mvn xjc:something} or {@code mvn schemagen:something}), the
120      * {@code execution} object will not be injected.
121      */
122     @Parameter(defaultValue = "${mojoExecution}", readonly = true)
123     private MojoExecution execution;
124 
125     /**
126      * <p>The directory where the staleFile is found.
127      * The staleFile assists in determining if re-generation of JAXB build products is required.</p>
128      * <p>While it is permitted to re-define the staleFileDirectory, it is recommended to keep it
129      * below the <code>${project.build.directory}</code>, to ensure that JAXB code or XSD re-generation
130      * occurs after cleaning the project.</p>
131      *
132      * @since 2.0
133      */
134     @Parameter(defaultValue = "${project.build.directory}/jaxb2", readonly = true, required = true)
135     protected File staleFileDirectory;
136 
137     /**
138      * <p>Defines the encoding used by XJC (for generating Java Source files) and schemagen (for generating XSDs).
139      * The corresponding argument parameter for XJC and SchemaGen is: {@code encoding}.</p>
140      * <p>The algorithm for finding the encoding to use is as follows
141      * (where the first non-null value found is used for encoding):
142      * <ol>
143      * <li>If the configuration property is explicitly given within the plugin's configuration, use that value.</li>
144      * <li>If the Maven property <code>project.build.sourceEncoding</code> is defined, use its value.</li>
145      * <li>Otherwise use the value from the system property <code>file.encoding</code>.</li>
146      * </ol>
147      * </p>
148      *
149      * @see #getEncoding(boolean)
150      * @since 2.0
151      */
152     @Parameter(defaultValue = "${project.build.sourceEncoding}")
153     private String encoding;
154 
155     /**
156      * <p>A Locale definition to create and set the system (default) Locale when the XJB or SchemaGen tools executes.
157      * The Locale will be reset to its default value after the execution of XJC or SchemaGen is complete.</p>
158      * <p>The configuration parameter must be supplied on the form {@code language[,country[,variant]]},
159      * such as {@code sv,SE} or {@code fr}. Refer to
160      * {@code org.codehaus.mojo.jaxb2.shared.environment.locale.LocaleFacet.createFor(String, Log)} for further
161      * information.</p>
162      * <p><strong>Example</strong> (assigns french locale):</p>
163      * <pre>
164      *     <code>
165      *         &lt;configuration&gt;
166      *              &lt;locale&gt;fr&lt;/locale&gt;
167      *         &lt;/configuration&gt;
168      *     </code>
169      * </pre>
170      *
171      * @see org.codehaus.mojo.jaxb2.shared.environment.locale.LocaleFacet#createFor(String, Log)
172      * @see Locale#getAvailableLocales()
173      * @since 2.2
174      */
175     @Parameter(required = false)
176     protected String locale;
177 
178     /**
179      * <p>Defines a set of extra EnvironmentFacet instances which are used to further configure the
180      * ToolExecutionEnvironment used by this plugin to fire XJC or SchemaGen.</p>
181      * <p><em>Example:</em> If you implement the EnvironmentFacet interface in the class
182      * {@code org.acme.MyCoolEnvironmentFacetImplementation}, its {@code setup()} method is called before the
183      * XJC or SchemaGen tools are executed to setup some facet of their Execution environment. Correspondingly, the
184      * {@code restore()} method in your {@code org.acme.MyCoolEnvironmentFacetImplementation} class is invoked after
185      * the XJC or SchemaGen execution terminates.</p>
186      * <pre>
187      *     <code>
188      *         &lt;configuration&gt;
189      *         ...
190      *              &lt;extraFacets&gt;
191      *                  &lt;extraFacet implementation="org.acme.MyCoolEnvironmentFacetImplementation" /&gt;
192      *              &lt;/extraFacets&gt;
193      *         ...
194      *         &lt;/configuration&gt;
195      *     </code>
196      * </pre>
197      *
198      * @see EnvironmentFacet
199      * @see org.codehaus.mojo.jaxb2.shared.environment.ToolExecutionEnvironment#add(EnvironmentFacet)
200      * @since 2.2
201      */
202     @Parameter(required = false)
203     protected List<EnvironmentFacet> extraFacets;
204 
205     /**
206      * The Plexus BuildContext is used to identify files or directories modified since last build,
207      * implying functionality used to define if java generation must be performed again.
208      *
209      * @return the active Plexus BuildContext.
210      */
211     protected final BuildContext getBuildContext() {
212         return getInjectedObject(buildContext, "buildContext");
213     }
214 
215     /**
216      * @return The active MavenProject.
217      */
218     protected final MavenProject getProject() {
219         return getInjectedObject(project, "project");
220     }
221 
222     /**
223      * @return The active MojoExecution.
224      */
225     public MojoExecution getExecution() {
226         return getInjectedObject(execution, "execution");
227     }
228 
229     /**
230      * {@inheritDoc}
231      */
232     @Override
233     public final void execute() throws MojoExecutionException, MojoFailureException {
234 
235         // 0) Get the log and its relevant level
236         final Log log = getLog();
237         final boolean isDebugEnabled = log.isDebugEnabled();
238         final boolean isInfoEnabled = log.isInfoEnabled();
239 
240         // 1) Should we skip execution?
241         if (shouldExecutionBeSkipped()) {
242 
243             if (isDebugEnabled) {
244                 log.debug("Skipping execution, as instructed.");
245             }
246             return;
247         }
248 
249         // 2) Printout relevant version information.
250         if (isDebugEnabled) {
251             logPluginAndJaxbDependencyInfo();
252         }
253 
254         // 3) Are generated files stale?
255         if (isReGenerationRequired()) {
256 
257             if (performExecution()) {
258 
259                 // As instructed by the performExecution() method, update
260                 // the timestamp of the stale File.
261                 updateStaleFileTimestamp();
262 
263                 // Hack to support M2E
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     /**
275      * Implement this method to check if this AbstractJaxbMojo should skip executing altogether.
276      *
277      * @return {@code true} to indicate that this AbstractJaxbMojo should bail out of its execute method.
278      */
279     protected abstract boolean shouldExecutionBeSkipped();
280 
281     /**
282      * @return {@code true} to indicate that this AbstractJaxbMojo should be run since its generated files were
283      * either stale or not present, and {@code false} otherwise.
284      */
285     protected abstract boolean isReGenerationRequired();
286 
287     /**
288      * <p>Implement this method to perform this Mojo's execution.
289      * This method will only be called if {@code !shouldExecutionBeSkipped() && isReGenerationRequired()}.</p>
290      *
291      * @return {@code true} if the timestamp of the stale file should be updated.
292      * @throws MojoExecutionException if an unexpected problem occurs.
293      *                                Throwing this exception causes a "BUILD ERROR" message to be displayed.
294      * @throws MojoFailureException   if an expected problem (such as a compilation failure) occurs.
295      *                                Throwing this exception causes a "BUILD FAILURE" message to be displayed.
296      */
297     protected abstract boolean performExecution() throws MojoExecutionException, MojoFailureException;
298 
299     /**
300      * Override this method to acquire a List holding all URLs to the sources which this
301      * AbstractJaxbMojo should use to produce its output (XSDs files for AbstractXsdGeneratorMojos and
302      * Java Source Code for AbstractJavaGeneratorMojos).
303      *
304      * @return A non-null List holding URLs to sources used by this AbstractJaxbMojo to produce its output.
305      */
306     protected abstract List<URL> getSources();
307 
308     /**
309      * Retrieves the directory where the generated files should be written to.
310      *
311      * @return the directory where the generated files should be written to.
312      */
313     protected abstract File getOutputDirectory();
314 
315     /**
316      * Retrieves the configured List of paths from which this AbstractJaxbMojo and its internal toolset
317      * (XJC or SchemaGen) should read bytecode classes.
318      *
319      * @return the configured List of paths from which this AbstractJaxbMojo and its internal toolset (XJC or
320      * SchemaGen) should read classes.
321      * @throws org.apache.maven.plugin.MojoExecutionException if the classpath could not be retrieved.
322      */
323     protected abstract List<String> getClasspath() throws MojoExecutionException;
324 
325     /**
326      * Convenience method to invoke when some plugin configuration is incorrect.
327      * Will output the problem as a warning with some degree of log formatting.
328      *
329      * @param propertyName The name of the problematic property.
330      * @param description  The problem description.
331      */
332     @SuppressWarnings("all")
333     protected void warnAboutIncorrectPluginConfiguration(final String propertyName, final String description) {
334 
335         final StringBuilder builder = new StringBuilder();
336         builder.append("\n+=================== [Incorrect Plugin Configuration Detected]\n");
337         builder.append("|\n");
338         builder.append("| Property : " + propertyName + "\n");
339         builder.append("| Problem  : " + description + "\n");
340         builder.append("|\n");
341         builder.append("+=================== [End Incorrect Plugin Configuration Detected]\n\n");
342         getLog().warn(builder.toString().replace("\n", NEWLINE));
343     }
344 
345     /**
346      * @param arguments The final arguments to be passed to a JAXB tool (XJC or SchemaGen).
347      * @param toolName  The name of the tool.
348      * @return the arguments, untouched.
349      */
350     protected final String[] logAndReturnToolArguments(final String[] arguments, final String toolName) {
351 
352         // Check sanity
353         Validate.notNull(arguments, "arguments");
354 
355         if (getLog().isDebugEnabled()) {
356 
357             final StringBuilder argBuilder = new StringBuilder();
358             argBuilder.append("\n+=================== [" + arguments.length + " " + toolName + " Arguments]\n");
359             argBuilder.append("|\n");
360             for (int i = 0; i < arguments.length; i++) {
361                 argBuilder.append("| [").append(i).append("]: ").append(arguments[i]).append("\n");
362             }
363             argBuilder.append("|\n");
364             argBuilder.append("+=================== [End " + arguments.length + " " + toolName + " Arguments]\n\n");
365             getLog().debug(argBuilder.toString().replace("\n", NEWLINE));
366         }
367 
368         // All done.
369         return arguments;
370     }
371 
372     /**
373      * Retrieves the last name part of the stale file.
374      * The full name of the stale file will be generated by pre-pending {@code "." + getExecution().getExecutionId()}
375      * before this staleFileName.
376      *
377      * @return The name of the stale file used by this AbstractJavaGeneratorMojo to detect staleness amongst its
378      * generated files.
379      */
380     protected abstract String getStaleFileName();
381 
382     /**
383      * Acquires the staleFile for this execution
384      *
385      * @return the staleFile (used to define where) for this execution
386      */
387     protected final File getStaleFile() {
388         final String staleFileName = "."
389                 + (getExecution() == null ? "nonExecutionJaxb" : getExecution().getExecutionId())
390                 + "-" + getStaleFileName();
391         return new File(staleFileDirectory, staleFileName);
392     }
393 
394     /**
395      * <p>The algorithm for finding the encoding to use is as follows (where the first non-null value found
396      * is used for encoding):</p>
397      * <ol>
398      * <li>If the configuration property is explicitly given within the plugin's configuration, use that value.</li>
399      * <li>If the Maven property <code>project.build.sourceEncoding</code> is defined, use its value.</li>
400      * <li>Otherwise use the value from the system property <code>file.encoding</code>.</li>
401      * </ol>
402      *
403      * @param warnIfConfiguredEncodingDiffersFromFileEncoding Defines if the configured encoding is not equal to the
404      *                                                        system property {@code file.encoding}, emit a warning
405      *                                                        on the Maven Log (implies that the Maven log has to be
406      *                                                        warnEnabled).
407      * @return The encoding to be used by this AbstractJaxbMojo and its tools.
408      * @see #encoding
409      */
410     protected final String getEncoding(final boolean warnIfConfiguredEncodingDiffersFromFileEncoding) {
411 
412         // Harvest information
413         final boolean configuredEncoding = encoding != null;
414         final String fileEncoding = System.getProperty(SYSTEM_FILE_ENCODING_PROPERTY);
415         final String effectiveEncoding = configuredEncoding ? encoding : fileEncoding;
416 
417         // Should we warn?
418         if (warnIfConfiguredEncodingDiffersFromFileEncoding
419                 && !fileEncoding.equalsIgnoreCase(effectiveEncoding)
420                 && getLog().isWarnEnabled()) {
421             getLog().warn("Configured encoding [" + effectiveEncoding
422                     + "] differs from encoding given in system property '" + SYSTEM_FILE_ENCODING_PROPERTY
423                     + "' [" + fileEncoding + "]");
424         }
425 
426         if (getLog().isDebugEnabled()) {
427             getLog().debug("Using " + (configuredEncoding ? "explicitly configured" : "system property")
428                     + " encoding [" + effectiveEncoding + "]");
429         }
430 
431         // All Done.
432         return effectiveEncoding;
433     }
434 
435     /**
436      * Retrieves the JAXB episode File, and ensures that the parent directory where it exists is created.
437      *
438      * @param customEpisodeFileName {@code null} to indicate that the standard episode file name ("sun-jaxb.episode")
439      *                              should be used, and otherwise a non-empty name which should be used
440      *                              as the episode file name.
441      * @return A non-null File where the JAXB episode file should be written.
442      * @throws MojoExecutionException if the parent directory of the episode file could not be created.
443      */
444     protected File getEpisodeFile(final String customEpisodeFileName) throws MojoExecutionException {
445 
446         // Check sanity
447         final String effectiveEpisodeFileName = customEpisodeFileName == null
448                 ? "sun-jaxb.episode"
449                 : customEpisodeFileName;
450         Validate.notEmpty(effectiveEpisodeFileName, "effectiveEpisodeFileName");
451 
452         // Use the standard episode location
453         final File generatedMetaInfDirectory = new File(getOutputDirectory(), "META-INF");
454 
455         if (!generatedMetaInfDirectory.exists()) {
456 
457             FileSystemUtilities.createDirectory(generatedMetaInfDirectory, false);
458             if (getLog().isDebugEnabled()) {
459                 getLog().debug("Created episode directory ["
460                         + FileSystemUtilities.getCanonicalPath(generatedMetaInfDirectory) + "]: " +
461                         generatedMetaInfDirectory.exists());
462             }
463         }
464 
465         // All done.
466         return new File(generatedMetaInfDirectory, effectiveEpisodeFileName);
467     }
468 
469     //
470     // Private helpers
471     //
472 
473     private void logPluginAndJaxbDependencyInfo() {
474 
475         if (getLog().isDebugEnabled()) {
476             final StringBuilder builder = new StringBuilder();
477             builder.append("\n+=================== [Brief Plugin Build Dependency Information]\n");
478             builder.append("|\n");
479             builder.append("| Note: These dependencies pertain to what was used to build *the plugin*.\n");
480             builder.append("|       Check project dependencies to see the ones used in *your build*.\n");
481             builder.append("|\n");
482 
483             // Find the dependency and version information within the dependencies.properties file.
484             final SortedMap<String, String> versionMap = DependsFileParser.getVersionMap(OWN_ARTIFACT_ID);
485 
486             builder.append("|\n");
487             builder.append("| Plugin's own information\n");
488             builder.append("|     GroupId    : " + versionMap.get(DependsFileParser.OWN_GROUPID_KEY) + "\n");
489             builder.append("|     ArtifactID : " + versionMap.get(DependsFileParser.OWN_ARTIFACTID_KEY) + "\n");
490             builder.append("|     Version    : " + versionMap.get(DependsFileParser.OWN_VERSION_KEY) + "\n");
491             builder.append("|     Buildtime  : " + versionMap.get(DependsFileParser.BUILDTIME_KEY) + "\n");
492             builder.append("|\n");
493             builder.append("| Plugin's JAXB-related dependencies\n");
494             builder.append("|\n");
495 
496             final SortedMap<String, DependencyInfo> diMap = DependsFileParser.createDependencyInfoMap(versionMap);
497 
498             int dependencyIndex = 0;
499             for (Map.Entry<String, DependencyInfo> current : diMap.entrySet()) {
500 
501                 final String key = current.getKey().trim();
502                 for (String currentRelevantGroupId : RELEVANT_GROUPIDS) {
503                     if (key.startsWith(currentRelevantGroupId)) {
504 
505                         final DependencyInfo di = current.getValue();
506                         builder.append("|   " + (++dependencyIndex) + ") [" + di.getArtifactId() + "]\n");
507                         builder.append("|     GroupId    : " + di.getGroupId() + "\n");
508                         builder.append("|     ArtifactID : " + di.getArtifactId() + "\n");
509                         builder.append("|     Version    : " + di.getVersion() + "\n");
510                         builder.append("|     Scope      : " + di.getScope() + "\n");
511                         builder.append("|     Type       : " + di.getType() + "\n");
512                         builder.append("|\n");
513                     }
514                 }
515             }
516 
517             builder.append("+=================== [End Brief Plugin Build Dependency Information]\n\n");
518             getLog().debug(builder.toString().replace("\n", NEWLINE));
519         }
520     }
521 
522     private <T> T getInjectedObject(final T objectOrNull, final String objectName) {
523 
524         if (objectOrNull == null) {
525             getLog().error(
526                     "Found null '" + objectName + "', implying that Maven @Component injection was not done properly.");
527         }
528 
529         return objectOrNull;
530     }
531 
532     private void updateStaleFileTimestamp() throws MojoExecutionException {
533 
534         final File staleFile = getStaleFile();
535         if (!staleFile.exists()) {
536 
537             // Ensure that the staleFileDirectory exists
538             FileSystemUtilities.createDirectory(staleFile.getParentFile(), false);
539 
540             try {
541                 staleFile.createNewFile();
542 
543                 if (getLog().isDebugEnabled()) {
544                     getLog().debug("Created staleFile [" + FileSystemUtilities.getCanonicalPath(staleFile) + "]");
545                 }
546             } catch (IOException e) {
547                 throw new MojoExecutionException("Could not create staleFile.", e);
548             }
549 
550         } else {
551             if (!staleFile.setLastModified(System.currentTimeMillis())) {
552                 getLog().warn("Failed updating modification time of staleFile ["
553                         + FileSystemUtilities.getCanonicalPath(staleFile) + "]");
554             }
555         }
556     }
557 
558     /**
559      * Prints out the system properties to the Maven Log at Debug level.
560      */
561     protected void logSystemPropertiesAndBasedir() {
562         if (getLog().isDebugEnabled()) {
563 
564             final StringBuilder builder = new StringBuilder();
565 
566             builder.append("\n+=================== [System properties]\n");
567             builder.append("|\n");
568 
569             // Sort the system properties
570             final SortedMap<String, Object> props = new TreeMap<String, Object>();
571             props.put("basedir", FileSystemUtilities.getCanonicalPath(getProject().getBasedir()));
572 
573             for (Map.Entry<Object, Object> current : System.getProperties().entrySet()) {
574                 props.put("" + current.getKey(), current.getValue());
575             }
576             for (Map.Entry<String, Object> current : props.entrySet()) {
577                 builder.append("| [" + current.getKey() + "]: " + current.getValue() + "\n");
578             }
579 
580             builder.append("|\n");
581             builder.append("+=================== [End System properties]\n");
582 
583             // All done.
584             getLog().debug(builder.toString().replace("\n", NEWLINE));
585         }
586     }
587 }