Cleaned up code
[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   /**
62    * The project whose project files to create.
63    *
64    * @parameter expression="${project}"
65    * @required
66    * @readonly
67    */
68   private MavenProject project;
69
70   /**
71    * Directories to scan.
72    *
73    * @parameter expression="${project.build.outputDirectory}"
74    */
75   private String outputDirectory;
76
77   /**
78    * Skip execution
79    *
80    * @parameter expression="${maven.test.skip}"
81    */
82   private boolean skip;
83
84   /**
85    * SQL-Driver name.
86    *
87    * @parameter expression="${hibernate.connection.driver_class}
88    */
89   private String driverClassName;
90
91   /**
92    * Database URL.
93    *
94    * @parameter expression="${hibernate.connection.url}"
95    */
96   private String url;
97
98   /**
99    * Database username
100    *
101    * @parameter expression="${hibernate.connection.username}"
102    */
103   private String username;
104
105   /**
106    * Database password
107    *
108    * @parameter expression="${hibernate.connection.password}"
109    */
110   private String password;
111
112   /**
113    * Hibernate dialect.
114    *
115    * @parameter expression="${hibernate.dialect}"
116    */
117   private String hibernateDialect;
118
119   /**
120    * Hibernate configuration file.
121    *
122    * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
123    */
124   private String hibernateProperties;
125
126   /**
127    * Target of execution:
128    * <ul>
129    *   <li><strong>NONE</strong> do nothing - just validate the configuration</li>
130    *   <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
131    *   <li><strong>SCRIPT</strong> export schema to SQL-script</li>
132    *   <li><strong>BOTH</strong></li>
133    * </ul>
134    * @parameter default-value="EXPORT"
135    */
136   private String target;
137
138   /**
139    * Type of export.
140    * <ul>
141    *   <li><strong>NONE</strong> do nothing - just validate the configuration</li>
142    *   <li><strong>CREATE</strong> create database-schema</li>
143    *   <li><strong>DROP</strong> drop database-schema</li>
144    *   <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
145    * </ul>
146    * @parameter default-value="BOTH"
147    */
148   private String type;
149
150   /**
151    * Output file.
152    *
153    * @parameter default-value="${project.build.outputDirectory}/schema.sql"
154    */
155   private String outputFile;
156
157   /**
158    * Delimiter in output-file.
159    *
160    * @parameter default-value=";"
161    */
162   private String delimiter;
163
164   /**
165    * Format output-file.
166    *
167    * @parameter default-value="true"
168    */
169   private boolean format;
170
171
172   @Override
173   public void execute()
174     throws
175       MojoFailureException,
176       MojoExecutionException
177   {
178     if (skip)
179       return;
180
181     File dir = new File(outputDirectory);
182     if (!dir.exists())
183       throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
184
185
186     Set<String> classes = new HashSet<String>();
187     try
188     {
189       AnnotationDB db = new AnnotationDB();
190       getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
191       URL dirUrl = dir.toURI().toURL();
192       db.scanArchives(dirUrl);
193       if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
194         classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
195       if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
196         classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
197       if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
198         classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
199     }
200     catch (IOException e)
201     {
202       getLog().error("Error while scanning!", e);
203       throw new MojoFailureException(e.getMessage());
204     }
205     if (classes.isEmpty())
206       throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
207
208     Properties properties = new Properties();
209
210     /** Try to read configuration from properties-file */
211     try
212     {
213       File file = new File(hibernateProperties);
214       if (file.exists())
215       {
216         getLog().info("Reading properties from file " + hibernateProperties + "...");
217         properties.load(new FileInputStream(file));
218       }
219       else
220         getLog().info("Ignoring nonexistent properties-file " + hibernateProperties + "!");
221     }
222     catch (IOException e)
223     {
224       getLog().error("Error while reading properties!", e);
225       throw new MojoExecutionException(e.getMessage());
226     }
227
228     /** Overwrite values from propertie-file or set  if given */
229     if (driverClassName != null)
230       properties.setProperty("hibernate.connection.driver_class", driverClassName);
231     if (url != null)
232       properties.setProperty("hibernate.connection.url", url);
233     if (username != null)
234       properties.setProperty("hibernate.connection.username", username);
235     if (password != null)
236       properties.setProperty("hibernate.connection.password", password);
237     if (hibernateDialect != null)
238       properties.setProperty("hibernate.dialect", hibernateDialect);
239
240     if (properties.isEmpty())
241       getLog().warn("No properties set!");
242     for (Entry<Object,Object> entry : properties.entrySet())
243       getLog().debug(entry.getKey() + " = " + entry.getValue());
244
245     ClassLoader classLoader = null;
246     try
247     {
248       getLog().debug("Creating ClassLoader for project-dependencies...");
249       List<String> classpathFiles = project.getCompileClasspathElements();
250       URL[] urls = new URL[classpathFiles.size()];
251       for (int i = 0; i < classpathFiles.size(); ++i)
252       {
253         getLog().debug("Dependency: " + classpathFiles.get(i));
254         urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
255       }
256       classLoader = new URLClassLoader(urls, getClass().getClassLoader());
257     }
258     catch (Exception e)
259     {
260       getLog().error("Error while creating ClassLoader!", e);
261       throw new MojoExecutionException(e.getMessage());
262     }
263
264     Configuration config = new Configuration();
265     config.setProperties(properties);
266     try
267     {
268       getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
269       for (String annotatedClass : classes)
270       {
271         getLog().debug("Class " + annotatedClass);
272         config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
273       }
274     }
275     catch (ClassNotFoundException e)
276     {
277       getLog().error("Error while adding annotated classes!", e);
278       throw new MojoExecutionException(e.getMessage());
279     }
280
281     Target target = null;
282     try
283     {
284       target = Target.valueOf(this.target);
285     }
286     catch (IllegalArgumentException e)
287     {
288       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
289       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
290       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
291     }
292     Type type = null;
293     try
294     {
295       type = Type.valueOf(this.type);
296     }
297     catch (IllegalArgumentException e)
298     {
299       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
300       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
301       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
302     }
303
304     Connection connection = null;
305     try
306     {
307       /**
308        * The connection must be established outside of hibernate, because
309        * hibernate does not use the context-classloader of the current
310        * thread and, hence, would not be able to resolve the driver-class!
311        */
312       switch (target)
313       {
314         case EXPORT:
315         case BOTH:
316           switch (type)
317           {
318             case CREATE:
319             case DROP:
320             case BOTH:
321               Class driverClass = classLoader.loadClass(driverClassName);
322               getLog().debug("Registering JDBC-driver " + driverClass.getName());
323               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
324               getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
325               connection = DriverManager.getConnection(url, username, password);
326           }
327       }
328     }
329     catch (ClassNotFoundException e)
330     {
331       getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
332       throw new MojoExecutionException(e.getMessage());
333     }
334     catch (Exception e)
335     {
336       getLog().error("Cannot establish connection to database!");
337       Enumeration<Driver> drivers = DriverManager.getDrivers();
338       if (!drivers.hasMoreElements())
339         getLog().error("No drivers registered!");
340       while (drivers.hasMoreElements())
341         getLog().debug("Driver: " + drivers.nextElement());
342       throw new MojoExecutionException(e.getMessage());
343     }
344
345     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
346     MavenLogAppender.startPluginLog(this);
347     try
348     {
349       /**
350        * Change class-loader of current thread, so that hibernate can
351        * see all dependencies!
352        */
353       Thread.currentThread().setContextClassLoader(classLoader);
354
355       SchemaExport export = new SchemaExport(config, connection);
356       export.setOutputFile(outputFile);
357       export.setDelimiter(delimiter);
358       export.setFormat(format);
359       export.execute(target, type);
360
361       for (Object exception : export.getExceptions())
362         getLog().debug(exception.toString());
363     }
364     finally
365     {
366       /** Stop Log-Capturing */
367       MavenLogAppender.endPluginLog(this);
368
369       /** Restore the old class-loader (TODO: is this really necessary?) */
370       Thread.currentThread().setContextClassLoader(contextClassLoader);
371
372       /** Close the connection */
373       try
374       {
375         connection.close();
376       }
377       catch (SQLException e)
378       {
379         getLog().error("Error while closing connection: " + e.getMessage());
380       }
381     }
382   }
383
384   /**
385    * Needed, because DriverManager won't pick up drivers, that were not
386    * loaded by the system-classloader!
387    * See:
388    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
389    */
390   static final class DriverProxy implements Driver
391   {
392     private final Driver target;
393
394     DriverProxy(Driver target)
395     {
396       if (target == null)
397         throw new NullPointerException();
398       this.target = target;
399     }
400
401     public java.sql.Driver getTarget()
402     {
403       return target;
404     }
405
406     @Override
407     public boolean acceptsURL(String url) throws SQLException
408     {
409       return target.acceptsURL(url);
410     }
411
412     @Override
413     public java.sql.Connection connect(
414         String url,
415         java.util.Properties info
416       )
417       throws
418         SQLException
419     {
420       return target.connect(url, info);
421     }
422
423     @Override
424     public int getMajorVersion()
425     {
426       return target.getMajorVersion();
427     }
428
429     @Override
430     public int getMinorVersion()
431     {
432       return target.getMinorVersion();
433     }
434
435     @Override
436     public DriverPropertyInfo[] getPropertyInfo(
437         String url,
438         Properties info
439       )
440       throws
441         SQLException
442     {
443       return target.getPropertyInfo(url, info);
444     }
445
446     @Override
447     public boolean jdbcCompliant()
448     {
449       return target.jdbcCompliant();
450     }
451
452     @Override
453     public String toString()
454     {
455       return "Proxy: " + target;
456     }
457
458     @Override
459     public int hashCode()
460     {
461       return target.hashCode();
462     }
463
464     @Override
465     public boolean equals(Object obj)
466     {
467       if (!(obj instanceof DriverProxy))
468         return false;
469       DriverProxy other = (DriverProxy) obj;
470       return this.target.equals(other.target);
471     }
472   }
473 }