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 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);
542 /** The generated SQL varies with the dialect! */
543 if (md5s.containsKey(DIALECT))
545 String dialect = properties.getProperty(DIALECT);
546 if (md5s.get(DIALECT).equals(dialect))
547 getLog().debug("SQL-dialect unchanged.");
550 getLog().debug("SQL-dialect changed: " + dialect);
552 md5s.put(DIALECT, dialect);
558 md5s.put(DIALECT, properties.getProperty(DIALECT));
561 /** The generated SQL varies with the envers-configuration */
562 if (md5s.get(ENVERS) != null)
564 if (md5s.get(ENVERS).equals(Boolean.toString(envers)))
565 getLog().debug("Envers-Configuration unchanged. Enabled: " + envers);
568 getLog().debug("Envers-Configuration changed. Enabled: " + envers);
570 md5s.put(ENVERS, Boolean.toString(envers));
576 md5s.put(ENVERS, Boolean.toString(envers));
579 if (properties.isEmpty())
581 getLog().error("No properties set!");
582 throw new MojoFailureException("Hibernate-Configuration is missing!");
585 Configuration config = new Configuration();
586 config.setProperties(properties);
588 if ( properties.containsKey(NAMING_STRATEGY))
590 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
591 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
594 @SuppressWarnings("unchecked")
595 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
596 config.setNamingStrategy(namingStrategyClass.newInstance());
600 getLog().error("Error setting NamingStrategy", e);
601 throw new MojoExecutionException(e.getMessage());
605 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
606 for (Class<?> annotatedClass : classes)
608 getLog().debug("Class " + annotatedClass);
609 config.addAnnotatedClass(annotatedClass);
612 if (hibernateMapping != null)
616 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
617 for (String filename : hibernateMapping.split("[\\s,]+"))
619 // First try the filename as absolute/relative path
620 File file = new File(filename);
623 // If the file was not found, search for it in the resource-directories
624 for (Resource resource : project.getResources())
626 file = new File(resource.getDirectory() + File.separator + filename);
631 if (file != null && file.exists())
633 InputStream is = new FileInputStream(file);
634 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
636 while((i = is.read(buffer)) > -1)
637 digest.update(buffer, 0, i);
639 byte[] bytes = digest.digest();
640 BigInteger bi = new BigInteger(1, bytes);
641 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
642 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
643 if (!newMd5.equals(oldMd5))
645 getLog().debug("Found new or modified mapping-file: " + filename);
647 md5s.put(filename, newMd5);
651 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
653 getLog().debug("Adding mappings from XML-configurationfile: " + file);
654 config.addFile(file);
657 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
660 catch (NoSuchAlgorithmException e)
662 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
664 catch (FileNotFoundException e)
666 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
668 catch (IOException e)
670 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
674 Target target = null;
677 target = Target.valueOf(this.target.toUpperCase());
679 catch (IllegalArgumentException e)
681 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
682 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
683 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
688 type = Type.valueOf(this.type.toUpperCase());
690 catch (IllegalArgumentException e)
692 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
693 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
694 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
697 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
699 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
703 && !target.equals(Target.SCRIPT)
704 && !target.equals(Target.NONE)
708 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
709 getLog().info("Skipping schema generation!");
710 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
714 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
715 for (Entry<Object,Object> entry : properties.entrySet())
716 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
718 Connection connection = null;
722 * The connection must be established outside of hibernate, because
723 * hibernate does not use the context-classloader of the current
724 * thread and, hence, would not be able to resolve the driver-class!
726 getLog().debug("Target: " + target + ", Type: " + type);
736 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
737 getLog().debug("Registering JDBC-driver " + driverClass.getName());
738 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
740 "Opening JDBC-connection to "
741 + properties.getProperty(URL)
743 + properties.getProperty(USERNAME)
745 + properties.getProperty(PASSWORD)
747 connection = DriverManager.getConnection(
748 properties.getProperty(URL),
749 properties.getProperty(USERNAME),
750 properties.getProperty(PASSWORD)
755 catch (ClassNotFoundException e)
757 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
758 throw new MojoExecutionException(e.getMessage());
762 getLog().error("Cannot establish connection to database!");
763 Enumeration<Driver> drivers = DriverManager.getDrivers();
764 if (!drivers.hasMoreElements())
765 getLog().error("No drivers registered!");
766 while (drivers.hasMoreElements())
767 getLog().debug("Driver: " + drivers.nextElement());
768 throw new MojoExecutionException(e.getMessage());
771 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
772 MavenLogAppender.startPluginLog(this);
776 * Change class-loader of current thread, so that hibernate can
777 * see all dependencies!
779 Thread.currentThread().setContextClassLoader(classLoader);
781 config.buildMappings();
785 getLog().info("Automatic auditing via hibernate-envers enabled!");
786 AuditConfiguration.getFor(config);
789 SchemaExport export = new SchemaExport(config, connection);
790 export.setOutputFile(outputFile);
791 export.setDelimiter(delimiter);
792 export.setFormat(format);
793 export.execute(target, type);
795 for (Object exception : export.getExceptions())
796 getLog().debug(exception.toString());
800 /** Stop Log-Capturing */
801 MavenLogAppender.endPluginLog(this);
803 /** Restore the old class-loader (TODO: is this really necessary?) */
804 Thread.currentThread().setContextClassLoader(contextClassLoader);
806 /** Close the connection */
809 if (connection != null)
812 catch (SQLException e)
814 getLog().error("Error while closing connection: " + e.getMessage());
818 /** Write md5-sums for annotated classes to file */
821 FileOutputStream fos = new FileOutputStream(saved);
822 ObjectOutputStream oos = new ObjectOutputStream(fos);
823 oos.writeObject(md5s);
829 getLog().error("Cannot write md5-sums to file: " + e);
834 * Needed, because DriverManager won't pick up drivers, that were not
835 * loaded by the system-classloader!
837 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
839 static final class DriverProxy implements Driver
841 private final Driver target;
843 DriverProxy(Driver target)
846 throw new NullPointerException();
847 this.target = target;
850 public java.sql.Driver getTarget()
856 public boolean acceptsURL(String url) throws SQLException
858 return target.acceptsURL(url);
862 public java.sql.Connection connect(
864 java.util.Properties info
869 return target.connect(url, info);
873 public int getMajorVersion()
875 return target.getMajorVersion();
879 public int getMinorVersion()
881 return target.getMinorVersion();
885 public DriverPropertyInfo[] getPropertyInfo(
892 return target.getPropertyInfo(url, info);
896 public boolean jdbcCompliant()
898 return target.jdbcCompliant();
902 * This Method cannot be annotated with @Override, becaus the plugin
903 * will not compile then under Java 1.6!
905 public Logger getParentLogger() throws SQLFeatureNotSupportedException
907 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
911 public String toString()
913 return "Proxy: " + target;
917 public int hashCode()
919 return target.hashCode();
923 public boolean equals(Object obj)
925 if (!(obj instanceof DriverProxy))
927 DriverProxy other = (DriverProxy) obj;
928 return this.target.equals(other.target);