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.tool.hbm2ddl.SchemaExport;
61 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
62 import org.hibernate.tool.hbm2ddl.Target;
63 import org.scannotation.AnnotationDB;
67 * Goal which extracts the hibernate-mapping-configuration and
68 * exports an according SQL-database-schema.
71 * @phase process-classes
73 * @requiresDependencyResolution runtime
75 public class Hbm2DdlMojo extends AbstractMojo
77 public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
79 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
80 public final static String URL = "hibernate.connection.url";
81 public final static String USERNAME = "hibernate.connection.username";
82 public final static String PASSWORD = "hibernate.connection.password";
83 public final static String DIALECT = "hibernate.dialect";
84 public final static String NAMING_STRATEGY="hibernate.ejb.naming_strategy";
86 private final static String MD5S = "schema.md5s";
91 * Only needed internally.
93 * @parameter property="project"
97 private MavenProject project;
102 * Only needed internally.
104 * @parameter property="project.build.directory"
108 private String buildDirectory;
111 * Classes-Directory to scan.
113 * This parameter defaults to the maven build-output-directory for classes.
114 * Additonally, all dependencies are scanned for annotated classes.
116 * @parameter property="project.build.outputDirectory"
118 private String outputDirectory;
121 * Wether to scan test-classes too, or not.
123 * If this parameter is set to <code>true</code> the test-classes of the
124 * artifact will be scanned for hibernate-annotated classes additionally.
126 * @parameter property="hibernate.export.scan_testclasses" default-value="false"
128 private boolean scanTestClasses;
131 * Test-Classes-Directory to scan.
133 * This parameter defaults to the maven build-output-directory for
136 * This parameter is only used, when <code>scanTestClasses</code> is set
137 * to <code>true</code>!
139 * @parameter property="project.build.testOutputDirectory"
141 private String testOutputDirectory;
146 * If set to <code>true</code>, the execution is skipped.
148 * A skipped excecution is signaled via the maven-property
149 * <code>${hibernate.export.skipped}</code>.
151 * The excecution is skipped automatically, if no modified or newly added
152 * annotated classes are found and the dialect was not changed.
154 * @parameter property="maven.test.skip" default-value="false"
156 private boolean skip;
161 * Force execution, even if no modified or newly added annotated classes
162 * where found and the dialect was not changed.
164 * <code>skip</code> takes precedence over <code>force</code>.
166 * @parameter property="hibernate.export.force" default-value="false"
168 private boolean force;
173 * @parameter property="hibernate.connection.driver_class"
175 private String driverClassName;
180 * @parameter property="hibernate.connection.url"
187 * @parameter property="hibernate.connection.username"
189 private String username;
194 * @parameter property="hibernate.connection.password"
196 private String password;
201 * @parameter property="hibernate.dialect"
203 private String hibernateDialect;
206 * Hibernate Naming Strategy
207 * @parameter property="hibernate.ejb.naming_strategy"
209 private String hibernateNamingStrategy;
212 * Path to Hibernate configuration file.
214 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
216 private String hibernateProperties;
219 * List of Hibernate-Mapping-Files (XML).
220 * Multiple files can be separated with white-spaces and/or commas.
222 * @parameter property="hibernate.mapping"
224 private String hibernateMapping;
227 * Target of execution:
229 * <li><strong>NONE</strong> do nothing - just validate the configuration (forces excecution, signals skip)</li>
230 * <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>. forces excecution, signals skip)</li>
231 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
232 * <li><strong>BOTH</strong></li>
235 * @parameter property="hibernate.export.target" default-value="EXPORT"
237 private String target;
242 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
243 * <li><strong>CREATE</strong> create database-schema</li>
244 * <li><strong>DROP</strong> drop database-schema</li>
245 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
248 * @parameter property="hibernate.export.type" default-value="BOTH"
255 * @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
257 private String outputFile;
260 * Delimiter in output-file.
262 * @parameter property="hibernate.export.schema.delimiter" default-value=";"
264 private String delimiter;
267 * Format output-file.
269 * @parameter property="hibernate.export.schema.format" default-value="true"
271 private boolean format;
275 public void execute()
277 MojoFailureException,
278 MojoExecutionException
282 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
283 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
287 File dir = new File(outputDirectory);
289 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
291 Map<String,String> md5s;
292 boolean modified = false;
293 File saved = new File(buildDirectory + File.separator + MD5S);
299 FileInputStream fis = new FileInputStream(saved);
300 ObjectInputStream ois = new ObjectInputStream(fis);
301 md5s = (HashMap<String,String>)ois.readObject();
306 md5s = new HashMap<String,String>();
307 getLog().warn("Cannot read timestamps from saved: " + e);
312 md5s = new HashMap<String,String>();
315 saved.createNewFile();
317 catch (IOException e)
319 getLog().warn("Cannot create saved for timestamps: " + e);
323 ClassLoader classLoader = null;
326 getLog().debug("Creating ClassLoader for project-dependencies...");
327 List<String> classpathFiles = project.getCompileClasspathElements();
329 classpathFiles.addAll(project.getTestClasspathElements());
330 URL[] urls = new URL[classpathFiles.size()];
331 for (int i = 0; i < classpathFiles.size(); ++i)
333 getLog().debug("Dependency: " + classpathFiles.get(i));
334 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
336 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
340 getLog().error("Error while creating ClassLoader!", e);
341 throw new MojoExecutionException(e.getMessage());
344 Set<Class<?>> classes =
345 new TreeSet<Class<?>>(
346 new Comparator<Class<?>>() {
348 public int compare(Class<?> a, Class<?> b)
350 return a.getName().compareTo(b.getName());
357 AnnotationDB db = new AnnotationDB();
358 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
359 URL dirUrl = dir.toURI().toURL();
360 db.scanArchives(dirUrl);
363 dir = new File(testOutputDirectory);
365 throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
366 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
367 dirUrl = dir.toURI().toURL();
368 db.scanArchives(dirUrl);
371 Set<String> classNames = new HashSet<String>();
372 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
373 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
374 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
375 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
376 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
377 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
379 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
380 for (String name : classNames)
382 Class<?> annotatedClass = classLoader.loadClass(name);
383 classes.add(annotatedClass);
386 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
387 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
389 while((i = is.read(buffer)) > -1)
390 digest.update(buffer, 0, i);
392 byte[] bytes = digest.digest();
393 BigInteger bi = new BigInteger(1, bytes);
394 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
395 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
396 if (!newMd5.equals(oldMd5))
398 getLog().debug("Found new or modified annotated class: " + name);
400 md5s.put(name, newMd5);
404 getLog().debug(oldMd5 + " -> class unchanged: " + name);
408 catch (ClassNotFoundException e)
410 getLog().error("Error while adding annotated classes!", e);
411 throw new MojoExecutionException(e.getMessage());
415 getLog().error("Error while scanning!", e);
416 throw new MojoFailureException(e.getMessage());
419 if (classes.isEmpty())
421 if (hibernateMapping == null || hibernateMapping.isEmpty())
422 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
426 getLog().debug("Detected classes with mapping-annotations:");
427 for (Class<?> annotatedClass : classes)
428 getLog().debug(" " + annotatedClass.getName());
432 Properties properties = new Properties();
434 /** Try to read configuration from properties-file */
437 File file = new File(hibernateProperties);
440 getLog().info("Reading properties from file " + hibernateProperties + "...");
441 properties.load(new FileInputStream(file));
444 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
446 catch (IOException e)
448 getLog().error("Error while reading properties!", e);
449 throw new MojoExecutionException(e.getMessage());
452 /** Overwrite values from propertie-file or set, if given */
453 if (driverClassName != null)
455 if (properties.containsKey(DRIVER_CLASS))
457 "Overwriting property " +
458 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
459 " with the value " + driverClassName
462 getLog().debug("Using the value " + driverClassName);
463 properties.setProperty(DRIVER_CLASS, driverClassName);
467 if (properties.containsKey(URL))
469 "Overwriting property " +
470 URL + "=" + properties.getProperty(URL) +
471 " with the value " + url
474 getLog().debug("Using the value " + url);
475 properties.setProperty(URL, url);
477 if (username != null)
479 if (properties.containsKey(USERNAME))
481 "Overwriting property " +
482 USERNAME + "=" + properties.getProperty(USERNAME) +
483 " with the value " + username
486 getLog().debug("Using the value " + username);
487 properties.setProperty(USERNAME, username);
489 if (password != null)
491 if (properties.containsKey(PASSWORD))
493 "Overwriting property " +
494 PASSWORD + "=" + properties.getProperty(PASSWORD) +
495 " with the value " + password
498 getLog().debug("Using the value " + password);
499 properties.setProperty(PASSWORD, password);
501 if (hibernateDialect != null)
503 if (properties.containsKey(DIALECT))
505 "Overwriting property " +
506 DIALECT + "=" + properties.getProperty(DIALECT) +
507 " with the value " + hibernateDialect
510 getLog().debug("Using the value " + hibernateDialect);
511 properties.setProperty(DIALECT, hibernateDialect);
513 if ( hibernateNamingStrategy != null )
515 if ( properties.contains(NAMING_STRATEGY))
517 "Overwriting property " +
518 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
519 " with the value " + hibernateNamingStrategy
522 getLog().debug("Using the value " + hibernateNamingStrategy);
523 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
526 /** The generated SQL varies with the dialect! */
527 if (md5s.containsKey(DIALECT))
529 String dialect = properties.getProperty(DIALECT);
530 if (md5s.get(DIALECT).equals(dialect))
531 getLog().debug("SQL-dialect unchanged.");
534 getLog().debug("SQL-dialect changed: " + dialect);
536 md5s.put(DIALECT, dialect);
542 md5s.put(DIALECT, properties.getProperty(DIALECT));
545 if (properties.isEmpty())
547 getLog().error("No properties set!");
548 throw new MojoFailureException("Hibernate-Configuration is missing!");
551 Configuration config = new Configuration();
552 config.setProperties(properties);
554 if ( properties.containsKey(NAMING_STRATEGY))
556 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
557 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
560 @SuppressWarnings("unchecked")
561 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
562 config.setNamingStrategy(namingStrategyClass.newInstance());
566 getLog().error("Error setting NamingStrategy", e);
567 throw new MojoExecutionException(e.getMessage());
571 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
572 for (Class<?> annotatedClass : classes)
574 getLog().debug("Class " + annotatedClass);
575 config.addAnnotatedClass(annotatedClass);
578 if (hibernateMapping != null)
582 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
583 for (String filename : hibernateMapping.split("[\\s,]+"))
586 for (Resource resource : project.getResources())
588 file = new File(resource.getDirectory() + File.separator + filename);
592 if (file != null && file.exists())
594 InputStream is = new FileInputStream(file);
595 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
597 while((i = is.read(buffer)) > -1)
598 digest.update(buffer, 0, i);
600 byte[] bytes = digest.digest();
601 BigInteger bi = new BigInteger(1, bytes);
602 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
603 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
604 if (!newMd5.equals(oldMd5))
606 getLog().debug("Found new or modified mapping-file: " + filename);
608 md5s.put(filename, newMd5);
612 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
614 getLog().debug("Adding mappings from XML-configurationfile: " + file);
615 config.addFile(file);
618 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
621 catch (NoSuchAlgorithmException e)
623 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
625 catch (FileNotFoundException e)
627 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
629 catch (IOException e)
631 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
635 Target target = null;
638 target = Target.valueOf(this.target.toUpperCase());
640 catch (IllegalArgumentException e)
642 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
643 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
644 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
649 type = Type.valueOf(this.type.toUpperCase());
651 catch (IllegalArgumentException e)
653 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
654 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
655 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
658 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
660 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
664 && !target.equals(Target.SCRIPT)
665 && !target.equals(Target.NONE)
669 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
670 getLog().info("Skipping schema generation!");
671 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
675 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
676 for (Entry<Object,Object> entry : properties.entrySet())
677 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
679 Connection connection = null;
683 * The connection must be established outside of hibernate, because
684 * hibernate does not use the context-classloader of the current
685 * thread and, hence, would not be able to resolve the driver-class!
696 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
697 getLog().debug("Registering JDBC-driver " + driverClass.getName());
698 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
700 "Opening JDBC-connection to "
701 + properties.getProperty(URL)
703 + properties.getProperty(USERNAME)
705 + properties.getProperty(PASSWORD)
707 connection = DriverManager.getConnection(
708 properties.getProperty(URL),
709 properties.getProperty(USERNAME),
710 properties.getProperty(PASSWORD)
715 catch (ClassNotFoundException e)
717 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
718 throw new MojoExecutionException(e.getMessage());
722 getLog().error("Cannot establish connection to database!");
723 Enumeration<Driver> drivers = DriverManager.getDrivers();
724 if (!drivers.hasMoreElements())
725 getLog().error("No drivers registered!");
726 while (drivers.hasMoreElements())
727 getLog().debug("Driver: " + drivers.nextElement());
728 throw new MojoExecutionException(e.getMessage());
731 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
732 MavenLogAppender.startPluginLog(this);
736 * Change class-loader of current thread, so that hibernate can
737 * see all dependencies!
739 Thread.currentThread().setContextClassLoader(classLoader);
741 SchemaExport export = new SchemaExport(config, connection);
742 export.setOutputFile(outputFile);
743 export.setDelimiter(delimiter);
744 export.setFormat(format);
745 export.execute(target, type);
747 for (Object exception : export.getExceptions())
748 getLog().debug(exception.toString());
752 /** Stop Log-Capturing */
753 MavenLogAppender.endPluginLog(this);
755 /** Restore the old class-loader (TODO: is this really necessary?) */
756 Thread.currentThread().setContextClassLoader(contextClassLoader);
758 /** Close the connection */
761 if (connection != null)
764 catch (SQLException e)
766 getLog().error("Error while closing connection: " + e.getMessage());
770 /** Write md5-sums for annotated classes to file */
773 FileOutputStream fos = new FileOutputStream(saved);
774 ObjectOutputStream oos = new ObjectOutputStream(fos);
775 oos.writeObject(md5s);
781 getLog().error("Cannot write md5-sums to file: " + e);
786 * Needed, because DriverManager won't pick up drivers, that were not
787 * loaded by the system-classloader!
789 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
791 static final class DriverProxy implements Driver
793 private final Driver target;
795 DriverProxy(Driver target)
798 throw new NullPointerException();
799 this.target = target;
802 public java.sql.Driver getTarget()
808 public boolean acceptsURL(String url) throws SQLException
810 return target.acceptsURL(url);
814 public java.sql.Connection connect(
816 java.util.Properties info
821 return target.connect(url, info);
825 public int getMajorVersion()
827 return target.getMajorVersion();
831 public int getMinorVersion()
833 return target.getMinorVersion();
837 public DriverPropertyInfo[] getPropertyInfo(
844 return target.getPropertyInfo(url, info);
848 public boolean jdbcCompliant()
850 return target.jdbcCompliant();
854 * This Method cannot be annotated with @Override, becaus the plugin
855 * will not compile then under Java 1.6!
857 public Logger getParentLogger() throws SQLFeatureNotSupportedException
859 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
863 public String toString()
865 return "Proxy: " + target;
869 public int hashCode()
871 return target.hashCode();
875 public boolean equals(Object obj)
877 if (!(obj instanceof DriverProxy))
879 DriverProxy other = (DriverProxy) obj;
880 return this.target.equals(other.target);