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