e4a301e76845812db3aa1b02a3cf5387977974f1
[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 the value " + password
512           );
513       else
514         getLog().debug("Using the value " + 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 the value " + hibernateDialect
524           );
525       else
526         getLog().debug("Using the value " + hibernateDialect);
527       properties.setProperty(DIALECT, hibernateDialect);
528     }
529     if ( hibernateNamingStrategy != null )
530     {
531       if ( properties.contains(NAMING_STRATEGY))
532         getLog().debug(
533             "Overwriting property " +
534             NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
535             " with the value " + hibernateNamingStrategy
536            );
537       else
538         getLog().debug("Using the value " + hibernateNamingStrategy);
539       properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
540     }
541     if (envers)
542     {
543       if (properties.containsKey(ENVERS))
544         getLog().debug(
545             "Overwriting property " +
546             ENVERS + "=" + properties.getProperty(ENVERS) +
547             " with the value " + envers
548           );
549       else
550         getLog().debug("Using the value " + envers);
551       properties.setProperty(ENVERS, Boolean.toString(envers));
552     }
553
554     /** The generated SQL varies with the dialect! */
555     if (md5s.containsKey(DIALECT))
556     {
557       String dialect = properties.getProperty(DIALECT);
558       if (md5s.get(DIALECT).equals(dialect))
559         getLog().debug("SQL-dialect unchanged.");
560       else
561       {
562         getLog().debug("SQL-dialect changed: " + dialect);
563         modified = true;
564         md5s.put(DIALECT, dialect);
565       }
566     }
567     else
568     {
569       modified = true;
570       md5s.put(DIALECT, properties.getProperty(DIALECT));
571     }
572
573     /** The generated SQL varies with the envers-configuration */
574     if (md5s.containsKey(ENVERS))
575     {
576       String envers = properties.getProperty(ENVERS);
577       if (md5s.get(ENVERS).equals(envers))
578         getLog().debug("Envers unchanged.");
579       else
580       {
581         getLog().debug("Envers changed: " + envers);
582         modified = true;
583         md5s.put(ENVERS, envers);
584       }
585     }
586     else
587     {
588       modified = true;
589       md5s.put(ENVERS, properties.getProperty(ENVERS));
590     }
591
592     if (properties.isEmpty())
593     {
594       getLog().error("No properties set!");
595       throw new MojoFailureException("Hibernate-Configuration is missing!");
596     }
597
598     Configuration config = new Configuration();
599     config.setProperties(properties);
600
601     if ( properties.containsKey(NAMING_STRATEGY))
602     {
603       String namingStrategy = properties.getProperty(NAMING_STRATEGY);
604       getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
605       try
606       {
607         @SuppressWarnings("unchecked")
608         Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
609         config.setNamingStrategy(namingStrategyClass.newInstance());
610       }
611       catch (Exception e)
612       {
613         getLog().error("Error setting NamingStrategy", e);
614         throw new MojoExecutionException(e.getMessage());
615       }
616     }
617
618     getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
619     for (Class<?> annotatedClass : classes)
620     {
621       getLog().debug("Class " + annotatedClass);
622       config.addAnnotatedClass(annotatedClass);
623     }
624
625     if (hibernateMapping != null)
626     {
627       try
628       {
629         MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
630         for (String filename : hibernateMapping.split("[\\s,]+"))
631         {
632           // First try the filename as absolute/relative path
633           File file = new File(filename);
634           if (!file.exists())
635           {
636             // If the file was not found, search for it in the resource-directories
637             for (Resource resource : project.getResources())
638             {
639               file = new File(resource.getDirectory() + File.separator + filename);
640               if (file.exists())
641                 break;
642             }
643           }
644           if (file != null && file.exists())
645           {
646             InputStream is = new FileInputStream(file);
647             byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
648             int i;
649             while((i = is.read(buffer)) > -1)
650               digest.update(buffer, 0, i);
651             is.close();
652             byte[] bytes = digest.digest();
653             BigInteger bi = new BigInteger(1, bytes);
654             String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
655             String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
656             if (!newMd5.equals(oldMd5))
657             {
658               getLog().debug("Found new or modified mapping-file: " + filename);
659               modified = true;
660               md5s.put(filename, newMd5);
661             }
662             else
663             {
664               getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
665             }
666             getLog().debug("Adding mappings from XML-configurationfile: " + file);
667             config.addFile(file);
668           }
669           else
670             throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
671         }
672       }
673       catch (NoSuchAlgorithmException e)
674       {
675         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
676       }
677       catch (FileNotFoundException e)
678       {
679         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
680       }
681       catch (IOException e)
682       {
683         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
684       }
685     }
686
687     Target target = null;
688     try
689     {
690       target = Target.valueOf(this.target.toUpperCase());
691     }
692     catch (IllegalArgumentException e)
693     {
694       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
695       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
696       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
697     }
698     Type type = null;
699     try
700     {
701       type = Type.valueOf(this.type.toUpperCase());
702     }
703     catch (IllegalArgumentException e)
704     {
705       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
706       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
707       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
708     }
709
710     if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
711     {
712       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
713     }
714     if (
715         !modified
716         && !target.equals(Target.SCRIPT)
717         && !target.equals(Target.NONE)
718         && !force
719       )
720     {
721       getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
722       getLog().info("Skipping schema generation!");
723       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
724       return;
725     }
726
727     getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
728     for (Entry<Object,Object> entry : properties.entrySet())
729       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
730
731     Connection connection = null;
732     try
733     {
734       /**
735        * The connection must be established outside of hibernate, because
736        * hibernate does not use the context-classloader of the current
737        * thread and, hence, would not be able to resolve the driver-class!
738        */
739       getLog().debug("Target: " + target + ", Type: " + type);
740       switch (target)
741       {
742         case EXPORT:
743         case BOTH:
744           switch (type)
745           {
746             case CREATE:
747             case DROP:
748             case BOTH:
749               Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
750               getLog().debug("Registering JDBC-driver " + driverClass.getName());
751               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
752               getLog().debug(
753                   "Opening JDBC-connection to "
754                   + properties.getProperty(URL)
755                   + " as "
756                   + properties.getProperty(USERNAME)
757                   + " with password "
758                   + properties.getProperty(PASSWORD)
759                   );
760               connection = DriverManager.getConnection(
761                   properties.getProperty(URL),
762                   properties.getProperty(USERNAME),
763                   properties.getProperty(PASSWORD)
764                   );
765           }
766       }
767     }
768     catch (ClassNotFoundException e)
769     {
770       getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
771       throw new MojoExecutionException(e.getMessage());
772     }
773     catch (Exception e)
774     {
775       getLog().error("Cannot establish connection to database!");
776       Enumeration<Driver> drivers = DriverManager.getDrivers();
777       if (!drivers.hasMoreElements())
778         getLog().error("No drivers registered!");
779       while (drivers.hasMoreElements())
780         getLog().debug("Driver: " + drivers.nextElement());
781       throw new MojoExecutionException(e.getMessage());
782     }
783
784     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
785     MavenLogAppender.startPluginLog(this);
786     try
787     {
788       /**
789        * Change class-loader of current thread, so that hibernate can
790        * see all dependencies!
791        */
792       Thread.currentThread().setContextClassLoader(classLoader);
793
794       config.buildMappings();
795
796       if ("true".equals(properties.getProperty(ENVERS)))
797       {
798         getLog().debug("Using envers");
799         AuditConfiguration.getFor(config);
800       }
801
802       SchemaExport export = new SchemaExport(config, connection);
803       export.setOutputFile(outputFile);
804       export.setDelimiter(delimiter);
805       export.setFormat(format);
806       export.execute(target, type);
807
808       for (Object exception : export.getExceptions())
809         getLog().debug(exception.toString());
810     }
811     finally
812     {
813       /** Stop Log-Capturing */
814       MavenLogAppender.endPluginLog(this);
815
816       /** Restore the old class-loader (TODO: is this really necessary?) */
817       Thread.currentThread().setContextClassLoader(contextClassLoader);
818
819       /** Close the connection */
820       try
821       {
822         if (connection != null)
823           connection.close();
824       }
825       catch (SQLException e)
826       {
827         getLog().error("Error while closing connection: " + e.getMessage());
828       }
829     }
830
831     /** Write md5-sums for annotated classes to file */
832     try
833     {
834       FileOutputStream fos = new FileOutputStream(saved);
835       ObjectOutputStream oos = new ObjectOutputStream(fos);
836       oos.writeObject(md5s);
837       oos.close();
838       fos.close();
839     }
840     catch (Exception e)
841     {
842       getLog().error("Cannot write md5-sums to file: " + e);
843     }
844   }
845
846   /**
847    * Needed, because DriverManager won't pick up drivers, that were not
848    * loaded by the system-classloader!
849    * See:
850    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
851    */
852   static final class DriverProxy implements Driver
853   {
854     private final Driver target;
855
856     DriverProxy(Driver target)
857     {
858       if (target == null)
859         throw new NullPointerException();
860       this.target = target;
861     }
862
863     public java.sql.Driver getTarget()
864     {
865       return target;
866     }
867
868     @Override
869     public boolean acceptsURL(String url) throws SQLException
870     {
871       return target.acceptsURL(url);
872     }
873
874     @Override
875     public java.sql.Connection connect(
876         String url,
877         java.util.Properties info
878       )
879       throws
880         SQLException
881     {
882       return target.connect(url, info);
883     }
884
885     @Override
886     public int getMajorVersion()
887     {
888       return target.getMajorVersion();
889     }
890
891     @Override
892     public int getMinorVersion()
893     {
894       return target.getMinorVersion();
895     }
896
897     @Override
898     public DriverPropertyInfo[] getPropertyInfo(
899         String url,
900         Properties info
901       )
902       throws
903         SQLException
904     {
905       return target.getPropertyInfo(url, info);
906     }
907
908     @Override
909     public boolean jdbcCompliant()
910     {
911       return target.jdbcCompliant();
912     }
913
914     /**
915      * This Method cannot be annotated with @Override, becaus the plugin
916      * will not compile then under Java 1.6!
917      */
918     public Logger getParentLogger() throws SQLFeatureNotSupportedException
919     {
920       throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
921     }
922
923     @Override
924     public String toString()
925     {
926       return "Proxy: " + target;
927     }
928
929     @Override
930     public int hashCode()
931     {
932       return target.hashCode();
933     }
934
935     @Override
936     public boolean equals(Object obj)
937     {
938       if (!(obj instanceof DriverProxy))
939         return false;
940       DriverProxy other = (DriverProxy) obj;
941       return this.target.equals(other.target);
942     }
943   }
944 }