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