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