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