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.FileNotFoundException;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
28 import java.math.BigInteger;
30 import java.net.URLClassLoader;
31 import java.security.MessageDigest;
32 import java.security.NoSuchAlgorithmException;
33 import java.sql.Connection;
34 import java.sql.Driver;
35 import java.sql.DriverManager;
36 import java.sql.DriverPropertyInfo;
37 import java.sql.SQLException;
38 import java.sql.SQLFeatureNotSupportedException;
39 import java.util.Comparator;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import java.util.Properties;
48 import java.util.TreeSet;
49 import java.util.logging.Logger;
50 import javax.persistence.Embeddable;
51 import javax.persistence.Entity;
52 import javax.persistence.MappedSuperclass;
53 import org.apache.maven.model.Resource;
54 import org.apache.maven.plugin.AbstractMojo;
55 import org.apache.maven.plugin.MojoExecutionException;
56 import org.apache.maven.plugin.MojoFailureException;
57 import org.apache.maven.project.MavenProject;
58 import org.hibernate.cfg.Configuration;
59 import org.hibernate.cfg.NamingStrategy;
60 import org.hibernate.envers.configuration.AuditConfiguration;
61 import org.hibernate.tool.hbm2ddl.SchemaExport;
62 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
63 import org.hibernate.tool.hbm2ddl.Target;
64 import org.scannotation.AnnotationDB;
68 * Goal which extracts the hibernate-mapping-configuration and
69 * exports an according SQL-database-schema.
72 * @phase process-classes
74 * @requiresDependencyResolution runtime
76 public class Hbm2DdlMojo extends AbstractMojo
78 public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
80 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
81 public final static String URL = "hibernate.connection.url";
82 public final static String USERNAME = "hibernate.connection.username";
83 public final static String PASSWORD = "hibernate.connection.password";
84 public final static String DIALECT = "hibernate.dialect";
85 public final static String NAMING_STRATEGY="hibernate.ejb.naming_strategy";
86 public final static String ENVERS = "hibernate.envers";
88 private final static String MD5S = "schema.md5s";
93 * Only needed internally.
95 * @parameter property="project"
99 private MavenProject project;
104 * Only needed internally.
106 * @parameter property="project.build.directory"
110 private String buildDirectory;
113 * Classes-Directory to scan.
115 * This parameter defaults to the maven build-output-directory for classes.
116 * Additonally, all dependencies are scanned for annotated classes.
118 * @parameter property="project.build.outputDirectory"
120 private String outputDirectory;
123 * Wether to scan test-classes too, or not.
125 * If this parameter is set to <code>true</code> the test-classes of the
126 * artifact will be scanned for hibernate-annotated classes additionally.
128 * @parameter property="hibernate.export.scan_testclasses" default-value="false"
130 private boolean scanTestClasses;
133 * Test-Classes-Directory to scan.
135 * This parameter defaults to the maven build-output-directory for
138 * This parameter is only used, when <code>scanTestClasses</code> is set
139 * to <code>true</code>!
141 * @parameter property="project.build.testOutputDirectory"
143 private String testOutputDirectory;
148 * If set to <code>true</code>, the execution is skipped.
150 * A skipped excecution is signaled via the maven-property
151 * <code>${hibernate.export.skipped}</code>.
153 * The excecution is skipped automatically, if no modified or newly added
154 * annotated classes are found and the dialect was not changed.
156 * @parameter property="hibernate.export.skip" default-value="false"
158 private boolean skip;
163 * Force execution, even if no modified or newly added annotated classes
164 * where found and the dialect was not changed.
166 * <code>skip</code> takes precedence over <code>force</code>.
168 * @parameter property="hibernate.export.force" default-value="false"
170 private boolean force;
175 * @parameter property="hibernate.connection.driver_class"
177 private String driverClassName;
182 * @parameter property="hibernate.connection.url"
189 * @parameter property="hibernate.connection.username"
191 private String username;
196 * @parameter property="hibernate.connection.password"
198 private String password;
203 * @parameter property="hibernate.dialect"
205 private String hibernateDialect;
208 * Hibernate Naming Strategy
209 * @parameter property="hibernate.ejb.naming_strategy"
211 private String hibernateNamingStrategy;
214 * Path to Hibernate configuration file.
216 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
218 private String hibernateProperties;
221 * List of Hibernate-Mapping-Files (XML).
222 * Multiple files can be separated with white-spaces and/or commas.
224 * @parameter property="hibernate.mapping"
226 private String hibernateMapping;
229 * Target of execution:
231 * <li><strong>NONE</strong> only export schema to SQL-script (forces excecution, signals skip)</li>
232 * <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>). forces excecution, signals skip)</li>
233 * <li><strong>SCRIPT</strong> export schema to SQL-script and print it to STDOUT</li>
234 * <li><strong>BOTH</strong></li>
237 * A databaseconnection is only needed for EXPORT and BOTH, but a
238 * Hibernate-Dialect must always be choosen.
240 * @parameter property="hibernate.export.target" default-value="EXPORT"
242 private String target;
247 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
248 * <li><strong>CREATE</strong> create database-schema</li>
249 * <li><strong>DROP</strong> drop database-schema</li>
250 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
253 * If NONE is choosen, no databaseconnection is needed.
255 * @parameter property="hibernate.export.type" default-value="BOTH"
262 * @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
264 private String outputFile;
267 * Delimiter in output-file.
269 * @parameter property="hibernate.export.schema.delimiter" default-value=";"
271 private String delimiter;
274 * Format output-file.
276 * @parameter property="hibernate.export.schema.format" default-value="true"
278 private boolean format;
281 * Generate envers schema for auditing tables.
283 * @parameter expression="${hibernate.envers}" default-value="false"
285 private boolean envers;
288 public void execute()
290 MojoFailureException,
291 MojoExecutionException
295 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
296 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
300 Map<String,String> md5s;
301 boolean modified = false;
302 File saved = new File(buildDirectory + File.separator + MD5S);
308 FileInputStream fis = new FileInputStream(saved);
309 ObjectInputStream ois = new ObjectInputStream(fis);
310 md5s = (HashMap<String,String>)ois.readObject();
315 md5s = new HashMap<String,String>();
316 getLog().warn("Cannot read timestamps from saved: " + e);
321 md5s = new HashMap<String,String>();
324 saved.createNewFile();
326 catch (IOException e)
328 getLog().debug("Cannot create file \"" + saved.getPath() + "\" for timestamps: " + e);
332 ClassLoader classLoader = null;
335 getLog().debug("Creating ClassLoader for project-dependencies...");
336 List<String> classpathFiles = project.getCompileClasspathElements();
338 classpathFiles.addAll(project.getTestClasspathElements());
339 URL[] urls = new URL[classpathFiles.size()];
340 for (int i = 0; i < classpathFiles.size(); ++i)
342 getLog().debug("Dependency: " + classpathFiles.get(i));
343 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
345 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
349 getLog().error("Error while creating ClassLoader!", e);
350 throw new MojoExecutionException(e.getMessage());
353 Set<Class<?>> classes =
354 new TreeSet<Class<?>>(
355 new Comparator<Class<?>>() {
357 public int compare(Class<?> a, Class<?> b)
359 return a.getName().compareTo(b.getName());
366 AnnotationDB db = new AnnotationDB();
367 File dir = new File(outputDirectory);
370 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
371 URL dirUrl = dir.toURI().toURL();
372 db.scanArchives(dirUrl);
376 dir = new File(testOutputDirectory);
379 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
380 URL dirUrl = dir.toURI().toURL();
381 db.scanArchives(dirUrl);
385 Set<String> classNames = new HashSet<String>();
386 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
387 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
388 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
389 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
390 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
391 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
393 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
394 for (String name : classNames)
396 Class<?> annotatedClass = classLoader.loadClass(name);
397 classes.add(annotatedClass);
398 String resourceName = annotatedClass.getName();
399 resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
402 .getResourceAsStream(resourceName);
403 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
405 while((i = is.read(buffer)) > -1)
406 digest.update(buffer, 0, i);
408 byte[] bytes = digest.digest();
409 BigInteger bi = new BigInteger(1, bytes);
410 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
411 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
412 if (!newMd5.equals(oldMd5))
414 getLog().debug("Found new or modified annotated class: " + name);
416 md5s.put(name, newMd5);
420 getLog().debug(oldMd5 + " -> class unchanged: " + name);
424 catch (ClassNotFoundException e)
426 getLog().error("Error while adding annotated classes!", e);
427 throw new MojoExecutionException(e.getMessage());
431 getLog().error("Error while scanning!", e);
432 throw new MojoFailureException(e.getMessage());
435 if (classes.isEmpty())
437 if (hibernateMapping == null || hibernateMapping.isEmpty())
438 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
442 getLog().debug("Detected classes with mapping-annotations:");
443 for (Class<?> annotatedClass : classes)
444 getLog().debug(" " + annotatedClass.getName());
448 Properties properties = new Properties();
450 /** Try to read configuration from properties-file */
453 File file = new File(hibernateProperties);
456 getLog().info("Reading properties from file " + hibernateProperties + "...");
457 properties.load(new FileInputStream(file));
460 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
462 catch (IOException e)
464 getLog().error("Error while reading properties!", e);
465 throw new MojoExecutionException(e.getMessage());
468 /** Overwrite values from propertie-file or set, if given */
469 if (driverClassName != null)
471 if (properties.containsKey(DRIVER_CLASS))
473 "Overwriting property " +
474 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
475 " with the value " + driverClassName
478 getLog().debug("Using the value " + driverClassName);
479 properties.setProperty(DRIVER_CLASS, driverClassName);
483 if (properties.containsKey(URL))
485 "Overwriting property " +
486 URL + "=" + properties.getProperty(URL) +
487 " with the value " + url
490 getLog().debug("Using the value " + url);
491 properties.setProperty(URL, url);
493 if (username != null)
495 if (properties.containsKey(USERNAME))
497 "Overwriting property " +
498 USERNAME + "=" + properties.getProperty(USERNAME) +
499 " with the value " + username
502 getLog().debug("Using the value " + username);
503 properties.setProperty(USERNAME, username);
505 if (password != null)
507 if (properties.containsKey(PASSWORD))
509 "Overwriting property " +
510 PASSWORD + "=" + properties.getProperty(PASSWORD) +
511 " with the value " + password
514 getLog().debug("Using the value " + password);
515 properties.setProperty(PASSWORD, password);
517 if (hibernateDialect != null)
519 if (properties.containsKey(DIALECT))
521 "Overwriting property " +
522 DIALECT + "=" + properties.getProperty(DIALECT) +
523 " with the value " + hibernateDialect
526 getLog().debug("Using the value " + hibernateDialect);
527 properties.setProperty(DIALECT, hibernateDialect);
529 if ( hibernateNamingStrategy != null )
531 if ( properties.contains(NAMING_STRATEGY))
533 "Overwriting property " +
534 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
535 " with the value " + hibernateNamingStrategy
538 getLog().debug("Using the value " + hibernateNamingStrategy);
539 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
543 if (properties.containsKey(ENVERS))
545 "Overwriting property " +
546 ENVERS + "=" + properties.getProperty(ENVERS) +
547 " with the value " + envers
550 getLog().debug("Using the value " + envers);
551 properties.setProperty(ENVERS, Boolean.toString(envers));
554 /** The generated SQL varies with the dialect! */
555 if (md5s.containsKey(DIALECT))
557 String dialect = properties.getProperty(DIALECT);
558 if (md5s.get(DIALECT).equals(dialect))
559 getLog().debug("SQL-dialect unchanged.");
562 getLog().debug("SQL-dialect changed: " + dialect);
564 md5s.put(DIALECT, dialect);
570 md5s.put(DIALECT, properties.getProperty(DIALECT));
573 /** The generated SQL varies with the envers-configuration */
574 if (md5s.containsKey(ENVERS))
576 String envers = properties.getProperty(ENVERS);
577 if (md5s.get(ENVERS).equals(envers))
578 getLog().debug("Envers unchanged.");
581 getLog().debug("Envers changed: " + envers);
583 md5s.put(ENVERS, envers);
589 md5s.put(ENVERS, properties.getProperty(ENVERS));
592 if (properties.isEmpty())
594 getLog().error("No properties set!");
595 throw new MojoFailureException("Hibernate-Configuration is missing!");
598 Configuration config = new Configuration();
599 config.setProperties(properties);
601 if ( properties.containsKey(NAMING_STRATEGY))
603 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
604 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
607 @SuppressWarnings("unchecked")
608 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
609 config.setNamingStrategy(namingStrategyClass.newInstance());
613 getLog().error("Error setting NamingStrategy", e);
614 throw new MojoExecutionException(e.getMessage());
618 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
619 for (Class<?> annotatedClass : classes)
621 getLog().debug("Class " + annotatedClass);
622 config.addAnnotatedClass(annotatedClass);
625 if (hibernateMapping != null)
629 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
630 for (String filename : hibernateMapping.split("[\\s,]+"))
632 // First try the filename as absolute/relative path
633 File file = new File(filename);
636 // If the file was not found, search for it in the resource-directories
637 for (Resource resource : project.getResources())
639 file = new File(resource.getDirectory() + File.separator + filename);
644 if (file != null && file.exists())
646 InputStream is = new FileInputStream(file);
647 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
649 while((i = is.read(buffer)) > -1)
650 digest.update(buffer, 0, i);
652 byte[] bytes = digest.digest();
653 BigInteger bi = new BigInteger(1, bytes);
654 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
655 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
656 if (!newMd5.equals(oldMd5))
658 getLog().debug("Found new or modified mapping-file: " + filename);
660 md5s.put(filename, newMd5);
664 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
666 getLog().debug("Adding mappings from XML-configurationfile: " + file);
667 config.addFile(file);
670 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
673 catch (NoSuchAlgorithmException e)
675 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
677 catch (FileNotFoundException e)
679 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
681 catch (IOException e)
683 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
687 Target target = null;
690 target = Target.valueOf(this.target.toUpperCase());
692 catch (IllegalArgumentException e)
694 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
695 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
696 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
701 type = Type.valueOf(this.type.toUpperCase());
703 catch (IllegalArgumentException e)
705 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
706 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
707 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
710 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
712 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
716 && !target.equals(Target.SCRIPT)
717 && !target.equals(Target.NONE)
721 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
722 getLog().info("Skipping schema generation!");
723 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
727 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
728 for (Entry<Object,Object> entry : properties.entrySet())
729 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
731 Connection connection = null;
735 * The connection must be established outside of hibernate, because
736 * hibernate does not use the context-classloader of the current
737 * thread and, hence, would not be able to resolve the driver-class!
739 getLog().debug("Target: " + target + ", Type: " + type);
749 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
750 getLog().debug("Registering JDBC-driver " + driverClass.getName());
751 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
753 "Opening JDBC-connection to "
754 + properties.getProperty(URL)
756 + properties.getProperty(USERNAME)
758 + properties.getProperty(PASSWORD)
760 connection = DriverManager.getConnection(
761 properties.getProperty(URL),
762 properties.getProperty(USERNAME),
763 properties.getProperty(PASSWORD)
768 catch (ClassNotFoundException e)
770 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
771 throw new MojoExecutionException(e.getMessage());
775 getLog().error("Cannot establish connection to database!");
776 Enumeration<Driver> drivers = DriverManager.getDrivers();
777 if (!drivers.hasMoreElements())
778 getLog().error("No drivers registered!");
779 while (drivers.hasMoreElements())
780 getLog().debug("Driver: " + drivers.nextElement());
781 throw new MojoExecutionException(e.getMessage());
784 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
785 MavenLogAppender.startPluginLog(this);
789 * Change class-loader of current thread, so that hibernate can
790 * see all dependencies!
792 Thread.currentThread().setContextClassLoader(classLoader);
794 config.buildMappings();
796 if ("true".equals(properties.getProperty(ENVERS)))
798 getLog().debug("Using envers");
799 AuditConfiguration.getFor(config);
802 SchemaExport export = new SchemaExport(config, connection);
803 export.setOutputFile(outputFile);
804 export.setDelimiter(delimiter);
805 export.setFormat(format);
806 export.execute(target, type);
808 for (Object exception : export.getExceptions())
809 getLog().debug(exception.toString());
813 /** Stop Log-Capturing */
814 MavenLogAppender.endPluginLog(this);
816 /** Restore the old class-loader (TODO: is this really necessary?) */
817 Thread.currentThread().setContextClassLoader(contextClassLoader);
819 /** Close the connection */
822 if (connection != null)
825 catch (SQLException e)
827 getLog().error("Error while closing connection: " + e.getMessage());
831 /** Write md5-sums for annotated classes to file */
834 FileOutputStream fos = new FileOutputStream(saved);
835 ObjectOutputStream oos = new ObjectOutputStream(fos);
836 oos.writeObject(md5s);
842 getLog().error("Cannot write md5-sums to file: " + e);
847 * Needed, because DriverManager won't pick up drivers, that were not
848 * loaded by the system-classloader!
850 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
852 static final class DriverProxy implements Driver
854 private final Driver target;
856 DriverProxy(Driver target)
859 throw new NullPointerException();
860 this.target = target;
863 public java.sql.Driver getTarget()
869 public boolean acceptsURL(String url) throws SQLException
871 return target.acceptsURL(url);
875 public java.sql.Connection connect(
877 java.util.Properties info
882 return target.connect(url, info);
886 public int getMajorVersion()
888 return target.getMajorVersion();
892 public int getMinorVersion()
894 return target.getMinorVersion();
898 public DriverPropertyInfo[] getPropertyInfo(
905 return target.getPropertyInfo(url, info);
909 public boolean jdbcCompliant()
911 return target.jdbcCompliant();
915 * This Method cannot be annotated with @Override, becaus the plugin
916 * will not compile then under Java 1.6!
918 public Logger getParentLogger() throws SQLFeatureNotSupportedException
920 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
924 public String toString()
926 return "Proxy: " + target;
930 public int hashCode()
932 return target.hashCode();
936 public boolean equals(Object obj)
938 if (!(obj instanceof DriverProxy))
940 DriverProxy other = (DriverProxy) obj;
941 return this.target.equals(other.target);