Fixed failure when target/classes does not exist when runnin mvn test phase
[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     Map<String,String> md5s;
293     boolean modified = false;
294     File saved = new File(buildDirectory + File.separator + MD5S);
295
296     if (saved.exists())
297     {
298       try
299       {
300         FileInputStream fis = new FileInputStream(saved);
301         ObjectInputStream ois = new ObjectInputStream(fis);
302         md5s = (HashMap<String,String>)ois.readObject();
303         ois.close();
304       }
305       catch (Exception e)
306       {
307         md5s = new HashMap<String,String>();
308         getLog().warn("Cannot read timestamps from saved: " + e);
309       }
310     }
311     else
312     {
313       md5s = new HashMap<String,String>();
314       try
315       {
316         saved.createNewFile();
317       }
318       catch (IOException e)
319       {
320         getLog().debug("Cannot create file \"" + saved.getPath() + "\" for timestamps: " + e);
321       }
322     }
323
324     ClassLoader classLoader = null;
325     try
326     {
327       getLog().debug("Creating ClassLoader for project-dependencies...");
328       List<String> classpathFiles = project.getCompileClasspathElements();
329       if (scanTestClasses)
330         classpathFiles.addAll(project.getTestClasspathElements());
331       URL[] urls = new URL[classpathFiles.size()];
332       for (int i = 0; i < classpathFiles.size(); ++i)
333       {
334         getLog().debug("Dependency: " + classpathFiles.get(i));
335         urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
336       }
337       classLoader = new URLClassLoader(urls, getClass().getClassLoader());
338     }
339     catch (Exception e)
340     {
341       getLog().error("Error while creating ClassLoader!", e);
342       throw new MojoExecutionException(e.getMessage());
343     }
344
345     Set<Class<?>> classes =
346         new TreeSet<Class<?>>(
347             new Comparator<Class<?>>() {
348               @Override
349               public int compare(Class<?> a, Class<?> b)
350               {
351                 return a.getName().compareTo(b.getName());
352               }
353             }
354           );
355
356     try
357     {
358       AnnotationDB db = new AnnotationDB();
359       File dir = new File(outputDirectory);
360       if (dir.exists())
361       {
362         getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
363         URL dirUrl = dir.toURI().toURL();
364         db.scanArchives(dirUrl);
365       }
366       if (scanTestClasses)
367       {
368         dir = new File(testOutputDirectory);
369         if (dir.exists())
370         {
371           getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
372           URL dirUrl = dir.toURI().toURL();
373           db.scanArchives(dirUrl);
374         }
375       }
376
377       Set<String> classNames = new HashSet<String>();
378       if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
379         classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
380       if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
381         classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
382       if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
383         classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
384
385       MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
386       for (String name : classNames)
387       {
388         Class<?> annotatedClass = classLoader.loadClass(name);
389         classes.add(annotatedClass);
390         String resourceName = annotatedClass.getName();
391         resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
392         InputStream is =
393             annotatedClass
394                 .getResourceAsStream(resourceName);
395         byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
396         int i;
397         while((i = is.read(buffer)) > -1)
398           digest.update(buffer, 0, i);
399         is.close();
400         byte[] bytes = digest.digest();
401         BigInteger bi = new BigInteger(1, bytes);
402         String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
403         String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
404         if (!newMd5.equals(oldMd5))
405         {
406           getLog().debug("Found new or modified annotated class: " + name);
407           modified = true;
408           md5s.put(name, newMd5);
409         }
410         else
411         {
412           getLog().debug(oldMd5 + " -> class unchanged: " + name);
413         }
414       }
415     }
416     catch (ClassNotFoundException e)
417     {
418       getLog().error("Error while adding annotated classes!", e);
419       throw new MojoExecutionException(e.getMessage());
420     }
421     catch (Exception e)
422     {
423       getLog().error("Error while scanning!", e);
424       throw new MojoFailureException(e.getMessage());
425     }
426
427     if (classes.isEmpty())
428     {
429       if (hibernateMapping == null || hibernateMapping.isEmpty())
430         throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
431     }
432     else
433     {
434       getLog().debug("Detected classes with mapping-annotations:");
435       for (Class<?> annotatedClass : classes)
436         getLog().debug("  " + annotatedClass.getName());
437     }
438
439
440     Properties properties = new Properties();
441
442     /** Try to read configuration from properties-file */
443     try
444     {
445       File file = new File(hibernateProperties);
446       if (file.exists())
447       {
448         getLog().info("Reading properties from file " + hibernateProperties + "...");
449         properties.load(new FileInputStream(file));
450       }
451       else
452         getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
453     }
454     catch (IOException e)
455     {
456       getLog().error("Error while reading properties!", e);
457       throw new MojoExecutionException(e.getMessage());
458     }
459
460     /** Overwrite values from propertie-file or set, if given */
461     if (driverClassName != null)
462     {
463       if (properties.containsKey(DRIVER_CLASS))
464         getLog().debug(
465             "Overwriting property " +
466             DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
467             " with the value " + driverClassName
468           );
469       else
470         getLog().debug("Using the value " + driverClassName);
471       properties.setProperty(DRIVER_CLASS, driverClassName);
472     }
473     if (url != null)
474     {
475       if (properties.containsKey(URL))
476         getLog().debug(
477             "Overwriting property " +
478             URL + "=" + properties.getProperty(URL) +
479             " with the value " + url
480           );
481       else
482         getLog().debug("Using the value " + url);
483       properties.setProperty(URL, url);
484     }
485     if (username != null)
486     {
487       if (properties.containsKey(USERNAME))
488         getLog().debug(
489             "Overwriting property " +
490             USERNAME + "=" + properties.getProperty(USERNAME) +
491             " with the value " + username
492           );
493       else
494         getLog().debug("Using the value " + username);
495       properties.setProperty(USERNAME, username);
496     }
497     if (password != null)
498     {
499       if (properties.containsKey(PASSWORD))
500         getLog().debug(
501             "Overwriting property " +
502             PASSWORD + "=" + properties.getProperty(PASSWORD) +
503             " with the value " + password
504           );
505       else
506         getLog().debug("Using the value " + password);
507       properties.setProperty(PASSWORD, password);
508     }
509     if (hibernateDialect != null)
510     {
511       if (properties.containsKey(DIALECT))
512         getLog().debug(
513             "Overwriting property " +
514             DIALECT + "=" + properties.getProperty(DIALECT) +
515             " with the value " + hibernateDialect
516           );
517       else
518         getLog().debug("Using the value " + hibernateDialect);
519       properties.setProperty(DIALECT, hibernateDialect);
520     }
521     if ( hibernateNamingStrategy != null )
522     {
523       if ( properties.contains(NAMING_STRATEGY))
524         getLog().debug(
525             "Overwriting property " +
526             NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
527             " with the value " + hibernateNamingStrategy
528            );
529       else
530         getLog().debug("Using the value " + hibernateNamingStrategy);
531       properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
532     }
533
534     /** The generated SQL varies with the dialect! */
535     if (md5s.containsKey(DIALECT))
536     {
537       String dialect = properties.getProperty(DIALECT);
538       if (md5s.get(DIALECT).equals(dialect))
539         getLog().debug("SQL-dialect unchanged.");
540       else
541       {
542         getLog().debug("SQL-dialect changed: " + dialect);
543         modified = true;
544         md5s.put(DIALECT, dialect);
545       }
546     }
547     else
548     {
549       modified = true;
550       md5s.put(DIALECT, properties.getProperty(DIALECT));
551     }
552
553     if (properties.isEmpty())
554     {
555       getLog().error("No properties set!");
556       throw new MojoFailureException("Hibernate-Configuration is missing!");
557     }
558
559     Configuration config = new Configuration();
560     config.setProperties(properties);
561
562     if ( properties.containsKey(NAMING_STRATEGY))
563     {
564       String namingStrategy = properties.getProperty(NAMING_STRATEGY);
565       getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
566       try
567       {
568         @SuppressWarnings("unchecked")
569         Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
570         config.setNamingStrategy(namingStrategyClass.newInstance());
571       }
572       catch (Exception e)
573       {
574         getLog().error("Error setting NamingStrategy", e);
575         throw new MojoExecutionException(e.getMessage());
576       }
577     }
578
579     getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
580     for (Class<?> annotatedClass : classes)
581     {
582       getLog().debug("Class " + annotatedClass);
583       config.addAnnotatedClass(annotatedClass);
584     }
585
586     if (hibernateMapping != null)
587     {
588       try
589       {
590         MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
591         for (String filename : hibernateMapping.split("[\\s,]+"))
592         {
593           // First try the filename as absolute/relative path
594           File file = new File(filename);
595           if (!file.exists())
596           {
597             // If the file was not found, search for it in the resource-directories
598             for (Resource resource : project.getResources())
599             {
600               file = new File(resource.getDirectory() + File.separator + filename);
601               if (file.exists())
602                 break;
603             }
604           }
605           if (file != null && file.exists())
606           {
607             InputStream is = new FileInputStream(file);
608             byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
609             int i;
610             while((i = is.read(buffer)) > -1)
611               digest.update(buffer, 0, i);
612             is.close();
613             byte[] bytes = digest.digest();
614             BigInteger bi = new BigInteger(1, bytes);
615             String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
616             String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
617             if (!newMd5.equals(oldMd5))
618             {
619               getLog().debug("Found new or modified mapping-file: " + filename);
620               modified = true;
621               md5s.put(filename, newMd5);
622             }
623             else
624             {
625               getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
626             }
627             getLog().debug("Adding mappings from XML-configurationfile: " + file);
628             config.addFile(file);
629           }
630           else
631             throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
632         }
633       }
634       catch (NoSuchAlgorithmException e)
635       {
636         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
637       }
638       catch (FileNotFoundException e)
639       {
640         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
641       }
642       catch (IOException e)
643       {
644         throw new MojoFailureException("Cannot calculate MD5-summs!", e);
645       }
646     }
647
648     Target target = null;
649     try
650     {
651       target = Target.valueOf(this.target.toUpperCase());
652     }
653     catch (IllegalArgumentException e)
654     {
655       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
656       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
657       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
658     }
659     Type type = null;
660     try
661     {
662       type = Type.valueOf(this.type.toUpperCase());
663     }
664     catch (IllegalArgumentException e)
665     {
666       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
667       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
668       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
669     }
670
671     if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
672     {
673       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
674     }
675     if (
676         !modified
677         && !target.equals(Target.SCRIPT)
678         && !target.equals(Target.NONE)
679         && !force
680       )
681     {
682       getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
683       getLog().info("Skipping schema generation!");
684       project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
685       return;
686     }
687
688     getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
689     for (Entry<Object,Object> entry : properties.entrySet())
690       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
691
692     Connection connection = null;
693     try
694     {
695       /**
696        * The connection must be established outside of hibernate, because
697        * hibernate does not use the context-classloader of the current
698        * thread and, hence, would not be able to resolve the driver-class!
699        */
700       getLog().debug("Target: " + target + ", Type: " + type);
701       switch (target)
702       {
703         case EXPORT:
704         case BOTH:
705           switch (type)
706           {
707             case CREATE:
708             case DROP:
709             case BOTH:
710               Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
711               getLog().debug("Registering JDBC-driver " + driverClass.getName());
712               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
713               getLog().debug(
714                   "Opening JDBC-connection to "
715                   + properties.getProperty(URL)
716                   + " as "
717                   + properties.getProperty(USERNAME)
718                   + " with password "
719                   + properties.getProperty(PASSWORD)
720                   );
721               connection = DriverManager.getConnection(
722                   properties.getProperty(URL),
723                   properties.getProperty(USERNAME),
724                   properties.getProperty(PASSWORD)
725                   );
726           }
727       }
728     }
729     catch (ClassNotFoundException e)
730     {
731       getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
732       throw new MojoExecutionException(e.getMessage());
733     }
734     catch (Exception e)
735     {
736       getLog().error("Cannot establish connection to database!");
737       Enumeration<Driver> drivers = DriverManager.getDrivers();
738       if (!drivers.hasMoreElements())
739         getLog().error("No drivers registered!");
740       while (drivers.hasMoreElements())
741         getLog().debug("Driver: " + drivers.nextElement());
742       throw new MojoExecutionException(e.getMessage());
743     }
744
745     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
746     MavenLogAppender.startPluginLog(this);
747     try
748     {
749       /**
750        * Change class-loader of current thread, so that hibernate can
751        * see all dependencies!
752        */
753       Thread.currentThread().setContextClassLoader(classLoader);
754
755       SchemaExport export = new SchemaExport(config, connection);
756       export.setOutputFile(outputFile);
757       export.setDelimiter(delimiter);
758       export.setFormat(format);
759       export.execute(target, type);
760
761       for (Object exception : export.getExceptions())
762         getLog().debug(exception.toString());
763     }
764     finally
765     {
766       /** Stop Log-Capturing */
767       MavenLogAppender.endPluginLog(this);
768
769       /** Restore the old class-loader (TODO: is this really necessary?) */
770       Thread.currentThread().setContextClassLoader(contextClassLoader);
771
772       /** Close the connection */
773       try
774       {
775         if (connection != null)
776           connection.close();
777       }
778       catch (SQLException e)
779       {
780         getLog().error("Error while closing connection: " + e.getMessage());
781       }
782     }
783
784     /** Write md5-sums for annotated classes to file */
785     try
786     {
787       FileOutputStream fos = new FileOutputStream(saved);
788       ObjectOutputStream oos = new ObjectOutputStream(fos);
789       oos.writeObject(md5s);
790       oos.close();
791       fos.close();
792     }
793     catch (Exception e)
794     {
795       getLog().error("Cannot write md5-sums to file: " + e);
796     }
797   }
798
799   /**
800    * Needed, because DriverManager won't pick up drivers, that were not
801    * loaded by the system-classloader!
802    * See:
803    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
804    */
805   static final class DriverProxy implements Driver
806   {
807     private final Driver target;
808
809     DriverProxy(Driver target)
810     {
811       if (target == null)
812         throw new NullPointerException();
813       this.target = target;
814     }
815
816     public java.sql.Driver getTarget()
817     {
818       return target;
819     }
820
821     @Override
822     public boolean acceptsURL(String url) throws SQLException
823     {
824       return target.acceptsURL(url);
825     }
826
827     @Override
828     public java.sql.Connection connect(
829         String url,
830         java.util.Properties info
831       )
832       throws
833         SQLException
834     {
835       return target.connect(url, info);
836     }
837
838     @Override
839     public int getMajorVersion()
840     {
841       return target.getMajorVersion();
842     }
843
844     @Override
845     public int getMinorVersion()
846     {
847       return target.getMinorVersion();
848     }
849
850     @Override
851     public DriverPropertyInfo[] getPropertyInfo(
852         String url,
853         Properties info
854       )
855       throws
856         SQLException
857     {
858       return target.getPropertyInfo(url, info);
859     }
860
861     @Override
862     public boolean jdbcCompliant()
863     {
864       return target.jdbcCompliant();
865     }
866
867     /**
868      * This Method cannot be annotated with @Override, becaus the plugin
869      * will not compile then under Java 1.6!
870      */
871     public Logger getParentLogger() throws SQLFeatureNotSupportedException
872     {
873       throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
874     }
875
876     @Override
877     public String toString()
878     {
879       return "Proxy: " + target;
880     }
881
882     @Override
883     public int hashCode()
884     {
885       return target.hashCode();
886     }
887
888     @Override
889     public boolean equals(Object obj)
890     {
891       if (!(obj instanceof DriverProxy))
892         return false;
893       DriverProxy other = (DriverProxy) obj;
894       return this.target.equals(other.target);
895     }
896   }
897 }