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