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.FileOutputStream;
23 import java.io.IOException;
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
27 import java.net.URLClassLoader;
28 import java.sql.Connection;
29 import java.sql.Driver;
30 import java.sql.DriverManager;
31 import java.sql.DriverPropertyInfo;
32 import java.sql.SQLException;
33 import java.sql.SQLFeatureNotSupportedException;
34 import java.util.Comparator;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.Properties;
43 import java.util.TreeSet;
44 import java.util.logging.Logger;
45 import javax.persistence.Embeddable;
46 import javax.persistence.Entity;
47 import javax.persistence.MappedSuperclass;
48 import org.apache.maven.plugin.AbstractMojo;
49 import org.apache.maven.plugin.MojoExecutionException;
50 import org.apache.maven.plugin.MojoFailureException;
51 import org.apache.maven.project.MavenProject;
52 import org.hibernate.cfg.Configuration;
53 import org.hibernate.tool.hbm2ddl.SchemaExport;
54 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
55 import org.hibernate.tool.hbm2ddl.Target;
56 import org.scannotation.AnnotationDB;
60 * Goal which extracts the hibernate-mapping-configuration and
61 * exports an according SQL-database-schema.
64 * @phase process-classes
66 * @requiresDependencyResolution runtime
68 public class Hbm2DdlMojo extends AbstractMojo
70 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
71 public final static String URL = "hibernate.connection.url";
72 public final static String USERNAME = "hibernate.connection.username";
73 public final static String PASSWORD = "hibernate.connection.password";
74 public final static String DIALECT = "hibernate.dialect";
76 private final static String TIMESTAMPS = "schema.timestamp";
79 * The project whose project files to create.
81 * @parameter expression="${project}"
85 private MavenProject project;
88 * Directories to scan.
90 * @parameter expression="${project.build.outputDirectory}"
92 private String outputDirectory;
97 * @parameter expression="${maven.test.skip}"
104 * @parameter expression="${hibernate.connection.driver_class}
106 private String driverClassName;
111 * @parameter expression="${hibernate.connection.url}"
118 * @parameter expression="${hibernate.connection.username}"
120 private String username;
125 * @parameter expression="${hibernate.connection.password}"
127 private String password;
132 * @parameter expression="${hibernate.dialect}"
134 private String hibernateDialect;
137 * Hibernate configuration file.
139 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
141 private String hibernateProperties;
144 * Target of execution:
146 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
147 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
148 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
149 * <li><strong>BOTH</strong></li>
151 * @parameter default-value="EXPORT"
153 private String target;
158 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
159 * <li><strong>CREATE</strong> create database-schema</li>
160 * <li><strong>DROP</strong> drop database-schema</li>
161 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
163 * @parameter default-value="BOTH"
170 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
172 private String outputFile;
175 * Delimiter in output-file.
177 * @parameter default-value=";"
179 private String delimiter;
182 * Format output-file.
184 * @parameter default-value="true"
186 private boolean format;
190 public void execute()
192 MojoFailureException,
193 MojoExecutionException
197 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
201 File dir = new File(outputDirectory);
203 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
205 Map<String,Long> timestamps;
206 boolean modified = false;
207 File saved = new File(outputDirectory + File.separator + TIMESTAMPS);
213 FileInputStream fis = new FileInputStream(saved);
214 ObjectInputStream ois = new ObjectInputStream(fis);
215 timestamps = (HashMap<String,Long>)ois.readObject();
220 timestamps = new HashMap<String,Long>();
221 getLog().warn("Cannot read timestamps from saved: " + e);
226 timestamps = new HashMap<String,Long>();
229 saved.createNewFile();
231 catch (IOException e)
233 getLog().warn("Cannot create saved for timestamps: " + e);
237 ClassLoader classLoader = null;
240 getLog().debug("Creating ClassLoader for project-dependencies...");
241 List<String> classpathFiles = project.getCompileClasspathElements();
242 URL[] urls = new URL[classpathFiles.size()];
243 for (int i = 0; i < classpathFiles.size(); ++i)
245 getLog().debug("Dependency: " + classpathFiles.get(i));
246 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
248 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
252 getLog().error("Error while creating ClassLoader!", e);
253 throw new MojoExecutionException(e.getMessage());
256 Set<Class<?>> classes =
257 new TreeSet<Class<?>>(
258 new Comparator<Class<?>>() {
260 public int compare(Class<?> a, Class<?> b)
262 return a.getName().compareTo(b.getName());
269 AnnotationDB db = new AnnotationDB();
270 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
271 URL dirUrl = dir.toURI().toURL();
272 db.scanArchives(dirUrl);
274 Set<String> classNames = new HashSet<String>();
275 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
276 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
277 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
278 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
279 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
280 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
282 for (String name : classNames)
284 Class<?> annotatedClass = classLoader.loadClass(name);
285 classes.add(annotatedClass);
286 URL classUrl = annotatedClass.getResource(annotatedClass.getSimpleName() + ".class");
287 File classFile = new File(classUrl.toURI());
288 long lastModified = classFile.lastModified();
289 long timestamp = !timestamps.containsKey(name) ? 0 : timestamps.get(name);
290 if (lastModified > timestamp)
292 getLog().debug("Found new or modified annotated class: " + name);
294 timestamps.put(name, lastModified);
298 catch (ClassNotFoundException e)
300 getLog().error("Error while adding annotated classes!", e);
301 throw new MojoExecutionException(e.getMessage());
305 getLog().error("Error while scanning!", e);
306 throw new MojoFailureException(e.getMessage());
309 if (classes.isEmpty())
310 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
314 getLog().info("No modified annotated classes found.");
315 getLog().info("Skipping schema generation!");
316 project.getProperties().setProperty("hibernate4.skipped", "true");
320 getLog().debug("Detected classes with mapping-annotations:");
321 for (Class<?> annotatedClass : classes)
322 getLog().debug(" " + annotatedClass.getName());
325 Properties properties = new Properties();
327 /** Try to read configuration from properties-file */
330 File file = new File(hibernateProperties);
333 getLog().info("Reading properties from file " + hibernateProperties + "...");
334 properties.load(new FileInputStream(file));
337 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
339 catch (IOException e)
341 getLog().error("Error while reading properties!", e);
342 throw new MojoExecutionException(e.getMessage());
345 /** Overwrite values from propertie-file or set, if given */
346 if (driverClassName != null)
348 if (properties.containsKey(DRIVER_CLASS))
350 "Overwriting property " +
351 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
352 " with the value " + driverClassName +
353 " from the plugin-configuration-parameter driverClassName!"
357 "Using the value " + driverClassName +
358 " from the plugin-configuration-parameter driverClassName!"
360 properties.setProperty(DRIVER_CLASS, driverClassName);
364 if (properties.containsKey(URL))
366 "Overwriting property " +
367 URL + "=" + properties.getProperty(URL) +
368 " with the value " + url +
369 " from the plugin-configuration-parameter url!"
373 "Using the value " + url +
374 " from the plugin-configuration-parameter url!"
376 properties.setProperty(URL, url);
378 if (username != null)
380 if (properties.containsKey(USERNAME))
382 "Overwriting property " +
383 USERNAME + "=" + properties.getProperty(USERNAME) +
384 " with the value " + username +
385 " from the plugin-configuration-parameter username!"
389 "Using the value " + username +
390 " from the plugin-configuration-parameter username!"
392 properties.setProperty(USERNAME, username);
394 if (password != null)
396 if (properties.containsKey(PASSWORD))
398 "Overwriting property " +
399 PASSWORD + "=" + properties.getProperty(PASSWORD) +
400 " with the value " + password +
401 " from the plugin-configuration-parameter password!"
405 "Using the value " + password +
406 " from the plugin-configuration-parameter password!"
408 properties.setProperty(PASSWORD, password);
410 if (hibernateDialect != null)
412 if (properties.containsKey(DIALECT))
414 "Overwriting property " +
415 DIALECT + "=" + properties.getProperty(DIALECT) +
416 " with the value " + hibernateDialect +
417 " from the plugin-configuration-parameter hibernateDialect!"
421 "Using the value " + hibernateDialect +
422 " from the plugin-configuration-parameter hibernateDialect!"
424 properties.setProperty(DIALECT, hibernateDialect);
427 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
428 if (properties.isEmpty())
430 getLog().error("No properties set!");
431 throw new MojoFailureException("Hibernate-Configuration is missing!");
433 for (Entry<Object,Object> entry : properties.entrySet())
434 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
436 Configuration config = new Configuration();
437 config.setProperties(properties);
438 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
439 for (Class<?> annotatedClass : classes)
441 getLog().debug("Class " + annotatedClass);
442 config.addAnnotatedClass(annotatedClass);
445 Target target = null;
448 target = Target.valueOf(this.target);
450 catch (IllegalArgumentException e)
452 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
453 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
454 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
459 type = Type.valueOf(this.type);
461 catch (IllegalArgumentException e)
463 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
464 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
465 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
468 Connection connection = null;
472 * The connection must be established outside of hibernate, because
473 * hibernate does not use the context-classloader of the current
474 * thread and, hence, would not be able to resolve the driver-class!
485 Class driverClass = classLoader.loadClass(driverClassName);
486 getLog().debug("Registering JDBC-driver " + driverClass.getName());
487 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
488 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
489 connection = DriverManager.getConnection(url, username, password);
493 catch (ClassNotFoundException e)
495 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
496 throw new MojoExecutionException(e.getMessage());
500 getLog().error("Cannot establish connection to database!");
501 Enumeration<Driver> drivers = DriverManager.getDrivers();
502 if (!drivers.hasMoreElements())
503 getLog().error("No drivers registered!");
504 while (drivers.hasMoreElements())
505 getLog().debug("Driver: " + drivers.nextElement());
506 throw new MojoExecutionException(e.getMessage());
509 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
510 MavenLogAppender.startPluginLog(this);
514 * Change class-loader of current thread, so that hibernate can
515 * see all dependencies!
517 Thread.currentThread().setContextClassLoader(classLoader);
519 SchemaExport export = new SchemaExport(config, connection);
520 export.setOutputFile(outputFile);
521 export.setDelimiter(delimiter);
522 export.setFormat(format);
523 export.execute(target, type);
525 for (Object exception : export.getExceptions())
526 getLog().debug(exception.toString());
530 /** Stop Log-Capturing */
531 MavenLogAppender.endPluginLog(this);
533 /** Restore the old class-loader (TODO: is this really necessary?) */
534 Thread.currentThread().setContextClassLoader(contextClassLoader);
536 /** Close the connection */
541 catch (SQLException e)
543 getLog().error("Error while closing connection: " + e.getMessage());
547 /** Write timestamps for annotated classes to file */
550 FileOutputStream fos = new FileOutputStream(saved);
551 ObjectOutputStream oos = new ObjectOutputStream(fos);
552 oos.writeObject(timestamps);
558 getLog().error("Cannot write timestamps to file: " + e);
563 * Needed, because DriverManager won't pick up drivers, that were not
564 * loaded by the system-classloader!
566 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
568 static final class DriverProxy implements Driver
570 private final Driver target;
572 DriverProxy(Driver target)
575 throw new NullPointerException();
576 this.target = target;
579 public java.sql.Driver getTarget()
585 public boolean acceptsURL(String url) throws SQLException
587 return target.acceptsURL(url);
591 public java.sql.Connection connect(
593 java.util.Properties info
598 return target.connect(url, info);
602 public int getMajorVersion()
604 return target.getMajorVersion();
608 public int getMinorVersion()
610 return target.getMinorVersion();
614 public DriverPropertyInfo[] getPropertyInfo(
621 return target.getPropertyInfo(url, info);
625 public boolean jdbcCompliant()
627 return target.jdbcCompliant();
631 * This Method cannot be annotated with @Override, becaus the plugin
632 * will not compile then under Java 1.6!
634 public Logger getParentLogger() throws SQLFeatureNotSupportedException
636 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
640 public String toString()
642 return "Proxy: " + target;
646 public int hashCode()
648 return target.hashCode();
652 public boolean equals(Object obj)
654 if (!(obj instanceof DriverProxy))
656 DriverProxy other = (DriverProxy) obj;
657 return this.target.equals(other.target);