1017ae6c864e963f380164ad3f1241cb0ae26a4e
[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.IOException;
23 import java.net.URL;
24 import java.net.URLClassLoader;
25 import java.sql.Connection;
26 import java.sql.Driver;
27 import java.sql.DriverManager;
28 import java.sql.DriverPropertyInfo;
29 import java.sql.SQLException;
30 import java.util.Enumeration;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
35 import java.util.Set;
36 import javax.persistence.Embeddable;
37 import javax.persistence.Entity;
38 import javax.persistence.MappedSuperclass;
39 import org.apache.maven.plugin.AbstractMojo;
40 import org.apache.maven.plugin.MojoExecutionException;
41 import org.apache.maven.plugin.MojoFailureException;
42 import org.apache.maven.project.MavenProject;
43 import org.hibernate.cfg.Configuration;
44 import org.hibernate.tool.hbm2ddl.SchemaExport;
45 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
46 import org.hibernate.tool.hbm2ddl.Target;
47 import org.scannotation.AnnotationDB;
48
49
50 /**
51  * Goal which extracts the hibernate-mapping-configuration and
52  * exports an according SQL-database-schema.
53  *
54  * @goal export
55  * @phase process-classes
56  * @threadSafe
57  * @requiresDependencyResolution runtime
58  */
59 public class Hbm2DdlMojo extends AbstractMojo
60 {
61   public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
62   public final static String URL = "hibernate.connection.url";
63   public final static String USERNAME = "hibernate.connection.username";
64   public final static String PASSWORD = "hibernate.connection.password";
65   public final static String DIALECT = "hibernate.dialect";
66
67
68   /**
69    * The project whose project files to create.
70    *
71    * @parameter expression="${project}"
72    * @required
73    * @readonly
74    */
75   private MavenProject project;
76
77   /**
78    * Directories to scan.
79    *
80    * @parameter expression="${project.build.outputDirectory}"
81    */
82   private String outputDirectory;
83
84   /**
85    * Skip execution
86    *
87    * @parameter expression="${maven.test.skip}"
88    */
89   private boolean skip;
90
91   /**
92    * SQL-Driver name.
93    *
94    * @parameter expression="${hibernate.connection.driver_class}
95    */
96   private String driverClassName;
97
98   /**
99    * Database URL.
100    *
101    * @parameter expression="${hibernate.connection.url}"
102    */
103   private String url;
104
105   /**
106    * Database username
107    *
108    * @parameter expression="${hibernate.connection.username}"
109    */
110   private String username;
111
112   /**
113    * Database password
114    *
115    * @parameter expression="${hibernate.connection.password}"
116    */
117   private String password;
118
119   /**
120    * Hibernate dialect.
121    *
122    * @parameter expression="${hibernate.dialect}"
123    */
124   private String hibernateDialect;
125
126   /**
127    * Hibernate configuration file.
128    *
129    * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
130    */
131   private String hibernateProperties;
132
133   /**
134    * Target of execution:
135    * <ul>
136    *   <li><strong>NONE</strong> do nothing - just validate the configuration</li>
137    *   <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
138    *   <li><strong>SCRIPT</strong> export schema to SQL-script</li>
139    *   <li><strong>BOTH</strong></li>
140    * </ul>
141    * @parameter default-value="EXPORT"
142    */
143   private String target;
144
145   /**
146    * Type of export.
147    * <ul>
148    *   <li><strong>NONE</strong> do nothing - just validate the configuration</li>
149    *   <li><strong>CREATE</strong> create database-schema</li>
150    *   <li><strong>DROP</strong> drop database-schema</li>
151    *   <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
152    * </ul>
153    * @parameter default-value="BOTH"
154    */
155   private String type;
156
157   /**
158    * Output file.
159    *
160    * @parameter default-value="${project.build.outputDirectory}/schema.sql"
161    */
162   private String outputFile;
163
164   /**
165    * Delimiter in output-file.
166    *
167    * @parameter default-value=";"
168    */
169   private String delimiter;
170
171   /**
172    * Format output-file.
173    *
174    * @parameter default-value="true"
175    */
176   private boolean format;
177
178
179   @Override
180   public void execute()
181     throws
182       MojoFailureException,
183       MojoExecutionException
184   {
185     if (skip)
186       return;
187
188     File dir = new File(outputDirectory);
189     if (!dir.exists())
190       throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
191
192
193     Set<String> classes = new HashSet<String>();
194     try
195     {
196       AnnotationDB db = new AnnotationDB();
197       getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
198       URL dirUrl = dir.toURI().toURL();
199       db.scanArchives(dirUrl);
200       if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
201         classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
202       if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
203         classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
204       if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
205         classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
206     }
207     catch (IOException e)
208     {
209       getLog().error("Error while scanning!", e);
210       throw new MojoFailureException(e.getMessage());
211     }
212     if (classes.isEmpty())
213       throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
214
215     Properties properties = new Properties();
216
217     /** Try to read configuration from properties-file */
218     try
219     {
220       File file = new File(hibernateProperties);
221       if (file.exists())
222       {
223         getLog().info("Reading properties from file " + hibernateProperties + "...");
224         properties.load(new FileInputStream(file));
225       }
226       else
227         getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
228     }
229     catch (IOException e)
230     {
231       getLog().error("Error while reading properties!", e);
232       throw new MojoExecutionException(e.getMessage());
233     }
234
235     /** Overwrite values from propertie-file or set, if given */
236     if (driverClassName != null)
237     {
238       if (properties.containsKey(DRIVER_CLASS))
239         getLog().debug(
240             "Overwriting property " +
241             DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
242             " with the value " + driverClassName +
243             " from the plugin-configuration-parameter driverClassName!"
244           );
245       else
246         getLog().debug(
247             "Using the value " + driverClassName +
248             " from the plugin-configuration-parameter driverClassName!"
249           );
250       properties.setProperty(DRIVER_CLASS, driverClassName);
251     }
252     if (url != null)
253     {
254       if (properties.containsKey(URL))
255         getLog().debug(
256             "Overwriting property " +
257             URL + "=" + properties.getProperty(URL) +
258             " with the value " + url +
259             " from the plugin-configuration-parameter url!"
260           );
261       else
262         getLog().debug(
263             "Using the value " + url +
264             " from the plugin-configuration-parameter url!"
265           );
266       properties.setProperty(URL, url);
267     }
268     if (username != null)
269     {
270       if (properties.containsKey(USERNAME))
271         getLog().debug(
272             "Overwriting property " +
273             USERNAME + "=" + properties.getProperty(USERNAME) +
274             " with the value " + username +
275             " from the plugin-configuration-parameter username!"
276           );
277       else
278         getLog().debug(
279             "Using the value " + username +
280             " from the plugin-configuration-parameter username!"
281           );
282       properties.setProperty(USERNAME, username);
283     }
284     if (password != null)
285     {
286       if (properties.containsKey(PASSWORD))
287         getLog().debug(
288             "Overwriting property " +
289             PASSWORD + "=" + properties.getProperty(PASSWORD) +
290             " with the value " + password +
291             " from the plugin-configuration-parameter password!"
292           );
293       else
294         getLog().debug(
295             "Using the value " + password +
296             " from the plugin-configuration-parameter password!"
297           );
298       properties.setProperty(PASSWORD, password);
299     }
300     if (hibernateDialect != null)
301     {
302       if (properties.containsKey(DIALECT))
303         getLog().debug(
304             "Overwriting property " +
305             DIALECT + "=" + properties.getProperty(DIALECT) +
306             " with the value " + hibernateDialect +
307             " from the plugin-configuration-parameter hibernateDialect!"
308           );
309       else
310         getLog().debug(
311             "Using the value " + hibernateDialect +
312             " from the plugin-configuration-parameter hibernateDialect!"
313           );
314       properties.setProperty(DIALECT, hibernateDialect);
315     }
316
317     getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
318     if (properties.isEmpty())
319     {
320       getLog().error("No properties set!");
321       throw new MojoFailureException("Hibernate-Configuration is missing!");
322     }
323     for (Entry<Object,Object> entry : properties.entrySet())
324       getLog().info("  " + entry.getKey() + " = " + entry.getValue());
325
326     ClassLoader classLoader = null;
327     try
328     {
329       getLog().debug("Creating ClassLoader for project-dependencies...");
330       List<String> classpathFiles = project.getCompileClasspathElements();
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     Configuration config = new Configuration();
346     config.setProperties(properties);
347     try
348     {
349       getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
350       for (String annotatedClass : classes)
351       {
352         getLog().debug("Class " + annotatedClass);
353         config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
354       }
355     }
356     catch (ClassNotFoundException e)
357     {
358       getLog().error("Error while adding annotated classes!", e);
359       throw new MojoExecutionException(e.getMessage());
360     }
361
362     Target target = null;
363     try
364     {
365       target = Target.valueOf(this.target);
366     }
367     catch (IllegalArgumentException e)
368     {
369       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
370       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
371       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
372     }
373     Type type = null;
374     try
375     {
376       type = Type.valueOf(this.type);
377     }
378     catch (IllegalArgumentException e)
379     {
380       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
381       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
382       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
383     }
384
385     Connection connection = null;
386     try
387     {
388       /**
389        * The connection must be established outside of hibernate, because
390        * hibernate does not use the context-classloader of the current
391        * thread and, hence, would not be able to resolve the driver-class!
392        */
393       switch (target)
394       {
395         case EXPORT:
396         case BOTH:
397           switch (type)
398           {
399             case CREATE:
400             case DROP:
401             case BOTH:
402               Class driverClass = classLoader.loadClass(driverClassName);
403               getLog().debug("Registering JDBC-driver " + driverClass.getName());
404               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
405               getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
406               connection = DriverManager.getConnection(url, username, password);
407           }
408       }
409     }
410     catch (ClassNotFoundException e)
411     {
412       getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
413       throw new MojoExecutionException(e.getMessage());
414     }
415     catch (Exception e)
416     {
417       getLog().error("Cannot establish connection to database!");
418       Enumeration<Driver> drivers = DriverManager.getDrivers();
419       if (!drivers.hasMoreElements())
420         getLog().error("No drivers registered!");
421       while (drivers.hasMoreElements())
422         getLog().debug("Driver: " + drivers.nextElement());
423       throw new MojoExecutionException(e.getMessage());
424     }
425
426     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
427     MavenLogAppender.startPluginLog(this);
428     try
429     {
430       /**
431        * Change class-loader of current thread, so that hibernate can
432        * see all dependencies!
433        */
434       Thread.currentThread().setContextClassLoader(classLoader);
435
436       SchemaExport export = new SchemaExport(config, connection);
437       export.setOutputFile(outputFile);
438       export.setDelimiter(delimiter);
439       export.setFormat(format);
440       export.execute(target, type);
441
442       for (Object exception : export.getExceptions())
443         getLog().debug(exception.toString());
444     }
445     finally
446     {
447       /** Stop Log-Capturing */
448       MavenLogAppender.endPluginLog(this);
449
450       /** Restore the old class-loader (TODO: is this really necessary?) */
451       Thread.currentThread().setContextClassLoader(contextClassLoader);
452
453       /** Close the connection */
454       try
455       {
456         connection.close();
457       }
458       catch (SQLException e)
459       {
460         getLog().error("Error while closing connection: " + e.getMessage());
461       }
462     }
463   }
464
465   /**
466    * Needed, because DriverManager won't pick up drivers, that were not
467    * loaded by the system-classloader!
468    * See:
469    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
470    */
471   static final class DriverProxy implements Driver
472   {
473     private final Driver target;
474
475     DriverProxy(Driver target)
476     {
477       if (target == null)
478         throw new NullPointerException();
479       this.target = target;
480     }
481
482     public java.sql.Driver getTarget()
483     {
484       return target;
485     }
486
487     @Override
488     public boolean acceptsURL(String url) throws SQLException
489     {
490       return target.acceptsURL(url);
491     }
492
493     @Override
494     public java.sql.Connection connect(
495         String url,
496         java.util.Properties info
497       )
498       throws
499         SQLException
500     {
501       return target.connect(url, info);
502     }
503
504     @Override
505     public int getMajorVersion()
506     {
507       return target.getMajorVersion();
508     }
509
510     @Override
511     public int getMinorVersion()
512     {
513       return target.getMinorVersion();
514     }
515
516     @Override
517     public DriverPropertyInfo[] getPropertyInfo(
518         String url,
519         Properties info
520       )
521       throws
522         SQLException
523     {
524       return target.getPropertyInfo(url, info);
525     }
526
527     @Override
528     public boolean jdbcCompliant()
529     {
530       return target.jdbcCompliant();
531     }
532
533     @Override
534     public String toString()
535     {
536       return "Proxy: " + target;
537     }
538
539     @Override
540     public int hashCode()
541     {
542       return target.hashCode();
543     }
544
545     @Override
546     public boolean equals(Object obj)
547     {
548       if (!(obj instanceof DriverProxy))
549         return false;
550       DriverProxy other = (DriverProxy) obj;
551       return this.target.equals(other.target);
552     }
553   }
554 }