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