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.export.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 property="hibernate.export.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 value " + password
514 getLog().debug("Using value " + password + " for property " + 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 value " + hibernateDialect
527 "Using value " + hibernateDialect + " for property " + DIALECT
529 properties.setProperty(DIALECT, hibernateDialect);
531 if ( hibernateNamingStrategy != null )
533 if ( properties.contains(NAMING_STRATEGY))
535 "Overwriting property " +
536 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
537 " with value " + hibernateNamingStrategy
541 "Using value " + hibernateNamingStrategy + " for property " +
544 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
547 /** The generated SQL varies with the dialect! */
548 if (md5s.containsKey(DIALECT))
550 String dialect = properties.getProperty(DIALECT);
551 if (md5s.get(DIALECT).equals(dialect))
552 getLog().debug("SQL-dialect unchanged.");
555 getLog().debug("SQL-dialect changed: " + dialect);
557 md5s.put(DIALECT, dialect);
563 md5s.put(DIALECT, properties.getProperty(DIALECT));
566 /** The generated SQL varies with the envers-configuration */
567 if (md5s.get(ENVERS) != null)
569 if (md5s.get(ENVERS).equals(Boolean.toString(envers)))
570 getLog().debug("Envers-Configuration unchanged. Enabled: " + envers);
573 getLog().debug("Envers-Configuration changed. Enabled: " + envers);
575 md5s.put(ENVERS, Boolean.toString(envers));
581 md5s.put(ENVERS, Boolean.toString(envers));
584 if (properties.isEmpty())
586 getLog().error("No properties set!");
587 throw new MojoFailureException("Hibernate-Configuration is missing!");
590 Configuration config = new Configuration();
591 config.setProperties(properties);
593 if ( properties.containsKey(NAMING_STRATEGY))
595 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
596 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
599 @SuppressWarnings("unchecked")
600 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
601 config.setNamingStrategy(namingStrategyClass.newInstance());
605 getLog().error("Error setting NamingStrategy", e);
606 throw new MojoExecutionException(e.getMessage());
610 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
611 for (Class<?> annotatedClass : classes)
613 getLog().debug("Class " + annotatedClass);
614 config.addAnnotatedClass(annotatedClass);
617 if (hibernateMapping != null)
621 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
622 for (String filename : hibernateMapping.split("[\\s,]+"))
624 // First try the filename as absolute/relative path
625 File file = new File(filename);
628 // If the file was not found, search for it in the resource-directories
629 for (Resource resource : project.getResources())
631 file = new File(resource.getDirectory() + File.separator + filename);
636 if (file != null && file.exists())
638 InputStream is = new FileInputStream(file);
639 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
641 while((i = is.read(buffer)) > -1)
642 digest.update(buffer, 0, i);
644 byte[] bytes = digest.digest();
645 BigInteger bi = new BigInteger(1, bytes);
646 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
647 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
648 if (!newMd5.equals(oldMd5))
650 getLog().debug("Found new or modified mapping-file: " + filename);
652 md5s.put(filename, newMd5);
656 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
658 getLog().debug("Adding mappings from XML-configurationfile: " + file);
659 config.addFile(file);
662 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
665 catch (NoSuchAlgorithmException e)
667 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
669 catch (FileNotFoundException e)
671 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
673 catch (IOException e)
675 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
679 Target target = null;
682 target = Target.valueOf(this.target.toUpperCase());
684 catch (IllegalArgumentException e)
686 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
687 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
688 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
693 type = Type.valueOf(this.type.toUpperCase());
695 catch (IllegalArgumentException e)
697 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
698 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
699 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
702 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
704 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
708 && !target.equals(Target.SCRIPT)
709 && !target.equals(Target.NONE)
713 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
714 getLog().info("Skipping schema generation!");
715 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
719 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
720 for (Entry<Object,Object> entry : properties.entrySet())
721 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
723 Connection connection = null;
727 * The connection must be established outside of hibernate, because
728 * hibernate does not use the context-classloader of the current
729 * thread and, hence, would not be able to resolve the driver-class!
731 getLog().debug("Target: " + target + ", Type: " + type);
741 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
742 getLog().debug("Registering JDBC-driver " + driverClass.getName());
743 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
745 "Opening JDBC-connection to "
746 + properties.getProperty(URL)
748 + properties.getProperty(USERNAME)
750 + properties.getProperty(PASSWORD)
752 connection = DriverManager.getConnection(
753 properties.getProperty(URL),
754 properties.getProperty(USERNAME),
755 properties.getProperty(PASSWORD)
760 catch (ClassNotFoundException e)
762 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
763 throw new MojoExecutionException(e.getMessage());
767 getLog().error("Cannot establish connection to database!");
768 Enumeration<Driver> drivers = DriverManager.getDrivers();
769 if (!drivers.hasMoreElements())
770 getLog().error("No drivers registered!");
771 while (drivers.hasMoreElements())
772 getLog().debug("Driver: " + drivers.nextElement());
773 throw new MojoExecutionException(e.getMessage());
776 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
777 MavenLogAppender.startPluginLog(this);
781 * Change class-loader of current thread, so that hibernate can
782 * see all dependencies!
784 Thread.currentThread().setContextClassLoader(classLoader);
786 config.buildMappings();
790 getLog().info("Automatic auditing via hibernate-envers enabled!");
791 AuditConfiguration.getFor(config);
794 SchemaExport export = new SchemaExport(config, connection);
795 export.setOutputFile(outputFile);
796 export.setDelimiter(delimiter);
797 export.setFormat(format);
798 export.execute(target, type);
800 for (Object exception : export.getExceptions())
801 getLog().debug(exception.toString());
805 /** Stop Log-Capturing */
806 MavenLogAppender.endPluginLog(this);
808 /** Restore the old class-loader (TODO: is this really necessary?) */
809 Thread.currentThread().setContextClassLoader(contextClassLoader);
811 /** Close the connection */
814 if (connection != null)
817 catch (SQLException e)
819 getLog().error("Error while closing connection: " + e.getMessage());
823 /** Write md5-sums for annotated classes to file */
826 FileOutputStream fos = new FileOutputStream(saved);
827 ObjectOutputStream oos = new ObjectOutputStream(fos);
828 oos.writeObject(md5s);
834 getLog().error("Cannot write md5-sums to file: " + e);
839 * Needed, because DriverManager won't pick up drivers, that were not
840 * loaded by the system-classloader!
842 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
844 static final class DriverProxy implements Driver
846 private final Driver target;
848 DriverProxy(Driver target)
851 throw new NullPointerException();
852 this.target = target;
855 public java.sql.Driver getTarget()
861 public boolean acceptsURL(String url) throws SQLException
863 return target.acceptsURL(url);
867 public java.sql.Connection connect(
869 java.util.Properties info
874 return target.connect(url, info);
878 public int getMajorVersion()
880 return target.getMajorVersion();
884 public int getMinorVersion()
886 return target.getMinorVersion();
890 public DriverPropertyInfo[] getPropertyInfo(
897 return target.getPropertyInfo(url, info);
901 public boolean jdbcCompliant()
903 return target.jdbcCompliant();
907 * This Method cannot be annotated with @Override, becaus the plugin
908 * will not compile then under Java 1.6!
910 public Logger getParentLogger() throws SQLFeatureNotSupportedException
912 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
916 public String toString()
918 return "Proxy: " + target;
922 public int hashCode()
924 return target.hashCode();
928 public boolean equals(Object obj)
930 if (!(obj instanceof DriverProxy))
932 DriverProxy other = (DriverProxy) obj;
933 return this.target.equals(other.target);