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