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