1 package de.juplo.plugins.hibernate4;
4 * Copyright 2001-2005 The Apache Software Foundation.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import com.pyx4j.log4j.MavenLogAppender;
21 import java.io.FileInputStream;
22 import java.io.IOException;
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.sql.SQLFeatureNotSupportedException;
31 import java.util.Enumeration;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.Properties;
37 import java.util.logging.Logger;
38 import javax.persistence.Embeddable;
39 import javax.persistence.Entity;
40 import javax.persistence.MappedSuperclass;
41 import org.apache.maven.plugin.AbstractMojo;
42 import org.apache.maven.plugin.MojoExecutionException;
43 import org.apache.maven.plugin.MojoFailureException;
44 import org.apache.maven.project.MavenProject;
45 import org.hibernate.cfg.Configuration;
46 import org.hibernate.tool.hbm2ddl.SchemaExport;
47 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
48 import org.hibernate.tool.hbm2ddl.Target;
49 import org.scannotation.AnnotationDB;
53 * Goal which extracts the hibernate-mapping-configuration and
54 * exports an according SQL-database-schema.
57 * @phase process-classes
59 * @requiresDependencyResolution runtime
61 public class Hbm2DdlMojo extends AbstractMojo
63 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
64 public final static String URL = "hibernate.connection.url";
65 public final static String USERNAME = "hibernate.connection.username";
66 public final static String PASSWORD = "hibernate.connection.password";
67 public final static String DIALECT = "hibernate.dialect";
71 * The project whose project files to create.
73 * @parameter expression="${project}"
77 private MavenProject project;
80 * Directories to scan.
82 * @parameter expression="${project.build.outputDirectory}"
84 private String outputDirectory;
89 * @parameter expression="${maven.test.skip}"
96 * @parameter expression="${hibernate.connection.driver_class}
98 private String driverClassName;
103 * @parameter expression="${hibernate.connection.url}"
110 * @parameter expression="${hibernate.connection.username}"
112 private String username;
117 * @parameter expression="${hibernate.connection.password}"
119 private String password;
124 * @parameter expression="${hibernate.dialect}"
126 private String hibernateDialect;
129 * Hibernate configuration file.
131 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
133 private String hibernateProperties;
136 * Target of execution:
138 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
139 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
140 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
141 * <li><strong>BOTH</strong></li>
143 * @parameter default-value="EXPORT"
145 private String target;
150 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
151 * <li><strong>CREATE</strong> create database-schema</li>
152 * <li><strong>DROP</strong> drop database-schema</li>
153 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
155 * @parameter default-value="BOTH"
162 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
164 private String outputFile;
167 * Delimiter in output-file.
169 * @parameter default-value=";"
171 private String delimiter;
174 * Format output-file.
176 * @parameter default-value="true"
178 private boolean format;
182 public void execute()
184 MojoFailureException,
185 MojoExecutionException
190 File dir = new File(outputDirectory);
192 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
195 Set<String> classes = new HashSet<String>();
198 AnnotationDB db = new AnnotationDB();
199 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
200 URL dirUrl = dir.toURI().toURL();
201 db.scanArchives(dirUrl);
202 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
203 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
204 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
205 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
206 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
207 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
209 catch (IOException e)
211 getLog().error("Error while scanning!", e);
212 throw new MojoFailureException(e.getMessage());
214 if (classes.isEmpty())
215 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
217 Properties properties = new Properties();
219 /** Try to read configuration from properties-file */
222 File file = new File(hibernateProperties);
225 getLog().info("Reading properties from file " + hibernateProperties + "...");
226 properties.load(new FileInputStream(file));
229 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
231 catch (IOException e)
233 getLog().error("Error while reading properties!", e);
234 throw new MojoExecutionException(e.getMessage());
237 /** Overwrite values from propertie-file or set, if given */
238 if (driverClassName != null)
240 if (properties.containsKey(DRIVER_CLASS))
242 "Overwriting property " +
243 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
244 " with the value " + driverClassName +
245 " from the plugin-configuration-parameter driverClassName!"
249 "Using the value " + driverClassName +
250 " from the plugin-configuration-parameter driverClassName!"
252 properties.setProperty(DRIVER_CLASS, driverClassName);
256 if (properties.containsKey(URL))
258 "Overwriting property " +
259 URL + "=" + properties.getProperty(URL) +
260 " with the value " + url +
261 " from the plugin-configuration-parameter url!"
265 "Using the value " + url +
266 " from the plugin-configuration-parameter url!"
268 properties.setProperty(URL, url);
270 if (username != null)
272 if (properties.containsKey(USERNAME))
274 "Overwriting property " +
275 USERNAME + "=" + properties.getProperty(USERNAME) +
276 " with the value " + username +
277 " from the plugin-configuration-parameter username!"
281 "Using the value " + username +
282 " from the plugin-configuration-parameter username!"
284 properties.setProperty(USERNAME, username);
286 if (password != null)
288 if (properties.containsKey(PASSWORD))
290 "Overwriting property " +
291 PASSWORD + "=" + properties.getProperty(PASSWORD) +
292 " with the value " + password +
293 " from the plugin-configuration-parameter password!"
297 "Using the value " + password +
298 " from the plugin-configuration-parameter password!"
300 properties.setProperty(PASSWORD, password);
302 if (hibernateDialect != null)
304 if (properties.containsKey(DIALECT))
306 "Overwriting property " +
307 DIALECT + "=" + properties.getProperty(DIALECT) +
308 " with the value " + hibernateDialect +
309 " from the plugin-configuration-parameter hibernateDialect!"
313 "Using the value " + hibernateDialect +
314 " from the plugin-configuration-parameter hibernateDialect!"
316 properties.setProperty(DIALECT, hibernateDialect);
319 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
320 if (properties.isEmpty())
322 getLog().error("No properties set!");
323 throw new MojoFailureException("Hibernate-Configuration is missing!");
325 for (Entry<Object,Object> entry : properties.entrySet())
326 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
328 ClassLoader classLoader = null;
331 getLog().debug("Creating ClassLoader for project-dependencies...");
332 List<String> classpathFiles = project.getCompileClasspathElements();
333 URL[] urls = new URL[classpathFiles.size()];
334 for (int i = 0; i < classpathFiles.size(); ++i)
336 getLog().debug("Dependency: " + classpathFiles.get(i));
337 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
339 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
343 getLog().error("Error while creating ClassLoader!", e);
344 throw new MojoExecutionException(e.getMessage());
347 Configuration config = new Configuration();
348 config.setProperties(properties);
351 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
352 for (String annotatedClass : classes)
354 getLog().debug("Class " + annotatedClass);
355 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
358 catch (ClassNotFoundException e)
360 getLog().error("Error while adding annotated classes!", e);
361 throw new MojoExecutionException(e.getMessage());
364 Target target = null;
367 target = Target.valueOf(this.target);
369 catch (IllegalArgumentException e)
371 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
372 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
373 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
378 type = Type.valueOf(this.type);
380 catch (IllegalArgumentException e)
382 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
383 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
384 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
387 Connection connection = null;
391 * The connection must be established outside of hibernate, because
392 * hibernate does not use the context-classloader of the current
393 * thread and, hence, would not be able to resolve the driver-class!
404 Class driverClass = classLoader.loadClass(driverClassName);
405 getLog().debug("Registering JDBC-driver " + driverClass.getName());
406 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
407 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
408 connection = DriverManager.getConnection(url, username, password);
412 catch (ClassNotFoundException e)
414 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
415 throw new MojoExecutionException(e.getMessage());
419 getLog().error("Cannot establish connection to database!");
420 Enumeration<Driver> drivers = DriverManager.getDrivers();
421 if (!drivers.hasMoreElements())
422 getLog().error("No drivers registered!");
423 while (drivers.hasMoreElements())
424 getLog().debug("Driver: " + drivers.nextElement());
425 throw new MojoExecutionException(e.getMessage());
428 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
429 MavenLogAppender.startPluginLog(this);
433 * Change class-loader of current thread, so that hibernate can
434 * see all dependencies!
436 Thread.currentThread().setContextClassLoader(classLoader);
438 SchemaExport export = new SchemaExport(config, connection);
439 export.setOutputFile(outputFile);
440 export.setDelimiter(delimiter);
441 export.setFormat(format);
442 export.execute(target, type);
444 for (Object exception : export.getExceptions())
445 getLog().debug(exception.toString());
449 /** Stop Log-Capturing */
450 MavenLogAppender.endPluginLog(this);
452 /** Restore the old class-loader (TODO: is this really necessary?) */
453 Thread.currentThread().setContextClassLoader(contextClassLoader);
455 /** Close the connection */
460 catch (SQLException e)
462 getLog().error("Error while closing connection: " + e.getMessage());
468 * Needed, because DriverManager won't pick up drivers, that were not
469 * loaded by the system-classloader!
471 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
473 static final class DriverProxy implements Driver
475 private final Driver target;
477 DriverProxy(Driver target)
480 throw new NullPointerException();
481 this.target = target;
484 public java.sql.Driver getTarget()
490 public boolean acceptsURL(String url) throws SQLException
492 return target.acceptsURL(url);
496 public java.sql.Connection connect(
498 java.util.Properties info
503 return target.connect(url, info);
507 public int getMajorVersion()
509 return target.getMajorVersion();
513 public int getMinorVersion()
515 return target.getMinorVersion();
519 public DriverPropertyInfo[] getPropertyInfo(
526 return target.getPropertyInfo(url, info);
530 public boolean jdbcCompliant()
532 return target.jdbcCompliant();
536 * This Method cannot be annotated with @Override, becaus the plugin
537 * will not compile then under Java 1.6!
539 public Logger getParentLogger() throws SQLFeatureNotSupportedException
541 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
545 public String toString()
547 return "Proxy: " + target;
551 public int hashCode()
553 return target.hashCode();
557 public boolean equals(Object obj)
559 if (!(obj instanceof DriverProxy))
561 DriverProxy other = (DriverProxy) obj;
562 return this.target.equals(other.target);