Attribute "skip" is no initialized with value of property maven.test.skip
[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.Entity;
37 import javax.persistence.Embeddable;
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     URL dirUrl = null;
188     try {
189       AnnotationDB db = new AnnotationDB();
190       getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
191       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       getLog().error("Error while scanning!", e);
202       throw new MojoFailureException(e.getMessage());
203     }
204     if (classes.isEmpty())
205       throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
206
207     Properties properties = new Properties();
208
209     /** Try to read configuration from properties-file */
210     try {
211       File file = new File(hibernateProperties);
212       if (file.exists()) {
213         getLog().info("Reading properties from file " + hibernateProperties + "...");
214         properties.load(new FileInputStream(file));
215       }
216       else
217         getLog().info("Ignoring nonexistent properties-file " + hibernateProperties + "!");
218     }
219     catch (IOException e) {
220       getLog().error("Error while reading properties!", e);
221       throw new MojoExecutionException(e.getMessage());
222     }
223
224     /** Overwrite values from propertie-file or set  if given */
225     if (driverClassName != null)
226       properties.setProperty("hibernate.connection.driver_class", driverClassName);
227     if (url != null)
228       properties.setProperty("hibernate.connection.url", url);
229     if (username != null)
230       properties.setProperty("hibernate.connection.username", username);
231     if (password != null)
232       properties.setProperty("hibernate.connection.password", password);
233     if (hibernateDialect != null)
234       properties.setProperty("hibernate.dialect", hibernateDialect);
235
236     if (properties.isEmpty())
237       getLog().warn("No properties set!");
238     for (Entry<Object,Object> entry : properties.entrySet())
239       getLog().debug(entry.getKey() + " = " + entry.getValue());
240
241     ClassLoader classLoader = null;
242     try {
243       getLog().debug("Creating ClassLoader for project-dependencies...");
244       List<String> classpathFiles = project.getCompileClasspathElements();
245       URL[] urls = new URL[classpathFiles.size()];
246       for (int i = 0; i < classpathFiles.size(); ++i) {
247         getLog().debug("Dependency: " + classpathFiles.get(i));
248         urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
249       }
250       classLoader = new URLClassLoader(urls, getClass().getClassLoader());
251     }
252     catch (Exception e) {
253       getLog().error("Error while creating ClassLoader!", e);
254       throw new MojoExecutionException(e.getMessage());
255     }
256
257     Configuration config = new Configuration();
258     config.setProperties(properties);
259     try {
260       getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
261       for (String annotatedClass : classes) {
262         getLog().debug("Class " + annotatedClass);
263         config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
264       }
265     }
266     catch (ClassNotFoundException e) {
267       getLog().error("Error while adding annotated classes!", e);
268       throw new MojoExecutionException(e.getMessage());
269     }
270
271     Target target = null;
272     try {
273       target = Target.valueOf(this.target);
274     }
275     catch (IllegalArgumentException e) {
276       getLog().error("Invalid value for configuration-option \"target\": " + this.target);
277       getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
278       throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
279     }
280     Type type = null;
281     try {
282       type = Type.valueOf(this.type);
283     }
284     catch (IllegalArgumentException e) {
285       getLog().error("Invalid value for configuration-option \"type\": " + this.type);
286       getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
287       throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
288     }
289
290     Connection connection = null;
291     try {
292       /**
293        * The connection must be established outside of hibernate, because
294        * hibernate does not use the context-classloader of the current
295        * thread and, hence, would not be able to resolve the driver-class!
296        */
297       switch (target) {
298         case EXPORT:
299         case BOTH:
300           switch (type) {
301             case CREATE:
302             case DROP:
303             case BOTH:
304               Class driverClass = classLoader.loadClass(driverClassName);
305               getLog().debug("Registering JDBC-driver " + driverClass.getName());
306               DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
307               getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
308               connection = DriverManager.getConnection(url, username, password);
309           }
310       }
311     }
312     catch (ClassNotFoundException e) {
313       getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
314       throw new MojoExecutionException(e.getMessage());
315     }
316     catch (Exception e) {
317       getLog().error("Cannot establish connection to database!");
318       Enumeration<Driver> drivers = DriverManager.getDrivers();
319       if (!drivers.hasMoreElements())
320         getLog().error("No drivers registered!");
321       while (drivers.hasMoreElements())
322         getLog().debug("Driver: " + drivers.nextElement());
323       throw new MojoExecutionException(e.getMessage());
324     }
325
326     ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
327     MavenLogAppender.startPluginLog(this);
328     try {
329       /**
330        * Change class-loader of current thread, so that hibernate can
331        * see all dependencies!
332        */
333       Thread.currentThread().setContextClassLoader(classLoader);
334
335       SchemaExport export = new SchemaExport(config, connection);
336       export.setOutputFile(outputFile);
337       export.setDelimiter(delimiter);
338       export.setFormat(format);
339       export.execute(target, type);
340
341       for (Object exception : export.getExceptions())
342         getLog().debug(exception.toString());
343     }
344     finally {
345       /** Stop Log-Capturing */
346       MavenLogAppender.endPluginLog(this);
347
348       /** Restore the old class-loader (TODO: is this really necessary?) */
349       Thread.currentThread().setContextClassLoader(contextClassLoader);
350
351       /** Close the connection */
352       try {
353         connection.close();
354       }
355       catch (SQLException e) {
356         getLog().error("Error while closing connection: " + e.getMessage());
357       }
358     }
359   }
360
361   /**
362    * Needed, because DriverManager won't pick up drivers, that were not
363    * loaded by the system-classloader!
364    * See:
365    * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
366    */
367   static final class DriverProxy implements Driver {
368
369     private final Driver target;
370
371     DriverProxy(Driver target) {
372       if (target == null) {
373         throw new NullPointerException();
374       }
375       this.target = target;
376     }
377
378     public java.sql.Driver getTarget() {
379       return target;
380     }
381
382     @Override
383     public boolean acceptsURL(String url) throws SQLException {
384       return target.acceptsURL(url);
385     }
386
387     @Override
388     public java.sql.Connection connect(
389         String url, java.util.Properties info) throws SQLException {
390       return target.connect(url, info);
391     }
392
393     @Override
394     public int getMajorVersion() {
395       return target.getMajorVersion();
396     }
397
398     @Override
399     public int getMinorVersion() {
400       return target.getMinorVersion();
401     }
402
403     @Override
404     public DriverPropertyInfo[] getPropertyInfo(
405         String url, Properties info) throws SQLException {
406       return target.getPropertyInfo(url, info);
407     }
408
409     @Override
410     public boolean jdbcCompliant() {
411       return target.jdbcCompliant();
412     }
413
414     @Override
415     public String toString() {
416       return "Proxy: " + target;
417     }
418
419     @Override
420     public int hashCode() {
421       return target.hashCode();
422     }
423
424     @Override
425     public boolean equals(Object obj) {
426       if (!(obj instanceof DriverProxy)) {
427         return false;
428       }
429       DriverProxy other = (DriverProxy) obj;
430       return this.target.equals(other.target);
431     }
432 }
433 }