Skipping of unchanged scenarios is now based on MD5-sums of all classes
[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     if (!modified)
329     {
330       getLog().info("No modified annotated classes found.");
331       getLog().info("Skipping schema generation!");
332       project.getProperties().setProperty("hibernate4.skipped", "true");
333       return;
334     }
335
336     getLog().debug("Detected classes with mapping-annotations:");
337     for (Class<?> annotatedClass : classes)
338       getLog().debug("  " + annotatedClass.getName());
339
340
341     Properties properties = new Properties();
342
343     /** Try to read configuration from properties-file */
344     try
345     {
346       File file = new File(hibernateProperties);
347       if (file.exists())
348       {
349         getLog().info("Reading properties from file " + hibernateProperties + "...");
350         properties.load(new FileInputStream(file));
351       }
352       else
353         getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
354     }
355     catch (IOException e)
356     {
357       getLog().error("Error while reading properties!", e);
358       throw new MojoExecutionException(e.getMessage());
359     }
360
361     /** Overwrite values from propertie-file or set, if given */
362     if (driverClassName != null)
363     {
364       if (properties.containsKey(DRIVER_CLASS))
365         getLog().debug(
366             "Overwriting property " +
367             DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
368             " with the value " + driverClassName +
369             " from the plugin-configuration-parameter driverClassName!"
370           );
371       else
372         getLog().debug(
373             "Using the value " + driverClassName +
374             " from the plugin-configuration-parameter driverClassName!"
375           );
376       properties.setProperty(DRIVER_CLASS, driverClassName);
377     }
378     if (url != null)
379     {
380       if (properties.containsKey(URL))
381         getLog().debug(
382             "Overwriting property " +
383             URL + "=" + properties.getProperty(URL) +
384             " with the value " + url +
385             " from the plugin-configuration-parameter url!"
386           );
387       else
388         getLog().debug(
389             "Using the value " + url +
390             " from the plugin-configuration-parameter url!"
391           );
392       properties.setProperty(URL, url);
393     }
394     if (username != null)
395     {
396       if (properties.containsKey(USERNAME))
397         getLog().debug(
398             "Overwriting property " +
399             USERNAME + "=" + properties.getProperty(USERNAME) +
400             " with the value " + username +
401             " from the plugin-configuration-parameter username!"
402           );
403       else
404         getLog().debug(
405             "Using the value " + username +
406             " from the plugin-configuration-parameter username!"
407           );
408       properties.setProperty(USERNAME, username);
409     }
410     if (password != null)
411     {
412       if (properties.containsKey(PASSWORD))
413         getLog().debug(
414             "Overwriting property " +
415             PASSWORD + "=" + properties.getProperty(PASSWORD) +
416             " with the value " + password +
417             " from the plugin-configuration-parameter password!"
418           );
419       else
420         getLog().debug(
421             "Using the value " + password +
422             " from the plugin-configuration-parameter password!"
423           );
424       properties.setProperty(PASSWORD, password);
425     }
426     if (hibernateDialect != null)
427     {
428       if (properties.containsKey(DIALECT))
429         getLog().debug(
430             "Overwriting property " +
431             DIALECT + "=" + properties.getProperty(DIALECT) +
432             " with the value " + hibernateDialect +
433             " from the plugin-configuration-parameter hibernateDialect!"
434           );
435       else
436         getLog().debug(
437             "Using the value " + hibernateDialect +
438             " from the plugin-configuration-parameter hibernateDialect!"
439           );
440       properties.setProperty(DIALECT, hibernateDialect);
441     }
442
443     getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
444     if (properties.isEmpty())
445     {
446       getLog().error("No properties set!");
447       throw new MojoFailureException("Hibernate-Configuration is missing!");
448     }
449     for (Entry<Object,Object> entry : properties.entrySet())
450       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
451
452     Configuration config = new Configuration();
453     config.setProperties(properties);
454     getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
455     for (Class<?> annotatedClass : classes)
456     {
457       getLog().debug("Class " + annotatedClass);
458       config.addAnnotatedClass(annotatedClass);
459     }
460
461     Target target = null;
462     try
463     {
464       target = Target.valueOf(this.target);
465     }
466     catch (IllegalArgumentException e)
467     {
468       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
469       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
470       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
471     }
472     Type type = null;
473     try
474     {
475       type = Type.valueOf(this.type);
476     }
477     catch (IllegalArgumentException e)
478     {
479       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
480       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
481       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
482     }
483
484     Connection connection = null;
485     try
486     {
487       /**
488        * The connection must be established outside of hibernate, because
489        * hibernate does not use the context-classloader of the current
490        * thread and, hence, would not be able to resolve the driver-class!
491        */
492       switch (target)
493       {
494         case EXPORT:
495         case BOTH:
496           switch (type)
497           {
498             case CREATE:
499             case DROP:
500             case BOTH:
501               Class driverClass = classLoader.loadClass(driverClassName);
502               getLog().debug("Registering JDBC-driver " + driverClass.getName());
503               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
504               getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
505               connection = DriverManager.getConnection(url, username, password);
506           }
507       }
508     }
509     catch (ClassNotFoundException e)
510     {
511       getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
512       throw new MojoExecutionException(e.getMessage());
513     }
514     catch (Exception e)
515     {
516       getLog().error("Cannot establish connection to database!");
517       Enumeration<Driver> drivers = DriverManager.getDrivers();
518       if (!drivers.hasMoreElements())
519         getLog().error("No drivers registered!");
520       while (drivers.hasMoreElements())
521         getLog().debug("Driver: " + drivers.nextElement());
522       throw new MojoExecutionException(e.getMessage());
523     }
524
525     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
526     MavenLogAppender.startPluginLog(this);
527     try
528     {
529       /**
530        * Change class-loader of current thread, so that hibernate can
531        * see all dependencies!
532        */
533       Thread.currentThread().setContextClassLoader(classLoader);
534
535       SchemaExport export = new SchemaExport(config, connection);
536       export.setOutputFile(outputFile);
537       export.setDelimiter(delimiter);
538       export.setFormat(format);
539       export.execute(target, type);
540
541       for (Object exception : export.getExceptions())
542         getLog().debug(exception.toString());
543     }
544     finally
545     {
546       /** Stop Log-Capturing */
547       MavenLogAppender.endPluginLog(this);
548
549       /** Restore the old class-loader (TODO: is this really necessary?) */
550       Thread.currentThread().setContextClassLoader(contextClassLoader);
551
552       /** Close the connection */
553       try
554       {
555         connection.close();
556       }
557       catch (SQLException e)
558       {
559         getLog().error("Error while closing connection: " + e.getMessage());
560       }
561     }
562
563     /** Write timestamps for annotated classes to file */
564     try
565     {
566       FileOutputStream fos = new FileOutputStream(saved);
567       ObjectOutputStream oos = new ObjectOutputStream(fos);
568       oos.writeObject(md5s);
569       oos.close();
570       fos.close();
571     }
572     catch (Exception e)
573     {
574       getLog().error("Cannot write timestamps to file: " + e);
575     }
576   }
577
578   /**
579    * Needed, because DriverManager won't pick up drivers, that were not
580    * loaded by the system-classloader!
581    * See:
582    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
583    */
584   static final class DriverProxy implements Driver
585   {
586     private final Driver target;
587
588     DriverProxy(Driver target)
589     {
590       if (target == null)
591         throw new NullPointerException();
592       this.target = target;
593     }
594
595     public java.sql.Driver getTarget()
596     {
597       return target;
598     }
599
600     @Override
601     public boolean acceptsURL(String url) throws SQLException
602     {
603       return target.acceptsURL(url);
604     }
605
606     @Override
607     public java.sql.Connection connect(
608         String url,
609         java.util.Properties info
610       )
611       throws
612         SQLException
613     {
614       return target.connect(url, info);
615     }
616
617     @Override
618     public int getMajorVersion()
619     {
620       return target.getMajorVersion();
621     }
622
623     @Override
624     public int getMinorVersion()
625     {
626       return target.getMinorVersion();
627     }
628
629     @Override
630     public DriverPropertyInfo[] getPropertyInfo(
631         String url,
632         Properties info
633       )
634       throws
635         SQLException
636     {
637       return target.getPropertyInfo(url, info);
638     }
639
640     @Override
641     public boolean jdbcCompliant()
642     {
643       return target.jdbcCompliant();
644     }
645
646     /**
647      * This Method cannot be annotated with @Override, becaus the plugin
648      * will not compile then under Java 1.6!
649      */
650     public Logger getParentLogger() throws SQLFeatureNotSupportedException
651     {
652       throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
653     }
654
655     @Override
656     public String toString()
657     {
658       return "Proxy: " + target;
659     }
660
661     @Override
662     public int hashCode()
663     {
664       return target.hashCode();
665     }
666
667     @Override
668     public boolean equals(Object obj)
669     {
670       if (!(obj instanceof DriverProxy))
671         return false;
672       DriverProxy other = (DriverProxy) obj;
673       return this.target.equals(other.target);
674     }
675   }
676 }