Adding envers support
[hibernate4-maven-plugin] / src / main / java / de / juplo / plugins / hibernate4 / Hbm2DdlMojo.java
1 package de.juplo.plugins.hibernate4;
2
3 /*
4  * Copyright 2001-2005 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 import com.pyx4j.log4j.MavenLogAppender;
20 import org.apache.maven.plugin.AbstractMojo;
21 import org.apache.maven.plugin.MojoExecutionException;
22 import org.apache.maven.plugin.MojoFailureException;
23 import org.apache.maven.project.MavenProject;
24 import org.hibernate.cfg.Configuration;
25 import org.hibernate.envers.configuration.AuditConfiguration;
26 import org.hibernate.tool.hbm2ddl.SchemaExport;
27 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
28 import org.hibernate.tool.hbm2ddl.Target;
29 import org.scannotation.AnnotationDB;
30
31 import javax.persistence.Embeddable;
32 import javax.persistence.Entity;
33 import javax.persistence.MappedSuperclass;
34 import java.io.*;
35 import java.math.BigInteger;
36 import java.net.URL;
37 import java.net.URLClassLoader;
38 import java.security.MessageDigest;
39 import java.sql.*;
40 import java.util.*;
41 import java.util.Map.Entry;
42 import java.util.logging.Logger;
43
44
45 /**
46  * Goal which extracts the hibernate-mapping-configuration and
47  * exports an according SQL-database-schema.
48  *
49  * @goal export
50  * @phase process-classes
51  * @threadSafe
52  * @requiresDependencyResolution runtime
53  */
54 public class Hbm2DdlMojo extends AbstractMojo
55 {
56   public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
57
58   public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
59   public final static String URL = "hibernate.connection.url";
60   public final static String USERNAME = "hibernate.connection.username";
61   public final static String PASSWORD = "hibernate.connection.password";
62   public final static String DIALECT = "hibernate.dialect";
63   public final static String ENVERS = "hibernate.export.envers";
64
65   private final static String MD5S = "schema.md5s";
66
67   /**
68    * The maven project.
69    * <p>
70    * Only needed internally.
71    *
72    * @parameter expression="${project}"
73    * @required
74    * @readonly
75    */
76   private MavenProject project;
77
78   /**
79    * Build-directory.
80    * <p>
81    * Only needed internally.
82    *
83    * @parameter expression="${project.build.directory}"
84    * @required
85    * @readonly
86    */
87   private String buildDirectory;
88
89   /**
90    * Classes-Directory to scan.
91    * <p>
92    * This parameter defaults to the maven build-output-directory for classes.
93    * Additonally, all dependencies are scanned for annotated classes.
94    *
95    * @parameter expression="${project.build.outputDirectory}"
96    */
97   private String outputDirectory;
98
99   /**
100    * Wether to scan test-classes too, or not.
101    * <p>
102    * If this parameter is set to <code>true</code> the test-classes of the
103    * artifact will be scanned for hibernate-annotated classes additionally.
104    *
105    * @parameter expression="${hibernate.export.scann_testclasses}" default-value="false"
106    */
107   private boolean scanTestClasses;
108
109   /**
110    * Test-Classes-Directory to scan.
111    * <p>
112    * This parameter defaults to the maven build-output-directory for
113    * test-classes.
114    * <p>
115    * This parameter is only used, when <code>scanTestClasses</code> is set
116    * to <code>true</code>!
117    *
118    * @parameter expression="${project.build.testOutputDirectory}"
119    */
120   private String testOutputDirectory;
121
122   /**
123    * Skip execution
124    * <p>
125    * If set to <code>true</code>, the execution is skipped.
126    * <p>
127    * A skipped excecution is signaled via the maven-property
128    * <code>${hibernate.export.skipped}</code>.
129    * <p>
130    * The excecution is skipped automatically, if no modified or newly added
131    * annotated classes are found and the dialect was not changed.
132    *
133    * @parameter expression="${maven.test.skip}" default-value="false"
134    */
135   private boolean skip;
136
137   /**
138    * Force execution
139    * <p>
140    * Force execution, even if no modified or newly added annotated classes
141    * where found and the dialect was not changed.
142    * <p>
143    * <code>skip</code> takes precedence over <code>force</code>.
144    *
145    * @parameter expression="${hibernate.export.force}" default-value="false"
146    */
147   private boolean force;
148
149   /**
150    * SQL-Driver name.
151    *
152    * @parameter expression="${hibernate.connection.driver_class}
153    */
154   private String driverClassName;
155
156   /**
157    * Database URL.
158    *
159    * @parameter expression="${hibernate.connection.url}"
160    */
161   private String url;
162
163   /**
164    * Database username
165    *
166    * @parameter expression="${hibernate.connection.username}"
167    */
168   private String username;
169
170   /**
171    * Database password
172    *
173    * @parameter expression="${hibernate.connection.password}"
174    */
175   private String password;
176
177   /**
178    * Hibernate dialect.
179    *
180    * @parameter expression="${hibernate.dialect}"
181    */
182   private String hibernateDialect;
183
184   /**
185    * Path to Hibernate configuration file.
186    *
187    * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
188    */
189   private String hibernateProperties;
190
191   /**
192    * Target of execution:
193    * <ul>
194    *   <li><strong>NONE</strong> do nothing - just validate the configuration (forces excecution, signals skip)</li>
195    *   <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>. forces excecution, signals skip)</li>
196    *   <li><strong>SCRIPT</strong> export schema to SQL-script</li>
197    *   <li><strong>BOTH</strong></li>
198    * </ul>
199    *
200    * @parameter expression="${hibernate.export.target}" default-value="EXPORT"
201    */
202   private String target;
203
204   /**
205    * Type of execution.
206    * <ul>
207    *   <li><strong>NONE</strong> do nothing - just validate the configuration</li>
208    *   <li><strong>CREATE</strong> create database-schema</li>
209    *   <li><strong>DROP</strong> drop database-schema</li>
210    *   <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
211    * </ul>
212    *
213    * @parameter expression="${hibernate.export.type}" default-value="BOTH"
214    */
215   private String type;
216
217   /**
218    * Output file.
219    *
220    * @parameter expression="${hibernate.export.schema.filename}" default-value="${project.build.directory}/schema.sql"
221    */
222   private String outputFile;
223
224   /**
225    * Delimiter in output-file.
226    *
227    * @parameter expression="${hibernate.export.schema.delimiter}" default-value=";"
228    */
229   private String delimiter;
230
231   /**
232    * Format output-file.
233    *
234    * @parameter expression="${hibernate.export.schema.format}" default-value="true"
235    */
236   private boolean format;
237
238   /**
239    * Generate envers schema for auditing tables.
240    *
241    * @parameter expression="${hibernate.export.envers}" default-value="false"
242    */
243   private Boolean envers;
244
245   /**
246    * Transient attribute, used only for knowing if the schema has changed since it was last run.
247    */
248   private boolean modified;
249
250   @Override
251   public void execute()
252     throws
253       MojoFailureException,
254       MojoExecutionException
255   {
256     if (skip)
257     {
258       getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
259       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
260       return;
261     }
262
263     File dir = new File(outputDirectory);
264     if (!dir.exists())
265       throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
266
267     Map<String,String> md5s;
268     modified = false;
269     File saved = new File(buildDirectory + File.separator + MD5S);
270
271     if (saved.exists())
272     {
273       try
274       {
275         FileInputStream fis = new FileInputStream(saved);
276         ObjectInputStream ois = new ObjectInputStream(fis);
277         md5s = (HashMap<String,String>)ois.readObject();
278         ois.close();
279       }
280       catch (Exception e)
281       {
282         md5s = new HashMap<String,String>();
283         getLog().warn("Cannot read timestamps from saved: " + e);
284       }
285     }
286     else
287     {
288       md5s = new HashMap<String,String>();
289       try
290       {
291         saved.createNewFile();
292       }
293       catch (IOException e)
294       {
295         getLog().warn("Cannot create saved for timestamps: " + e);
296       }
297     }
298
299     ClassLoader classLoader;
300     try
301     {
302       getLog().debug("Creating ClassLoader for project-dependencies...");
303       List<String> classpathFiles = project.getCompileClasspathElements();
304       if (scanTestClasses)
305         classpathFiles.addAll(project.getTestClasspathElements());
306       URL[] urls = new URL[classpathFiles.size()];
307       for (int i = 0; i < classpathFiles.size(); ++i)
308       {
309         getLog().debug("Dependency: " + classpathFiles.get(i));
310         urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
311       }
312       classLoader = new URLClassLoader(urls, getClass().getClassLoader());
313     }
314     catch (Exception e)
315     {
316       getLog().error("Error while creating ClassLoader!", e);
317       throw new MojoExecutionException(e.getMessage());
318     }
319
320     Properties properties = new Properties();
321
322     /** Try to read configuration from properties-file */
323     try
324     {
325       File file = new File(hibernateProperties);
326       if (file.exists())
327       {
328         getLog().info("Reading properties from file " + hibernateProperties + "...");
329         properties.load(new FileInputStream(file));
330       }
331       else
332         getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
333     }
334     catch (IOException e)
335     {
336       getLog().error("Error while reading properties!", e);
337       throw new MojoExecutionException(e.getMessage());
338     }
339
340     /** Overwrite values from propertie-file or set, if given */
341     if (driverClassName != null)
342     {
343       if (properties.containsKey(DRIVER_CLASS))
344         getLog().debug(
345             "Overwriting property " +
346             DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
347             " with the value " + driverClassName
348           );
349       else
350         getLog().debug("Using the value " + driverClassName);
351       properties.setProperty(DRIVER_CLASS, driverClassName);
352     }
353     if (url != null)
354     {
355       if (properties.containsKey(URL))
356         getLog().debug(
357             "Overwriting property " +
358             URL + "=" + properties.getProperty(URL) +
359             " with the value " + url
360           );
361       else
362         getLog().debug("Using the value " + url);
363       properties.setProperty(URL, url);
364     }
365     if (username != null)
366     {
367       if (properties.containsKey(USERNAME))
368         getLog().debug(
369             "Overwriting property " +
370             USERNAME + "=" + properties.getProperty(USERNAME) +
371             " with the value " + username
372           );
373       else
374         getLog().debug("Using the value " + username);
375       properties.setProperty(USERNAME, username);
376     }
377     if (password != null)
378     {
379       if (properties.containsKey(PASSWORD))
380         getLog().debug(
381             "Overwriting property " +
382             PASSWORD + "=" + properties.getProperty(PASSWORD) +
383             " with the value " + password 
384           );
385       else
386         getLog().debug("Using the value " + password);
387       properties.setProperty(PASSWORD, password);
388     }
389     if (hibernateDialect != null)
390     {
391       if (properties.containsKey(DIALECT))
392         getLog().debug(
393             "Overwriting property " +
394             DIALECT + "=" + properties.getProperty(DIALECT) +
395             " with the value " + hibernateDialect
396           );
397       else
398         getLog().debug("Using the value " + hibernateDialect);
399       properties.setProperty(DIALECT, hibernateDialect);
400     }
401
402     /** The generated SQL varies with the dialect! */
403     if (md5s.containsKey(DIALECT))
404     {
405       String dialect = properties.getProperty(DIALECT);
406       if (md5s.get(DIALECT).equals(dialect))
407         getLog().debug("SQL-dialect unchanged.");
408       else
409       {
410         getLog().debug("SQL-dialect changed: " + dialect);
411         modified = true;
412         md5s.put(DIALECT, dialect);
413       }
414     }
415     else
416     {
417       modified = true;
418       md5s.put(DIALECT, properties.getProperty(DIALECT));
419     }
420
421     if (md5s.containsKey(ENVERS))
422     {
423       String envers = properties.getProperty(ENVERS);
424       if (md5s.get(ENVERS).equals(envers))
425         getLog().debug("Envers unchanged.");
426       else
427       {
428         getLog().debug("Envers changed: " + envers);
429         modified = true;
430         md5s.put(ENVERS, envers.toString());
431       }
432     }
433     else
434     {
435       modified = true;
436       md5s.put(ENVERS, properties.getProperty(ENVERS));
437     }
438
439     if (envers != null) {
440       if (properties.containsKey(ENVERS))
441         getLog().debug(
442             "Overwriting property " +
443                 ENVERS + "=" + properties.getProperty(ENVERS) +
444                 " with the value " + envers
445         );
446       else
447         getLog().debug("Using the value " + envers);
448       properties.setProperty(ENVERS, envers.toString());
449     }
450
451     if (properties.isEmpty())
452     {
453       getLog().error("No properties set!");
454       throw new MojoFailureException("Hibernate-Configuration is missing!");
455     }
456
457     Target target;
458     try
459     {
460       target = Target.valueOf(this.target.toUpperCase());
461     }
462     catch (IllegalArgumentException e)
463     {
464       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
465       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
466       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
467     }
468     Type type;
469     try
470     {
471       type = Type.valueOf(this.type.toUpperCase());
472     }
473     catch (IllegalArgumentException e)
474     {
475       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
476       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
477       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
478     }
479
480     if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
481     {
482       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
483     }
484     if (
485         !modified
486         && !target.equals(Target.SCRIPT)
487         && !target.equals(Target.NONE)
488         && !force
489       )
490     {
491       getLog().info("No modified annotated classes found and dialect unchanged.");
492       getLog().info("Skipping schema generation!");
493       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
494       return;
495     }
496
497     getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
498     for (Entry<Object,Object> entry : properties.entrySet())
499       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
500
501     Connection connection = null;
502     try
503     {
504       /**
505        * The connection must be established outside of hibernate, because
506        * hibernate does not use the context-classloader of the current
507        * thread and, hence, would not be able to resolve the driver-class!
508        */
509       switch (target)
510       {
511         case EXPORT:
512         case BOTH:
513           switch (type)
514           {
515             case CREATE:
516             case DROP:
517             case BOTH:
518               Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
519               getLog().debug("Registering JDBC-driver " + driverClass.getName());
520               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
521               getLog().debug(
522                   "Opening JDBC-connection to "
523                   + properties.getProperty(URL)
524                   + " as "
525                   + properties.getProperty(USERNAME)
526                   + " with password "
527                   + properties.getProperty(PASSWORD)
528                   );
529               connection = DriverManager.getConnection(
530                   properties.getProperty(URL),
531                   properties.getProperty(USERNAME),
532                   properties.getProperty(PASSWORD)
533                   );
534           }
535       }
536     }
537     catch (ClassNotFoundException e)
538     {
539       getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
540       throw new MojoExecutionException(e.getMessage());
541     }
542     catch (Exception e)
543     {
544       getLog().error("Cannot establish connection to database!");
545       Enumeration<Driver> drivers = DriverManager.getDrivers();
546       if (!drivers.hasMoreElements())
547         getLog().error("No drivers registered!");
548       while (drivers.hasMoreElements())
549         getLog().debug("Driver: " + drivers.nextElement());
550       throw new MojoExecutionException(e.getMessage());
551     }
552
553     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
554     MavenLogAppender.startPluginLog(this);
555     try
556     {
557       /**
558        * Change class-loader of current thread, so that hibernate can
559        * see all dependencies!
560        */
561       Thread.currentThread().setContextClassLoader(classLoader);
562
563       Set<Class<?>> classes = scanForAnnotations(dir, classLoader, md5s);
564
565       Configuration config = new Configuration();
566       config.setProperties(properties);
567       getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
568       for (Class<?> annotatedClass : classes)
569       {
570         getLog().debug("Class " + annotatedClass);
571         config.addAnnotatedClass(annotatedClass);
572       }
573       config.buildMappings();
574       if ("true".equals(properties.getProperty(ENVERS)))
575       {
576         getLog().debug("Using envers");
577         AuditConfiguration.getFor(config);
578       }
579
580       SchemaExport export = new SchemaExport(config, connection);
581       export.setOutputFile(outputFile);
582       export.setDelimiter(delimiter);
583       export.setFormat(format);
584       export.execute(target, type);
585
586       for (Object exception : export.getExceptions())
587         getLog().debug(exception.toString());
588     }
589     finally
590     {
591       /** Stop Log-Capturing */
592       MavenLogAppender.endPluginLog(this);
593
594       /** Restore the old class-loader (TODO: is this really necessary?) */
595       Thread.currentThread().setContextClassLoader(contextClassLoader);
596
597       /** Close the connection */
598       try
599       {
600         if (connection != null)
601           connection.close();
602       }
603       catch (SQLException e)
604       {
605         getLog().error("Error while closing connection: " + e.getMessage());
606       }
607     }
608
609     /** Write md5-sums for annotated classes to file */
610     try
611     {
612       FileOutputStream fos = new FileOutputStream(saved);
613       ObjectOutputStream oos = new ObjectOutputStream(fos);
614       oos.writeObject(md5s);
615       oos.close();
616       fos.close();
617     }
618     catch (Exception e)
619     {
620       getLog().error("Cannot write md5-sums to file: " + e);
621     }
622   }
623
624   /**
625    * Needed, because DriverManager won't pick up drivers, that were not
626    * loaded by the system-classloader!
627    * See:
628    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
629    */
630   static final class DriverProxy implements Driver
631   {
632     private final Driver target;
633
634     DriverProxy(Driver target)
635     {
636       if (target == null)
637         throw new NullPointerException();
638       this.target = target;
639     }
640
641     public java.sql.Driver getTarget()
642     {
643       return target;
644     }
645
646     @Override
647     public boolean acceptsURL(String url) throws SQLException
648     {
649       return target.acceptsURL(url);
650     }
651
652     @Override
653     public java.sql.Connection connect(
654         String url,
655         java.util.Properties info
656       )
657       throws
658         SQLException
659     {
660       return target.connect(url, info);
661     }
662
663     @Override
664     public int getMajorVersion()
665     {
666       return target.getMajorVersion();
667     }
668
669     @Override
670     public int getMinorVersion()
671     {
672       return target.getMinorVersion();
673     }
674
675     @Override
676     public DriverPropertyInfo[] getPropertyInfo(
677         String url,
678         Properties info
679       )
680       throws
681         SQLException
682     {
683       return target.getPropertyInfo(url, info);
684     }
685
686     @Override
687     public boolean jdbcCompliant()
688     {
689       return target.jdbcCompliant();
690     }
691
692     /**
693      * This Method cannot be annotated with @Override, becaus the plugin
694      * will not compile then under Java 1.6!
695      */
696     public Logger getParentLogger() throws SQLFeatureNotSupportedException
697     {
698       throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
699     }
700
701     @Override
702     public String toString()
703     {
704       return "Proxy: " + target;
705     }
706
707     @Override
708     public int hashCode()
709     {
710       return target.hashCode();
711     }
712
713     @Override
714     public boolean equals(Object obj)
715     {
716       if (!(obj instanceof DriverProxy))
717         return false;
718       DriverProxy other = (DriverProxy) obj;
719       return this.target.equals(other.target);
720     }
721   }
722
723   public Set<Class<?>> scanForAnnotations(File dir, ClassLoader classLoader, Map<String,String> md5s) throws MojoExecutionException, MojoFailureException {
724     Set<Class<?>> classes = new TreeSet<Class<?>>(
725         new Comparator<Class<?>>() {
726           @Override
727           public int compare(Class<?> a, Class<?> b) {
728             return a.getName().compareTo(b.getName());
729           }
730         }
731     );
732
733     try {
734       AnnotationDB db = new AnnotationDB();
735       getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
736       URL dirUrl = dir.toURI().toURL();
737       db.scanArchives(dirUrl);
738       if (scanTestClasses) {
739         dir = new File(testOutputDirectory);
740         if (!dir.exists())
741           throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
742         getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
743         dirUrl = dir.toURI().toURL();
744         db.scanArchives(dirUrl);
745       }
746
747       Set<String> classNames = new HashSet<String>();
748       if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
749         classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
750       if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
751         classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
752       if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
753         classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
754
755       MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
756       for (String name : classNames) {
757         Class<?> annotatedClass = classLoader.loadClass(name);
758         classes.add(annotatedClass);
759         InputStream is =
760             annotatedClass
761                 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
762         byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
763         int i;
764         while((i = is.read(buffer)) > -1)
765           digest.update(buffer, 0, i);
766         is.close();
767         byte[] bytes = digest.digest();
768         BigInteger bi = new BigInteger(1, bytes);
769         String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
770         String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
771         if (!newMd5.equals(oldMd5))
772         {
773           getLog().debug("Found new or modified annotated class: " + name);
774           modified = true;
775           md5s.put(name, newMd5);
776         }
777         else
778         {
779           getLog().debug(oldMd5 + " -> class unchanged: " + name);
780         }
781       }
782     } catch (Exception e) {
783       getLog().error("Error while scanning!", e);
784       throw new MojoFailureException(e.getMessage());
785     }
786
787     if (classes.isEmpty())
788       throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
789
790     getLog().debug("Detected classes with mapping-annotations:");
791     for (Class<?> annotatedClass : classes)
792       getLog().debug("  " + annotatedClass.getName());
793     return classes;
794   }
795 }