Fixed bug with directories, that should be scanned for annotations
[hibernate4-maven-plugin] / src / main / java / de / juplo / plugins / hibernate / AbstractSchemaMojo.java
1 package de.juplo.plugins.hibernate;
2
3
4 import com.pyx4j.log4j.MavenLogAppender;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.net.MalformedURLException;
11 import java.net.URL;
12 import java.security.NoSuchAlgorithmException;
13 import java.time.ZonedDateTime;
14 import java.util.Collections;
15 import java.util.EnumSet;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.LinkedHashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Properties;
24 import java.util.Set;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27 import javax.persistence.Embeddable;
28 import javax.persistence.Entity;
29 import javax.persistence.MappedSuperclass;
30 import javax.persistence.spi.PersistenceUnitTransactionType;
31 import org.apache.maven.artifact.Artifact;
32 import org.apache.maven.model.Resource;
33 import org.apache.maven.plugin.AbstractMojo;
34 import org.apache.maven.plugin.MojoExecutionException;
35 import org.apache.maven.plugin.MojoFailureException;
36 import org.apache.maven.project.MavenProject;
37 import org.hibernate.boot.MetadataBuilder;
38 import org.hibernate.boot.MetadataSources;
39 import org.hibernate.boot.cfgxml.internal.ConfigLoader;
40 import org.hibernate.boot.cfgxml.spi.LoadedConfig;
41 import org.hibernate.boot.cfgxml.spi.MappingReference;
42 import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
43 import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
44 import org.hibernate.boot.registry.BootstrapServiceRegistry;
45 import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
46 import org.hibernate.boot.registry.StandardServiceRegistry;
47 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
48 import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
49 import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
50 import org.hibernate.boot.registry.selector.spi.StrategySelector;
51 import org.hibernate.boot.spi.MetadataImplementor;
52 import org.hibernate.cfg.AvailableSettings;
53 import static org.hibernate.cfg.AvailableSettings.DIALECT;
54 import static org.hibernate.cfg.AvailableSettings.DRIVER;
55 import static org.hibernate.cfg.AvailableSettings.FORMAT_SQL;
56 import static org.hibernate.cfg.AvailableSettings.HBM2DDL_DELIMITER;
57 import static org.hibernate.cfg.AvailableSettings.HBM2DLL_CREATE_NAMESPACES;
58 import static org.hibernate.cfg.AvailableSettings.IMPLICIT_NAMING_STRATEGY;
59 import static org.hibernate.cfg.AvailableSettings.JPA_JDBC_DRIVER;
60 import static org.hibernate.cfg.AvailableSettings.JPA_JDBC_PASSWORD;
61 import static org.hibernate.cfg.AvailableSettings.JPA_JDBC_URL;
62 import static org.hibernate.cfg.AvailableSettings.JPA_JDBC_USER;
63 import static org.hibernate.cfg.AvailableSettings.PASS;
64 import static org.hibernate.cfg.AvailableSettings.PHYSICAL_NAMING_STRATEGY;
65 import static org.hibernate.cfg.AvailableSettings.SHOW_SQL;
66 import static org.hibernate.cfg.AvailableSettings.USER;
67 import static org.hibernate.cfg.AvailableSettings.URL;
68 import org.hibernate.engine.config.spi.ConfigurationService;
69 import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
70 import org.hibernate.internal.util.config.ConfigurationException;
71 import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
72 import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
73 import org.hibernate.tool.schema.TargetType;
74 import org.hibernate.tool.schema.internal.ExceptionHandlerCollectingImpl;
75 import org.hibernate.tool.schema.internal.exec.ScriptTargetOutputToFile;
76 import org.hibernate.tool.schema.spi.ExecutionOptions;
77 import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
78 import org.hibernate.tool.schema.spi.ScriptTargetOutput;
79 import org.hibernate.tool.schema.spi.TargetDescriptor;
80 import org.scannotation.AnnotationDB;
81
82
83 /**
84  * Baseclass with common attributes and methods.
85  *
86  * @phase process-classes
87  * @threadSafe
88  * @requiresDependencyResolution runtime
89  */
90 public abstract class AbstractSchemaMojo extends AbstractMojo
91 {
92   public final static String EXECUTE = "hibernate.schema.execute";
93   public final static String OUTPUTDIRECTORY = "project.build.outputDirectory";
94   public final static String SCAN_CLASSES = "hibernate.schema.scan.classes";
95   public final static String SCAN_DEPENDENCIES = "hibernate.schema.scan.dependencies";
96   public final static String SCAN_TESTCLASSES = "hibernate.schema.scan.test_classes";
97   public final static String TEST_OUTPUTDIRECTORY = "project.build.testOutputDirectory";
98   public final static String SKIPPED = "hibernate.schema.skipped";
99   public final static String SCRIPT = "hibernate.schema.script";
100
101   private final static Pattern SPLIT = Pattern.compile("[^,\\s]+");
102
103   private final Set<String> packages = new HashSet<String>();
104
105
106   /**
107    * The maven project.
108    * <p>
109    * Only needed internally.
110    *
111    * @parameter property="project"
112    * @required
113    * @readonly
114    */
115   private MavenProject project;
116
117   /**
118    * Build-directory.
119    * <p>
120    * Only needed internally.
121    *
122    * @parameter property="project.build.directory"
123    * @required
124    * @readonly
125    */
126   private String buildDirectory;
127
128
129   /** Parameters to configure the genaration of the SQL *********************/
130
131   /**
132    * Excecute the generated SQL.
133    * If set to <code>false</code>, only the SQL-script is created and the
134    * database is not touched.
135    * <p>
136    * <strong>Important:</strong>
137    * This configuration value can only be configured through the
138    * <code>pom.xml</code>, or by the definition of a system-property, because
139    * it is not known by Hibernate nor JPA and, hence, not picked up from
140    * their configuration!
141    *
142    * @parameter property="hibernate.schema.execute" default-value="true"
143    * @since 2.0
144    */
145   private Boolean execute;
146
147   /**
148    * Skip execution
149    * <p>
150    * If set to <code>true</code>, the execution is skipped.
151    * <p>
152    * A skipped execution is signaled via the maven-property
153    * <code>${hibernate.schema.skipped}</code>.
154    * <p>
155    * The execution is skipped automatically, if no modified or newly added
156    * annotated classes are found and the dialect was not changed.
157    * <p>
158    * <strong>Important:</strong>
159    * This configuration value can only be configured through the
160    * <code>pom.xml</code>, or by the definition of a system-property, because
161    * it is not known by Hibernate nor JPA and, hence, not picked up from
162    * their configuration!
163    *
164    * @parameter property="hibernate.schema.skip" default-value="${maven.test.skip}"
165    * @since 1.0
166    */
167   private boolean skip;
168
169   /**
170    * Force generation/execution
171    * <p>
172    * Force the generation and (if configured) the execution of the SQL, even if
173    * no modified or newly added annotated classes where found and the
174    * configuration was not changed.
175    * <p>
176    * <code>skip</code> takes precedence over <code>force</code>.
177    * <p>
178    * <strong>Important:</strong>
179    * This configuration value can only be configured through the
180    * <code>pom.xml</code>, or by the definition of a system-property, because
181    * it is not known by Hibernate nor JPA and, hence, not picked up from
182    * their configuration!
183    *
184    * @parameter property="hibernate.schema.force" default-value="false"
185    * @since 1.0
186    */
187   private boolean force;
188
189   /**
190    * Hibernate dialect.
191    *
192    * @parameter property="hibernate.dialect"
193    * @since 1.0
194    */
195   private String dialect;
196
197   /**
198    * Delimiter in output-file.
199    * <p>
200    * <strong>Important:</strong>
201    * This configuration value can only be configured through the
202    * <code>pom.xml</code>, or by the definition of a system-property, because
203    * it is not known by Hibernate nor JPA and, hence, not picked up from
204    * their configuration!
205    *
206    * @parameter property="hibernate.hbm2ddl.delimiter" default-value=";"
207    * @since 1.0
208    */
209   private String delimiter;
210
211   /**
212    * Show the generated SQL in the command-line output.
213    *
214    * @parameter property="hibernate.show_sql"
215    * @since 1.0
216    */
217   private Boolean show;
218
219   /**
220    * Format output-file.
221    *
222    * @parameter property="hibernate.format_sql"
223    * @since 1.0
224    */
225   private Boolean format;
226
227   /**
228    * Specifies whether to automatically create also the database schema/catalog.
229    *
230    * @parameter property="hibernate.hbm2dll.create_namespaces" default-value="false"
231    * @since 2.0
232    */
233   private Boolean createNamespaces;
234
235   /**
236    * Implicit naming strategy
237    *
238    * @parameter property="hibernate.implicit_naming_strategy"
239    * @since 2.0
240    */
241   private String implicitNamingStrategy;
242
243   /**
244    * Physical naming strategy
245    *
246    * @parameter property="hibernate.physical_naming_strategy"
247    * @since 2.0
248    */
249   private String physicalNamingStrategy;
250
251   /**
252    * Wether the project should be scanned for annotated-classes, or not
253    * <p>
254    * This parameter is intended to allow overwriting of the parameter
255    * <code>exclude-unlisted-classes</code> of a <code>persistence-unit</code>.
256    * If not specified, it defaults to <code>true</code>
257    *
258    * @parameter property="hibernate.schema.scan.classes"
259    * @since 2.0
260    */
261   private Boolean scanClasses;
262
263   /**
264    * Classes-Directory to scan.
265    * <p>
266    * This parameter defaults to the maven build-output-directory for classes.
267    * Additionally, all dependencies are scanned for annotated classes.
268    * <p>
269    * <strong>Important:</strong>
270    * This configuration value can only be configured through the
271    * <code>pom.xml</code>, or by the definition of a system-property, because
272    * it is not known by Hibernate nor JPA and, hence, not picked up from
273    * their configuration!
274    *
275    * @parameter property="project.build.outputDirectory"
276    * @since 1.0
277    */
278   private String outputDirectory;
279
280   /**
281    * Dependency-Scopes, that should be scanned for annotated classes.
282    * <p>
283    * By default, only dependencies in the scope <code>compile</code> are
284    * scanned for annotated classes. Multiple scopes can be seperated by
285    * white space or commas.
286    * <p>
287    * If you do not want any dependencies to be scanned for annotated
288    * classes, set this parameter to <code>none</code>.
289    * <p>
290    * The plugin does not scan for annotated classes in transitive
291    * dependencies. If some of your annotated classes are hidden in a
292    * transitive dependency, you can simply add that dependency explicitly.
293    *
294    * @parameter property="hibernate.schema.scan.dependencies" default-value="compile"
295    * @since 1.0.3
296    */
297   private String scanDependencies;
298
299   /**
300    * Whether to scan the test-branch of the project for annotated classes, or
301    * not.
302    * <p>
303    * If this parameter is set to <code>true</code> the test-classes of the
304    * artifact will be scanned for hibernate-annotated classes additionally.
305    * <p>
306    * <strong>Important:</strong>
307    * This configuration value can only be configured through the
308    * <code>pom.xml</code>, or by the definition of a system-property, because
309    * it is not known by Hibernate nor JPA and, hence, not picked up from
310    * their configuration!
311    *
312    * @parameter property="hibernate.schema.scan.test_classes" default-value="false"
313    * @since 1.0.1
314    */
315   private Boolean scanTestClasses;
316
317   /**
318    * Test-Classes-Directory to scan.
319    * <p>
320    * This parameter defaults to the maven build-output-directory for
321    * test-classes.
322    * <p>
323    * This parameter is only used, when <code>scanTestClasses</code> is set
324    * to <code>true</code>!
325    * <p>
326    * <strong>Important:</strong>
327    * This configuration value can only be configured through the
328    * <code>pom.xml</code>, or by the definition of a system-property, because
329    * it is not known by Hibernate nor JPA and, hence, not picked up from
330    * their configuration!
331    *
332    * @parameter property="project.build.testOutputDirectory"
333    * @since 1.0.2
334    */
335   private String testOutputDirectory;
336
337
338   /** Conection parameters *************************************************/
339
340   /**
341    * SQL-Driver name.
342    *
343    * @parameter property="hibernate.connection.driver_class"
344    * @since 1.0
345    */
346   private String driver;
347
348   /**
349    * Database URL.
350    *
351    * @parameter property="hibernate.connection.url"
352    * @since 1.0
353    */
354   private String url;
355
356   /**
357    * Database username
358    *
359    * @parameter property="hibernate.connection.username"
360    * @since 1.0
361    */
362   private String username;
363
364   /**
365    * Database password
366    *
367    * @parameter property="hibernate.connection.password"
368    * @since 1.0
369    */
370   private String password;
371
372
373   /** Parameters to locate configuration sources ****************************/
374
375   /**
376    * Path to a file or name of a ressource with hibernate properties.
377    * If this parameter is specified, the plugin will try to load configuration
378    * values from a file with the given path or a ressource on the classpath with
379    * the given name. If both fails, the execution of the plugin will fail.
380    * <p>
381    * If this parameter is not set the plugin will load configuration values
382    * from a ressource named <code>hibernate.properties</code> on the classpath,
383    * if it is present, but will not fail if there is no such ressource.
384    * <p>
385    * During ressource-lookup, the test-classpath takes precedence.
386    *
387    * @parameter
388    * @since 1.0
389    */
390   private String hibernateProperties;
391
392   /**
393    * Path to Hibernate configuration file (.cfg.xml).
394    * If this parameter is specified, the plugin will try to load configuration
395    * values from a file with the given path or a ressource on the classpath with
396    * the given name. If both fails, the execution of the plugin will fail.
397    * <p>
398    * If this parameter is not set the plugin will load configuration values
399    * from a ressource named <code>hibernate.cfg.xml</code> on the classpath,
400    * if it is present, but will not fail if there is no such ressource.
401    * <p>
402    * During ressource-lookup, the test-classpath takes precedence.
403    * <p>
404    * Settings in this file will overwrite settings in the properties file.
405    *
406    * @parameter
407    * @since 1.1.0
408    */
409   private String hibernateConfig;
410
411   /**
412    * Name of the persistence-unit.
413    * If this parameter is specified, the plugin will try to load configuration
414    * values from a persistence-unit with the specified name. If no such
415    * persistence-unit can be found, the plugin will throw an exception.
416    * <p>
417    * If this parameter is not set and there is only one persistence-unit
418    * available, that unit will be used automatically. But if this parameter is
419    * not set and there are multiple persistence-units available on,
420    * the class-path, the execution of the plugin will fail.
421    * <p>
422    * Settings in this file will overwrite settings in the properties or the
423    * configuration file.
424    *
425    * @parameter
426    * @since 1.1.0
427    */
428   private String persistenceUnit;
429
430   /**
431    * List of Hibernate-Mapping-Files (XML).
432    * Multiple files can be separated with white-spaces and/or commas.
433    *
434    * @parameter property="hibernate.mapping"
435    * @since 1.0.2
436    */
437   private String mappings;
438
439
440
441   public final void execute(String filename)
442     throws
443       MojoFailureException,
444       MojoExecutionException
445   {
446     if (skip)
447     {
448       getLog().info("Execution of hibernate-maven-plugin was skipped!");
449       project.getProperties().setProperty(SKIPPED, "true");
450       return;
451     }
452
453     ModificationTracker tracker;
454     try
455     {
456       tracker = new ModificationTracker(buildDirectory, filename, getLog());
457     }
458     catch (NoSuchAlgorithmException e)
459     {
460       throw new MojoFailureException("Digest-Algorithm MD5 is missing!", e);
461     }
462
463     final SimpleConnectionProvider connectionProvider =
464         new SimpleConnectionProvider(getLog());
465
466     try
467     {
468       /** Start extended logging */
469       MavenLogAppender.startPluginLog(this);
470
471       /** Load checksums for old mapping and configuration */
472       tracker.load();
473
474       /** Create the ClassLoader */
475       MutableClassLoader classLoader = createClassLoader();
476
477       /** Create a BootstrapServiceRegistry with the created ClassLoader */
478       BootstrapServiceRegistry bootstrapServiceRegitry =
479           new BootstrapServiceRegistryBuilder()
480               .applyClassLoader(classLoader)
481               .build();
482       ClassLoaderService classLoaderService =
483           bootstrapServiceRegitry.getService(ClassLoaderService.class);
484
485       Properties properties = new Properties();
486       ConfigLoader configLoader = new ConfigLoader(bootstrapServiceRegitry);
487
488       /** Loading and merging configuration */
489       properties.putAll(loadProperties(configLoader));
490       LoadedConfig config = loadConfig(configLoader);
491       if (config != null)
492         properties.putAll(config.getConfigurationValues());
493       ParsedPersistenceXmlDescriptor unit =
494           loadPersistenceUnit(classLoaderService, properties);
495       if (unit != null)
496         properties.putAll(unit.getProperties());
497
498       /** Overwriting/Completing configuration */
499       configure(properties, tracker);
500
501       /** Check configuration for modifications */
502       if(tracker.track(properties))
503         getLog().debug("Configuration has changed.");
504       else
505         getLog().debug("Configuration unchanged.");
506
507       /** Check, that the outputfile is writable */
508       final File output = getOutputFile(filename);
509       /** Check, if the outputfile is missing or was changed */
510       checkOutputFile(output, tracker);
511
512       /** Configure Hibernate */
513       final StandardServiceRegistry serviceRegistry =
514           new StandardServiceRegistryBuilder(bootstrapServiceRegitry)
515               .applySettings(properties)
516               .addService(ConnectionProvider.class, connectionProvider)
517               .build();
518       final MetadataSources sources = new MetadataSources(serviceRegistry);
519
520       /** Add the remaining class-path-elements */
521       completeClassPath(classLoader);
522
523       /** Apply mappings from hibernate-configuration, if present */
524       if (config != null)
525       {
526         for (MappingReference mapping : config.getMappingReferences())
527           mapping.apply(sources);
528       }
529
530       Set<String> classes;
531       if (unit == null)
532       {
533         /** No persistent unit: default behaviour */
534         if (scanClasses == null)
535           scanClasses = true;
536         Set<URL> urls = new HashSet<URL>();
537         if (scanClasses)
538           addRoot(urls, outputDirectory);
539         if (scanTestClasses)
540           addRoot(urls, testOutputDirectory);
541         addDependencies(urls);
542         classes = scanUrls(urls);
543       }
544       else
545       {
546         /** Follow configuration in persisten unit */
547         if (scanClasses == null)
548           scanClasses = !unit.isExcludeUnlistedClasses();
549         Set<URL> urls = new HashSet<URL>();
550         if (scanClasses)
551         {
552           /**
553            * Scan the root of the persiten unit and configured jars for
554            * annotated classes
555            */
556           urls.add(unit.getPersistenceUnitRootUrl());
557           for (URL url : unit.getJarFileUrls())
558             urls.add(url);
559         }
560         if (scanTestClasses)
561           addRoot(urls, testOutputDirectory);
562         classes = scanUrls(urls);
563         for (String className : unit.getManagedClassNames())
564           classes.add(className);
565         /**
566          * Add mappings from the default mapping-file
567          * <code>META-INF/orm.xml</code>, if present
568          */
569         boolean error = false;
570         InputStream is;
571         is = classLoader.getResourceAsStream("META-INF/orm.xml");
572         if (is != null)
573         {
574           getLog().info("Adding default JPA-XML-mapping from META-INF/orm.xml");
575           try
576           {
577             tracker.track("META-INF/orm.xml", is);
578             sources.addResource("META-INF/orm.xml");
579           }
580           catch (IOException e)
581           {
582             getLog().error("cannot read META-INF/orm.xml: " + e);
583             error = true;
584           }
585         }
586         else
587         {
588           getLog().debug("no META-INF/orm.xml found");
589         }
590         /**
591          * Add mappings from files, that are explicitly configured in the
592          * persistence unit
593          */
594         for (String mapping : unit.getMappingFileNames())
595         {
596           getLog().info("Adding explicitly configured mapping from " + mapping);
597           is = classLoader.getResourceAsStream(mapping);
598           if (is != null)
599           {
600             try
601             {
602               tracker.track(mapping, is);
603               sources.addResource(mapping);
604             }
605             catch (IOException e)
606             {
607               getLog().info("cannot read mapping-file " + mapping + ": " + e);
608               error = true;
609             }
610           }
611           else
612           {
613             getLog().error("cannot find mapping-file " + mapping);
614             error = true;
615           }
616         }
617         if (error)
618           throw new MojoFailureException(
619               "error, while reading mappings configured in persistence-unit \"" +
620               unit.getName() +
621               "\""
622               );
623       }
624
625       /** Add the configured/collected annotated classes */
626       for (String className : classes)
627         addAnnotated(className, sources, classLoaderService, tracker);
628
629       /** Add explicitly configured classes */
630       addMappings(sources, tracker);
631
632       /** Skip execution, if mapping and configuration is unchanged */
633       if (!tracker.modified())
634       {
635         getLog().info("Mapping and configuration unchanged.");
636         if (force)
637           getLog().info("Generation/execution is forced!");
638         else
639         {
640           getLog().info("Skipping schema generation!");
641           project.getProperties().setProperty(SKIPPED, "true");
642           return;
643         }
644       }
645
646
647       /** Truncate output file */
648       try
649       {
650         new FileOutputStream(output).getChannel().truncate(0).close();
651       }
652       catch (IOException e)
653       {
654         String error =
655             "Error while truncating " + output.getAbsolutePath() + ": "
656             + e.getMessage();
657         getLog().warn(error);
658         throw new MojoExecutionException(error);
659       }
660
661       /** Create a connection, if sufficient configuration infromation is available */
662       connectionProvider.open(classLoaderService, properties);
663
664       MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
665
666       StrategySelector strategySelector =
667           serviceRegistry.getService(StrategySelector.class);
668
669       if (properties.containsKey(IMPLICIT_NAMING_STRATEGY))
670       {
671         metadataBuilder.applyImplicitNamingStrategy(
672             strategySelector.resolveStrategy(
673                 ImplicitNamingStrategy.class,
674                 properties.getProperty(IMPLICIT_NAMING_STRATEGY)
675                 )
676             );
677       }
678
679       if (properties.containsKey(PHYSICAL_NAMING_STRATEGY))
680       {
681         metadataBuilder.applyPhysicalNamingStrategy(
682             strategySelector.resolveStrategy(
683                 PhysicalNamingStrategy.class,
684                 properties.getProperty(PHYSICAL_NAMING_STRATEGY)
685                 )
686             );
687       }
688
689       /** Prepare the generation of the SQL */
690       Map settings = new HashMap();
691       settings.putAll(
692           serviceRegistry
693               .getService(ConfigurationService.class)
694               .getSettings()
695               );
696       ExceptionHandlerCollectingImpl handler =
697           new ExceptionHandlerCollectingImpl();
698       ExecutionOptions options =
699           SchemaManagementToolCoordinator
700               .buildExecutionOptions(settings, handler);
701       final EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.SCRIPT);
702       if (execute)
703         targetTypes.add(TargetType.DATABASE);
704       TargetDescriptor target = new TargetDescriptor()
705       {
706         @Override
707         public EnumSet<TargetType> getTargetTypes()
708         {
709           return targetTypes;
710         }
711
712         @Override
713         public ScriptTargetOutput getScriptTargetOutput()
714         {
715           String charset =
716               (String)
717               serviceRegistry
718                   .getService(ConfigurationService.class)
719                   .getSettings()
720                   .get(AvailableSettings.HBM2DDL_CHARSET_NAME);
721           return new ScriptTargetOutputToFile(output, charset);
722         }
723       };
724
725       /**
726        * Change class-loader of current thread.
727        * This is necessary, because still not all parts of Hibernate 5 use
728        * the newly introduced ClassLoaderService and will fail otherwise!
729        */
730       Thread thread = Thread.currentThread();
731       ClassLoader contextClassLoader = thread.getContextClassLoader();
732       try
733       {
734         thread.setContextClassLoader(classLoader);
735         build((MetadataImplementor)metadataBuilder.build(), options, target);
736         if (handler.getExceptions().size() > 0)
737         {
738           StringBuilder builder = new StringBuilder();
739           builder.append("Hibernate failed:");
740           for (Exception e : handler.getExceptions())
741           {
742             builder.append("\n * ");
743             builder.append(e.getMessage());
744           }
745           String error = builder.toString();
746           getLog().error(error);
747           throw new MojoFailureException(error);
748         }
749       }
750       finally
751       {
752         thread.setContextClassLoader(contextClassLoader);
753         /** Track, the content of the generated script */
754         checkOutputFile(output, tracker);
755       }
756     }
757     catch (MojoExecutionException e)
758     {
759       tracker.failed();
760       throw e;
761     }
762     catch (MojoFailureException e)
763     {
764       tracker.failed();
765       throw e;
766     }
767     catch (RuntimeException e)
768     {
769       tracker.failed();
770       throw e;
771     }
772     finally
773     {
774       /** Remember mappings and configuration */
775       tracker.save();
776
777       /** Close the connection - if one was opened */
778       connectionProvider.close();
779
780       /** Stop Log-Capturing */
781       MavenLogAppender.endPluginLog(this);
782     }
783   }
784
785
786   abstract void build(
787       MetadataImplementor metadata,
788       ExecutionOptions options,
789       TargetDescriptor target
790       )
791     throws
792       MojoFailureException,
793       MojoExecutionException;
794
795
796   private MutableClassLoader createClassLoader() throws MojoExecutionException
797   {
798     try
799     {
800       getLog().debug("Creating ClassLoader for project-dependencies...");
801       LinkedHashSet<URL> urls = new LinkedHashSet<URL>();
802       File file;
803
804       file = new File(testOutputDirectory);
805       if (!file.exists())
806       {
807         getLog().info("Creating test-output-directory: " + testOutputDirectory);
808         file.mkdirs();
809       }
810       urls.add(file.toURI().toURL());
811
812       file = new File(outputDirectory);
813       if (!file.exists())
814       {
815         getLog().info("Creating output-directory: " + outputDirectory);
816         file.mkdirs();
817       }
818       urls.add(file.toURI().toURL());
819
820       return new MutableClassLoader(urls, getLog());
821     }
822     catch (Exception e)
823     {
824       getLog().error("Error while creating ClassLoader!", e);
825       throw new MojoExecutionException(e.getMessage());
826     }
827   }
828
829   private void completeClassPath(MutableClassLoader classLoader)
830       throws
831         MojoExecutionException
832   {
833     try
834     {
835       getLog().debug("Completing class-paths of the ClassLoader for project-dependencies...");
836       List<String> classpathFiles = project.getCompileClasspathElements();
837       if (scanTestClasses)
838         classpathFiles.addAll(project.getTestClasspathElements());
839       LinkedHashSet<URL> urls = new LinkedHashSet<URL>();
840       for (String pathElement : classpathFiles)
841       {
842         getLog().debug("Dependency: " + pathElement);
843         urls.add(new File(pathElement).toURI().toURL());
844       }
845       classLoader.add(urls);
846     }
847     catch (Exception e)
848     {
849       getLog().error("Error while creating ClassLoader!", e);
850       throw new MojoExecutionException(e.getMessage());
851     }
852   }
853
854   private Map loadProperties(ConfigLoader configLoader)
855       throws
856         MojoExecutionException
857   {
858     /** Try to read configuration from properties-file */
859     if (hibernateProperties == null)
860     {
861       try
862       {
863         return configLoader.loadProperties("hibernate.properties");
864       }
865       catch (ConfigurationException e)
866       {
867         getLog().debug(e.getMessage());
868         return Collections.EMPTY_MAP;
869       }
870     }
871     else
872     {
873       try
874       {
875         File file = new File(hibernateProperties);
876         if (file.exists())
877         {
878           getLog().info("Reading settings from file " + hibernateProperties + "...");
879           return configLoader.loadProperties(file);
880         }
881         else
882           return configLoader.loadProperties(hibernateProperties);
883       }
884       catch (ConfigurationException e)
885       {
886         getLog().error("Error while reading properties!", e);
887         throw new MojoExecutionException(e.getMessage());
888       }
889     }
890   }
891
892   private LoadedConfig loadConfig(ConfigLoader configLoader)
893       throws MojoExecutionException
894   {
895     /** Try to read configuration from configuration-file */
896     if (hibernateConfig == null)
897     {
898       try
899       {
900         return configLoader.loadConfigXmlResource("hibernate.cfg.xml");
901       }
902       catch (ConfigurationException e)
903       {
904         getLog().debug(e.getMessage());
905         return null;
906       }
907     }
908     else
909     {
910       try
911       {
912         File file = new File(hibernateConfig);
913         if (file.exists())
914         {
915           getLog().info("Reading configuration from file " + hibernateConfig + "...");
916           return configLoader.loadConfigXmlFile(file);
917         }
918         else
919         {
920           return configLoader.loadConfigXmlResource(hibernateConfig);
921         }
922       }
923       catch (ConfigurationException e)
924       {
925         getLog().error("Error while reading configuration!", e);
926         throw new MojoExecutionException(e.getMessage());
927       }
928     }
929   }
930
931   private void configure(Properties properties, ModificationTracker tracker)
932       throws MojoFailureException
933   {
934     /**
935      * Special treatment for the configuration-value "execute": if it is
936      * switched to "true", the genearation fo the schema should be forced!
937      */
938     if (tracker.check(EXECUTE, execute.toString()) && execute)
939     {
940       getLog().info(
941           "hibernate.schema.execute was switched on: " +
942           "forcing generation/execution of SQL"
943           );
944       tracker.touch();
945     }
946     configure(properties, execute, EXECUTE);
947
948     /**
949      * Configure the generation of the SQL.
950      * Overwrite values from properties-file if the configuration parameter is
951      * known to Hibernate.
952      */
953     configure(properties, dialect, DIALECT);
954     configure(properties, delimiter, HBM2DDL_DELIMITER);
955     configure(properties, format, FORMAT_SQL);
956     configure(properties, createNamespaces, HBM2DLL_CREATE_NAMESPACES);
957     configure(properties, implicitNamingStrategy, IMPLICIT_NAMING_STRATEGY);
958     configure(properties, physicalNamingStrategy, PHYSICAL_NAMING_STRATEGY);
959     configure(properties, outputDirectory, OUTPUTDIRECTORY);
960     configure(properties, scanDependencies, SCAN_DEPENDENCIES);
961     configure(properties, scanTestClasses, SCAN_TESTCLASSES);
962     configure(properties, testOutputDirectory, TEST_OUTPUTDIRECTORY);
963
964     /**
965      * Special treatment for the configuration-value "show": a change of its
966      * configured value should not lead to a regeneration of the database
967      * schama!
968      */
969     if (show == null)
970       show = Boolean.valueOf(properties.getProperty(SHOW_SQL));
971     else
972       properties.setProperty(SHOW_SQL, show.toString());
973
974     /**
975      * Configure the connection parameters.
976      * Overwrite values from properties-file.
977      */
978     configure(properties, driver, DRIVER, JPA_JDBC_DRIVER);
979     configure(properties, url, URL, JPA_JDBC_URL);
980     configure(properties, username, USER, JPA_JDBC_USER);
981     configure(properties, password, PASS, JPA_JDBC_PASSWORD);
982
983     if (properties.isEmpty())
984     {
985       getLog().error("No properties set!");
986       throw new MojoFailureException("Hibernate configuration is missing!");
987     }
988
989     getLog().info("Gathered configuration:");
990     for (Entry<Object,Object> entry : properties.entrySet())
991       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
992   }
993
994   private void configure(
995       Properties properties,
996       String value,
997       String key,
998       String alternativeKey
999       )
1000   {
1001     configure(properties, value, key);
1002
1003     if (properties.containsKey(alternativeKey))
1004     {
1005       if (properties.containsKey(key))
1006       {
1007         getLog().warn(
1008             "Ignoring property " + alternativeKey + "=\"" +
1009             properties.getProperty(alternativeKey) +
1010             "\" in favour for property " + key + "=\"" +
1011             properties.getProperty(key) + "\""
1012             );
1013         properties.remove(alternativeKey);
1014       }
1015       else
1016       {
1017         value = properties.getProperty(alternativeKey);
1018         properties.remove(alternativeKey);
1019         getLog().info(
1020             "Using value \"" + value + "\" from property " + alternativeKey +
1021             " for property " + key
1022             );
1023         properties.setProperty(key, value);
1024       }
1025     }
1026   }
1027
1028   private void configure(Properties properties, String value, String key)
1029   {
1030     if (value != null)
1031     {
1032       if (properties.containsKey(key))
1033       {
1034         if (!properties.getProperty(key).equals(value))
1035         {
1036           getLog().info(
1037               "Overwriting property " + key + "=\"" +
1038               properties.getProperty(key) +
1039               "\" with value \"" + value + "\""
1040               );
1041           properties.setProperty(key, value);
1042         }
1043       }
1044       else
1045       {
1046         getLog().debug("Using value \"" + value + "\" for property " + key);
1047         properties.setProperty(key, value);
1048       }
1049     }
1050   }
1051
1052   private void configure(Properties properties, Boolean value, String key)
1053   {
1054     configure(properties, value == null ? null : value.toString(), key);
1055   }
1056
1057   private File getOutputFile(String filename)
1058       throws
1059         MojoExecutionException
1060   {
1061     File output = new File(filename);
1062
1063     if (!output.isAbsolute())
1064     {
1065       // Interpret relative file path relative to build directory
1066       output = new File(buildDirectory, filename);
1067     }
1068     getLog().debug("Output file: " + output.getPath());
1069
1070     // Ensure that directory path for specified file exists
1071     File outFileParentDir = output.getParentFile();
1072     if (null != outFileParentDir && !outFileParentDir.exists())
1073     {
1074       try
1075       {
1076         getLog().info(
1077             "Creating directory path for output file:" +
1078             outFileParentDir.getPath()
1079             );
1080         outFileParentDir.mkdirs();
1081       }
1082       catch (Exception e)
1083       {
1084         String error =
1085             "Error creating directory path for output file: " + e.getMessage();
1086         getLog().error(error);
1087         throw new MojoExecutionException(error);
1088       }
1089     }
1090
1091     try
1092     {
1093       output.createNewFile();
1094     }
1095     catch (IOException e)
1096     {
1097       String error = "Error creating output file: " + e.getMessage();
1098       getLog().error(error);
1099       throw new MojoExecutionException(error);
1100     }
1101
1102     if (!output.canWrite())
1103     {
1104       String error =
1105           "Output file " + output.getAbsolutePath() + " is not writable!";
1106       getLog().error(error);
1107       throw new MojoExecutionException(error);
1108     }
1109
1110     return output;
1111   }
1112
1113   private void checkOutputFile(File output, ModificationTracker tracker)
1114       throws
1115         MojoExecutionException
1116   {
1117     try
1118     {
1119       if (output.exists())
1120         tracker.track(SCRIPT, new FileInputStream(output));
1121       else
1122         tracker.track(SCRIPT, ZonedDateTime.now().toString());
1123     }
1124     catch (IOException e)
1125     {
1126       String error =
1127           "Error while checking the generated script: " + e.getMessage();
1128       getLog().error(error);
1129       throw new MojoExecutionException(error);
1130     }
1131   }
1132
1133   private void addMappings(MetadataSources sources, ModificationTracker tracker)
1134       throws MojoFailureException
1135   {
1136     getLog().debug("Adding explicitly configured mappings...");
1137     if (mappings != null)
1138     {
1139       try
1140       {
1141         for (String filename : mappings.split("[\\s,]+"))
1142         {
1143           // First try the filename as absolute/relative path
1144           File file = new File(filename);
1145           if (!file.exists())
1146           {
1147             // If the file was not found, search for it in the resource-directories
1148             for (Resource resource : project.getResources())
1149             {
1150               file = new File(resource.getDirectory() + File.separator + filename);
1151               if (file.exists())
1152                 break;
1153             }
1154           }
1155           if (file.exists())
1156           {
1157             if (file.isDirectory())
1158               // TODO: add support to read all mappings under a directory
1159               throw new MojoFailureException(file.getAbsolutePath() + " is a directory");
1160             if (tracker.track(filename, new FileInputStream(file)))
1161               getLog().debug("Found new or modified mapping-file: " + filename);
1162             else
1163               getLog().debug("Mapping-file unchanged: " + filename);
1164
1165             sources.addFile(file);
1166           }
1167           else
1168             throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
1169         }
1170       }
1171       catch (IOException e)
1172       {
1173         throw new MojoFailureException("Cannot calculate MD5 sums!", e);
1174       }
1175     }
1176   }
1177
1178   private void addRoot(Set<URL> urls, String path) throws MojoFailureException
1179   {
1180     try
1181     {
1182       File dir = new File(path);
1183       if (dir.exists())
1184       {
1185         getLog().info("Adding " + dir.getAbsolutePath() + " to the list of roots to scan...");
1186         urls.add(dir.toURI().toURL());
1187       }
1188     }
1189     catch (MalformedURLException e)
1190     {
1191       getLog().error("error while adding the project-root to the list of roots to scan!", e);
1192       throw new MojoFailureException(e.getMessage());
1193     }
1194   }
1195
1196   private void addDependencies(Set<URL> urls) throws MojoFailureException
1197   {
1198     try
1199     {
1200       if (scanDependencies != null)
1201       {
1202         Matcher matcher = SPLIT.matcher(scanDependencies);
1203         while (matcher.find())
1204         {
1205           getLog().info("Adding dependencies from scope " + matcher.group() + " to the list of roots to scan");
1206           for (Artifact artifact : project.getDependencyArtifacts())
1207           {
1208             if (!artifact.getScope().equalsIgnoreCase(matcher.group()))
1209               continue;
1210             if (artifact.getFile() == null)
1211             {
1212               getLog().warn("Cannot add dependency " + artifact.getId() + ": no JAR-file available!");
1213               continue;
1214             }
1215             getLog().info("Adding dependencies from scope " + artifact.getId() + " to the list of roots to scan");
1216             urls.add(artifact.getFile().toURI().toURL());
1217           }
1218         }
1219       }
1220     }
1221     catch (MalformedURLException e)
1222     {
1223       getLog().error("Error while adding dependencies to the list of roots to scan!", e);
1224       throw new MojoFailureException(e.getMessage());
1225     }
1226   }
1227
1228   private Set<String> scanUrls(Set<URL> scanRoots)
1229       throws
1230         MojoFailureException
1231   {
1232     try
1233     {
1234       AnnotationDB db = new AnnotationDB();
1235       for (URL root : scanRoots)
1236         db.scanArchives(root);
1237
1238       Set<String> classes = new HashSet<String>();
1239       if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
1240         classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
1241       if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
1242         classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
1243       if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
1244         classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
1245
1246       return classes;
1247     }
1248     catch (Exception e)
1249     {
1250       getLog().error("Error while scanning!", e);
1251       throw new MojoFailureException(e.getMessage());
1252     }
1253   }
1254
1255   private void addAnnotated(
1256       String name,
1257       MetadataSources sources,
1258       ClassLoaderService classLoaderService,
1259       ModificationTracker tracker
1260       )
1261       throws
1262         MojoFailureException,
1263         MojoExecutionException
1264   {
1265     try
1266     {
1267       getLog().info("Adding annotated resource: " + name);
1268       String packageName = null;
1269
1270       boolean error = false;
1271       try
1272       {
1273         Class<?> annotatedClass = classLoaderService.classForName(name);
1274         String resourceName = annotatedClass.getName();
1275         resourceName =
1276             resourceName.substring(
1277                 resourceName.lastIndexOf(".") + 1,
1278                 resourceName.length()
1279                 ) + ".class";
1280         InputStream is = annotatedClass.getResourceAsStream(resourceName);
1281         if (is != null)
1282         {
1283           if (tracker.track(name, is))
1284             getLog().debug("New or modified class: " + name);
1285           else
1286             getLog().debug("Unchanged class: " + name);
1287           sources.addAnnotatedClass(annotatedClass);
1288           packageName = annotatedClass.getPackage().getName();
1289         }
1290         else
1291         {
1292           getLog().error("cannot find ressource " + resourceName + " for class " + name);
1293           error = true;
1294         }
1295       }
1296       catch(ClassLoadingException e)
1297       {
1298         packageName = name;
1299       }
1300       if (error)
1301       {
1302         throw new MojoExecutionException("error while inspecting annotated class " + name);
1303       }
1304
1305       while (packageName != null)
1306       {
1307         if (packages.contains(packageName))
1308           return;
1309         String resource = packageName.replace('.', '/') + "/package-info.class";
1310         InputStream is = classLoaderService.locateResourceStream(resource);
1311         if (is == null)
1312         {
1313           // No compiled package-info available: no package-level annotations!
1314           getLog().debug("Package " + packageName + " is not annotated.");
1315         }
1316         else
1317         {
1318           if (tracker.track(packageName, is))
1319             getLog().debug("New or modified package: " + packageName);
1320           else
1321            getLog().debug("Unchanged package: " + packageName);
1322           getLog().info("Adding annotations from package " + packageName);
1323           sources.addPackage(packageName);
1324         }
1325         packages.add(packageName);
1326         int i = packageName.lastIndexOf('.');
1327         if (i < 0)
1328           packageName = null;
1329         else
1330           packageName = packageName.substring(0,i);
1331       }
1332     }
1333     catch (Exception e)
1334     {
1335       getLog().error("Error while adding the annotated class " + name, e);
1336       throw new MojoFailureException(e.getMessage());
1337     }
1338   }
1339
1340   private ParsedPersistenceXmlDescriptor loadPersistenceUnit(
1341       ClassLoaderService classLoaderService,
1342       Properties properties
1343       )
1344       throws
1345         MojoFailureException
1346   {
1347     PersistenceXmlParser parser =
1348         new PersistenceXmlParser(
1349             classLoaderService,
1350             PersistenceUnitTransactionType.RESOURCE_LOCAL
1351              );
1352
1353     Map<String, ParsedPersistenceXmlDescriptor> units =
1354         parser.doResolve(properties);
1355
1356     if (persistenceUnit == null)
1357     {
1358       Iterator<String> names = units.keySet().iterator();
1359       if (!names.hasNext())
1360       {
1361         getLog().info("Found no META-INF/persistence.xml.");
1362         return null;
1363       }
1364
1365       String name = names.next();
1366       if (!names.hasNext())
1367       {
1368           getLog().info("Using persistence-unit " + name);
1369           return units.get(name);
1370       }
1371
1372       StringBuilder builder = new StringBuilder();
1373       builder.append("No name provided and multiple persistence units found: ");
1374       builder.append(name);
1375       while(names.hasNext())
1376       {
1377         builder.append(", ");
1378         builder.append(names.next());
1379       }
1380       builder.append('.');
1381       throw new MojoFailureException(builder.toString());
1382     }
1383
1384     if (units.containsKey(persistenceUnit))
1385     {
1386       getLog().info("Using configured persistence-unit " + persistenceUnit);
1387       return units.get(persistenceUnit);
1388     }
1389
1390     throw new MojoFailureException("Could not find persistence-unit " + persistenceUnit);
1391   }
1392 }