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