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 java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52 import javax.persistence.Embeddable;
53 import javax.persistence.Entity;
54 import javax.persistence.MappedSuperclass;
55 import org.apache.maven.artifact.Artifact;
56 import org.apache.maven.model.Resource;
57 import org.apache.maven.plugin.AbstractMojo;
58 import org.apache.maven.plugin.MojoExecutionException;
59 import org.apache.maven.plugin.MojoFailureException;
60 import org.apache.maven.project.MavenProject;
61 import org.hibernate.cfg.NamingStrategy;
62 import org.hibernate.envers.configuration.spi.AuditConfiguration;
63 import org.hibernate.tool.hbm2ddl.SchemaExport;
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 public final static String MD5S = "hibernate4-generatedschema.md5s";
90 private final static Pattern split = Pattern.compile("[^,\\s]+");
96 * Only needed internally.
98 * @parameter property="project"
102 private MavenProject project;
107 * Only needed internally.
109 * @parameter property="project.build.directory"
113 private String buildDirectory;
116 * Classes-Directory to scan.
118 * This parameter defaults to the maven build-output-directory for classes.
119 * Additionally, all dependencies are scanned for annotated classes.
121 * @parameter property="project.build.outputDirectory"
124 private String outputDirectory;
127 * Whether to scan test-classes too, or not.
129 * If this parameter is set to <code>true</code> the test-classes of the
130 * artifact will be scanned for hibernate-annotated classes additionally.
132 * @parameter property="hibernate.export.scan_testclasses" default-value="false"
135 private boolean scanTestClasses;
138 * Dependency-Scopes, that should be scanned for annotated classes.
140 * By default, only dependencies in the scope <code>compile</code> are
141 * scanned for annotated classes. Multiple scopes can be seperated by
142 * white space or commas.
144 * If you do not want any dependencies to be scanned for annotated
145 * classes, set this parameter to <code>none</code>.
147 * The plugin does not scan for annotated classes in transitive
148 * dependencies. If some of your annotated classes are hidden in a
149 * transitive dependency, you can simply add that dependency explicitly.
151 * @parameter property="hibernate.export.scan_dependencies" default-value="compile"
154 private String scanDependencies;
157 * Test-Classes-Directory to scan.
159 * This parameter defaults to the maven build-output-directory for
162 * This parameter is only used, when <code>scanTestClasses</code> is set
163 * to <code>true</code>!
165 * @parameter property="project.build.testOutputDirectory"
168 private String testOutputDirectory;
173 * If set to <code>true</code>, the execution is skipped.
175 * A skipped execution is signaled via the maven-property
176 * <code>${hibernate.export.skipped}</code>.
178 * The execution is skipped automatically, if no modified or newly added
179 * annotated classes are found and the dialect was not changed.
181 * @parameter property="hibernate.skip" default-value="${maven.test.skip}"
184 private boolean skip;
189 * Force execution, even if no modified or newly added annotated classes
190 * where found and the dialect was not changed.
192 * <code>skip</code> takes precedence over <code>force</code>.
194 * @parameter property="hibernate.export.force" default-value="false"
197 private boolean force;
202 * @parameter property="hibernate.connection.driver_class"
205 private String driverClassName;
210 * @parameter property="hibernate.connection.url"
218 * @parameter property="hibernate.connection.username"
221 private String username;
226 * @parameter property="hibernate.connection.password"
229 private String password;
234 * @parameter property="hibernate.dialect"
237 private String hibernateDialect;
240 * Hibernate Naming Strategy
242 * @parameter property="hibernate.ejb.naming_strategy"
245 private String hibernateNamingStrategy;
248 * Path to Hibernate configuration file.
250 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
253 private String hibernateProperties;
256 * List of Hibernate-Mapping-Files (XML).
257 * Multiple files can be separated with white-spaces and/or commas.
259 * @parameter property="hibernate.mapping"
262 private String hibernateMapping;
265 * Create drop-statements for the generated tables.
266 * At least one of {@link #drop} and {@link #create} must be set.
268 * @parameter property="hibernate.export.drop" default-value="true"
271 private boolean drop;
274 * Create create-statements for the generated tables.
275 * At least one of {@link #drop} and {@link #create} must be set.
277 * @parameter property="hibernate.export.create" default-value="true"
280 private boolean create;
283 * Only create the database schema. Do not export it to the database.
285 * @parameter property="hibernate.export.export" default-value="true"
288 private boolean export;
293 * @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
296 private String outputFile;
299 * Delimiter in output-file.
301 * @parameter property="hibernate.export.schema.delimiter" default-value=";"
304 private String delimiter;
307 * Format output-file.
309 * @parameter property="hibernate.export.schema.format" default-value="true"
312 private boolean format;
315 * Generate envers schema for auditing tables.
317 * @parameter property="hibernate.export.envers" default-value="false"
320 private boolean envers;
324 public void execute()
326 MojoFailureException,
327 MojoExecutionException
331 getLog().info("Execution of hibernate4-maven-plugin:export was skipped!");
332 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
336 if (!create && !drop)
337 throw new MojoFailureException(
338 "At least one of drop and create must be set!"
341 Map<String,String> md5s;
342 boolean modified = false;
343 File saved = new File(buildDirectory + File.separator + MD5S);
345 if (saved.isFile() && saved.length() > 0)
349 FileInputStream fis = new FileInputStream(saved);
350 ObjectInputStream ois = new ObjectInputStream(fis);
351 md5s = (HashMap<String,String>)ois.readObject();
356 md5s = new HashMap<String,String>();
357 getLog().warn("Cannot read timestamps from saved: " + e);
362 md5s = new HashMap<String,String>();
365 saved.createNewFile();
367 catch (IOException e)
369 getLog().debug("Cannot create file \"" + saved.getPath() + "\" for timestamps: " + e);
373 ClassLoader classLoader = null;
376 getLog().debug("Creating ClassLoader for project-dependencies...");
377 List<String> classpathFiles = project.getCompileClasspathElements();
379 classpathFiles.addAll(project.getTestClasspathElements());
380 URL[] urls = new URL[classpathFiles.size()];
381 for (int i = 0; i < classpathFiles.size(); ++i)
383 getLog().debug("Dependency: " + classpathFiles.get(i));
384 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
386 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
390 getLog().error("Error while creating ClassLoader!", e);
391 throw new MojoExecutionException(e.getMessage());
394 Set<Class<?>> classes =
395 new TreeSet<Class<?>>(
396 new Comparator<Class<?>>() {
398 public int compare(Class<?> a, Class<?> b)
400 return a.getName().compareTo(b.getName());
407 AnnotationDB db = new AnnotationDB();
408 File dir = new File(outputDirectory);
411 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
412 URL dirUrl = dir.toURI().toURL();
413 db.scanArchives(dirUrl);
417 dir = new File(testOutputDirectory);
420 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
421 URL dirUrl = dir.toURI().toURL();
422 db.scanArchives(dirUrl);
425 if (scanDependencies != null)
427 Matcher matcher = split.matcher(scanDependencies);
428 while (matcher.find())
430 getLog().info("Scanning dependencies for scope " + matcher.group());
431 for (Artifact artifact : project.getDependencyArtifacts())
433 if (!artifact.getScope().equalsIgnoreCase(matcher.group()))
435 if (artifact.getFile() == null)
438 "Cannot scan dependency " +
440 ": no JAR-file available!"
445 "Scanning dependency " +
447 " for annotated classes..."
449 db.scanArchives(artifact.getFile().toURI().toURL());
454 Set<String> classNames = new HashSet<String>();
455 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
456 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
457 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
458 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
459 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
460 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
462 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
463 for (String name : classNames)
465 Class<?> annotatedClass = classLoader.loadClass(name);
466 classes.add(annotatedClass);
467 String resourceName = annotatedClass.getName();
468 resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
471 .getResourceAsStream(resourceName);
472 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
474 while((i = is.read(buffer)) > -1)
475 digest.update(buffer, 0, i);
477 byte[] bytes = digest.digest();
478 BigInteger bi = new BigInteger(1, bytes);
479 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
480 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
481 if (!newMd5.equals(oldMd5))
483 getLog().debug("Found new or modified annotated class: " + name);
485 md5s.put(name, newMd5);
489 getLog().debug(oldMd5 + " -> class unchanged: " + name);
493 catch (ClassNotFoundException e)
495 getLog().error("Error while adding annotated classes!", e);
496 throw new MojoExecutionException(e.getMessage());
500 getLog().error("Error while scanning!", e);
501 throw new MojoFailureException(e.getMessage());
504 if (classes.isEmpty())
506 if (hibernateMapping == null || hibernateMapping.isEmpty())
507 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
511 getLog().debug("Detected classes with mapping-annotations:");
512 for (Class<?> annotatedClass : classes)
513 getLog().debug(" " + annotatedClass.getName());
517 Properties properties = new Properties();
519 /** Try to read configuration from properties-file */
522 File file = new File(hibernateProperties);
525 getLog().info("Reading properties from file " + hibernateProperties + "...");
526 properties.load(new FileInputStream(file));
529 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
531 catch (IOException e)
533 getLog().error("Error while reading properties!", e);
534 throw new MojoExecutionException(e.getMessage());
537 /** Overwrite values from properties-file or set, if given */
538 if (driverClassName != null)
540 if (properties.containsKey(DRIVER_CLASS))
542 "Overwriting property " +
543 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
544 " with the value " + driverClassName
547 getLog().debug("Using the value " + driverClassName);
548 properties.setProperty(DRIVER_CLASS, driverClassName);
552 if (properties.containsKey(URL))
554 "Overwriting property " +
555 URL + "=" + properties.getProperty(URL) +
556 " with the value " + url
559 getLog().debug("Using the value " + url);
560 properties.setProperty(URL, url);
562 if (username != null)
564 if (properties.containsKey(USERNAME))
566 "Overwriting property " +
567 USERNAME + "=" + properties.getProperty(USERNAME) +
568 " with the value " + username
571 getLog().debug("Using the value " + username);
572 properties.setProperty(USERNAME, username);
574 if (password != null)
576 if (properties.containsKey(PASSWORD))
578 "Overwriting property " +
579 PASSWORD + "=" + properties.getProperty(PASSWORD) +
580 " with value " + password
583 getLog().debug("Using value " + password + " for property " + PASSWORD);
584 properties.setProperty(PASSWORD, password);
586 if (hibernateDialect != null)
588 if (properties.containsKey(DIALECT))
590 "Overwriting property " +
591 DIALECT + "=" + properties.getProperty(DIALECT) +
592 " with value " + hibernateDialect
596 "Using value " + hibernateDialect + " for property " + DIALECT
598 properties.setProperty(DIALECT, hibernateDialect);
602 hibernateDialect = properties.getProperty(DIALECT);
604 if ( hibernateNamingStrategy != null )
606 if ( properties.contains(NAMING_STRATEGY))
608 "Overwriting property " +
609 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
610 " with value " + hibernateNamingStrategy
614 "Using value " + hibernateNamingStrategy + " for property " +
617 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
620 /** The generated SQL varies with the dialect! */
621 if (md5s.containsKey(DIALECT))
623 String dialect = properties.getProperty(DIALECT);
624 if (md5s.get(DIALECT).equals(dialect))
625 getLog().debug("SQL-dialect unchanged.");
631 getLog().debug("SQL-dialect was unset.");
632 md5s.remove(DIALECT);
636 getLog().debug("SQL-dialect changed: " + dialect);
637 md5s.put(DIALECT, dialect);
643 String dialect = properties.getProperty(DIALECT);
647 md5s.put(DIALECT, properties.getProperty(DIALECT));
651 /** The generated SQL varies with the envers-configuration */
652 if (md5s.get(ENVERS) != null)
654 if (md5s.get(ENVERS).equals(Boolean.toString(envers)))
655 getLog().debug("Envers-Configuration unchanged. Enabled: " + envers);
658 getLog().debug("Envers-Configuration changed. Enabled: " + envers);
660 md5s.put(ENVERS, Boolean.toString(envers));
666 md5s.put(ENVERS, Boolean.toString(envers));
669 if (properties.isEmpty())
671 getLog().error("No properties set!");
672 throw new MojoFailureException("Hibernate configuration is missing!");
675 final ValidationConfiguration config = new ValidationConfiguration(hibernateDialect);
677 config.setProperties(properties);
679 if ( properties.containsKey(NAMING_STRATEGY))
681 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
682 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
685 @SuppressWarnings("unchecked")
686 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
687 config.setNamingStrategy(namingStrategyClass.newInstance());
691 getLog().error("Error setting NamingStrategy", e);
692 throw new MojoExecutionException(e.getMessage());
696 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
697 Connection connection = null;
698 MavenLogAppender.startPluginLog(this);
702 * Change class-loader of current thread, so that hibernate can
703 * see all dependencies!
705 Thread.currentThread().setContextClassLoader(classLoader);
707 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
708 // build annotated packages
709 Set<String> packages = new HashSet<String>();
710 for (Class<?> annotatedClass : classes)
712 String packageName = annotatedClass.getPackage().getName();
713 if (!packages.contains(packageName))
715 getLog().debug("Add package " + packageName);
716 packages.add(packageName);
717 config.addPackage(packageName);
718 getLog().debug("type definintions" + config.getTypeDefs());
720 getLog().debug("Class " + annotatedClass);
721 config.addAnnotatedClass(annotatedClass);
724 if (hibernateMapping != null)
728 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
729 for (String filename : hibernateMapping.split("[\\s,]+"))
731 // First try the filename as absolute/relative path
732 File file = new File(filename);
735 // If the file was not found, search for it in the resource-directories
736 for (Resource resource : project.getResources())
738 file = new File(resource.getDirectory() + File.separator + filename);
743 if (file != null && file.exists())
745 InputStream is = new FileInputStream(file);
746 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
748 while((i = is.read(buffer)) > -1)
749 digest.update(buffer, 0, i);
751 byte[] bytes = digest.digest();
752 BigInteger bi = new BigInteger(1, bytes);
753 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
754 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
755 if (!newMd5.equals(oldMd5))
757 getLog().debug("Found new or modified mapping-file: " + filename);
759 md5s.put(filename, newMd5);
763 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
765 getLog().debug("Adding mappings from XML-configurationfile: " + file);
766 config.addFile(file);
769 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
772 catch (NoSuchAlgorithmException e)
774 throw new MojoFailureException("Cannot calculate MD5 sums!", e);
776 catch (FileNotFoundException e)
778 throw new MojoFailureException("Cannot calculate MD5 sums!", e);
780 catch (IOException e)
782 throw new MojoFailureException("Cannot calculate MD5 sums!", e);
786 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
787 for (Entry<Object,Object> entry : properties.entrySet())
788 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
793 "No modified annotated classes or mapping-files found and " +
797 getLog().info("Schema generation is forced!");
800 getLog().info("Skipping schema generation!");
801 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
809 * The connection must be established outside of hibernate, because
810 * hibernate does not use the context-classloader of the current
811 * thread and, hence, would not be able to resolve the driver-class!
815 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
816 getLog().debug("Registering JDBC-driver " + driverClass.getName());
817 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
819 "Opening JDBC-connection to "
820 + properties.getProperty(URL)
822 + properties.getProperty(USERNAME)
824 + properties.getProperty(PASSWORD)
826 connection = DriverManager.getConnection(
827 properties.getProperty(URL),
828 properties.getProperty(USERNAME),
829 properties.getProperty(PASSWORD)
833 catch (ClassNotFoundException e)
835 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
836 throw new MojoExecutionException(e.getMessage());
840 getLog().error("Cannot establish connection to database!");
841 Enumeration<Driver> drivers = DriverManager.getDrivers();
842 if (!drivers.hasMoreElements())
843 getLog().error("No drivers registered!");
844 while (drivers.hasMoreElements())
845 getLog().debug("Driver: " + drivers.nextElement());
846 throw new MojoExecutionException(e.getMessage());
849 config.buildMappings();
853 getLog().info("Automatic auditing via hibernate-envers enabled!");
854 AuditConfiguration.getFor(config);
857 SchemaExport export = new SchemaExport(config, connection);
858 export.setDelimiter(delimiter);
859 export.setFormat(format);
861 File outF = new File(outputFile);
863 if (!outF.isAbsolute())
865 // Interpret relative file path relative to build directory
866 outF = new File(buildDirectory, outputFile);
867 getLog().info("Adjusted relative path, resulting path is " + outF.getPath());
870 // Ensure that directory path for specified file exists
871 File outFileParentDir = outF.getParentFile();
872 if (null != outFileParentDir && !outFileParentDir.exists())
876 getLog().info("Creating directory path for output file:" + outFileParentDir.getPath());
877 outFileParentDir.mkdirs();
881 getLog().error("Error creating directory path for output file: " + e.getLocalizedMessage());
885 export.setOutputFile(outF.getPath());
886 export.execute(false, this.export, drop && !create, create && !drop);
888 for (Object exception : export.getExceptions())
889 getLog().debug(exception.toString());
893 /** Stop Log-Capturing */
894 MavenLogAppender.endPluginLog(this);
896 /** Restore the old class-loader (TODO: is this really necessary?) */
897 Thread.currentThread().setContextClassLoader(contextClassLoader);
899 /** Close the connection */
902 if (connection != null)
905 catch (SQLException e)
907 getLog().error("Error while closing connection: " + e.getMessage());
911 /** Write md5-sums for annotated classes to file */
914 FileOutputStream fos = new FileOutputStream(saved);
915 ObjectOutputStream oos = new ObjectOutputStream(fos);
916 oos.writeObject(md5s);
922 getLog().error("Cannot write md5-sums to file: " + e);
927 * Needed, because DriverManager won't pick up drivers, that were not
928 * loaded by the system-classloader!
930 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
932 static final class DriverProxy implements Driver
934 private final Driver target;
936 DriverProxy(Driver target)
939 throw new NullPointerException();
940 this.target = target;
943 public java.sql.Driver getTarget()
949 public boolean acceptsURL(String url) throws SQLException
951 return target.acceptsURL(url);
955 public java.sql.Connection connect(
957 java.util.Properties info
962 return target.connect(url, info);
966 public int getMajorVersion()
968 return target.getMajorVersion();
972 public int getMinorVersion()
974 return target.getMinorVersion();
978 public DriverPropertyInfo[] getPropertyInfo(
985 return target.getPropertyInfo(url, info);
989 public boolean jdbcCompliant()
991 return target.jdbcCompliant();
995 * This Method cannot be annotated with @Override, becaus the plugin
996 * will not compile then under Java 1.6!
998 public Logger getParentLogger() throws SQLFeatureNotSupportedException
1000 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
1004 public String toString()
1006 return "Proxy: " + target;
1010 public int hashCode()
1012 return target.hashCode();
1016 public boolean equals(Object obj)
1018 if (!(obj instanceof DriverProxy))
1020 DriverProxy other = (DriverProxy) obj;
1021 return this.target.equals(other.target);