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