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> only export schema to SQL-script (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 and print it to STDOUT</li>
232 * <li><strong>BOTH</strong></li>
235 * A databaseconnection is only needed for EXPORT and BOTH, but a
236 * Hibernate-Dialect must always be choosen.
238 * @parameter property="hibernate.export.target" default-value="EXPORT"
240 private String target;
245 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
246 * <li><strong>CREATE</strong> create database-schema</li>
247 * <li><strong>DROP</strong> drop database-schema</li>
248 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
251 * If NONE is choosen, no databaseconnection is needed.
253 * @parameter property="hibernate.export.type" default-value="BOTH"
260 * @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
262 private String outputFile;
265 * Delimiter in output-file.
267 * @parameter property="hibernate.export.schema.delimiter" default-value=";"
269 private String delimiter;
272 * Format output-file.
274 * @parameter property="hibernate.export.schema.format" default-value="true"
276 private boolean format;
280 public void execute()
282 MojoFailureException,
283 MojoExecutionException
287 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
288 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
292 Map<String,String> md5s;
293 boolean modified = false;
294 File saved = new File(buildDirectory + File.separator + MD5S);
300 FileInputStream fis = new FileInputStream(saved);
301 ObjectInputStream ois = new ObjectInputStream(fis);
302 md5s = (HashMap<String,String>)ois.readObject();
307 md5s = new HashMap<String,String>();
308 getLog().warn("Cannot read timestamps from saved: " + e);
313 md5s = new HashMap<String,String>();
316 saved.createNewFile();
318 catch (IOException e)
320 getLog().debug("Cannot create file \"" + saved.getPath() + "\" for timestamps: " + e);
324 ClassLoader classLoader = null;
327 getLog().debug("Creating ClassLoader for project-dependencies...");
328 List<String> classpathFiles = project.getCompileClasspathElements();
330 classpathFiles.addAll(project.getTestClasspathElements());
331 URL[] urls = new URL[classpathFiles.size()];
332 for (int i = 0; i < classpathFiles.size(); ++i)
334 getLog().debug("Dependency: " + classpathFiles.get(i));
335 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
337 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
341 getLog().error("Error while creating ClassLoader!", e);
342 throw new MojoExecutionException(e.getMessage());
345 Set<Class<?>> classes =
346 new TreeSet<Class<?>>(
347 new Comparator<Class<?>>() {
349 public int compare(Class<?> a, Class<?> b)
351 return a.getName().compareTo(b.getName());
358 AnnotationDB db = new AnnotationDB();
359 File dir = new File(outputDirectory);
362 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
363 URL dirUrl = dir.toURI().toURL();
364 db.scanArchives(dirUrl);
368 dir = new File(testOutputDirectory);
371 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
372 URL dirUrl = dir.toURI().toURL();
373 db.scanArchives(dirUrl);
377 Set<String> classNames = new HashSet<String>();
378 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
379 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
380 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
381 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
382 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
383 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
385 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
386 for (String name : classNames)
388 Class<?> annotatedClass = classLoader.loadClass(name);
389 classes.add(annotatedClass);
390 String resourceName = annotatedClass.getName();
391 resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
394 .getResourceAsStream(resourceName);
395 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
397 while((i = is.read(buffer)) > -1)
398 digest.update(buffer, 0, i);
400 byte[] bytes = digest.digest();
401 BigInteger bi = new BigInteger(1, bytes);
402 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
403 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
404 if (!newMd5.equals(oldMd5))
406 getLog().debug("Found new or modified annotated class: " + name);
408 md5s.put(name, newMd5);
412 getLog().debug(oldMd5 + " -> class unchanged: " + name);
416 catch (ClassNotFoundException e)
418 getLog().error("Error while adding annotated classes!", e);
419 throw new MojoExecutionException(e.getMessage());
423 getLog().error("Error while scanning!", e);
424 throw new MojoFailureException(e.getMessage());
427 if (classes.isEmpty())
429 if (hibernateMapping == null || hibernateMapping.isEmpty())
430 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
434 getLog().debug("Detected classes with mapping-annotations:");
435 for (Class<?> annotatedClass : classes)
436 getLog().debug(" " + annotatedClass.getName());
440 Properties properties = new Properties();
442 /** Try to read configuration from properties-file */
445 File file = new File(hibernateProperties);
448 getLog().info("Reading properties from file " + hibernateProperties + "...");
449 properties.load(new FileInputStream(file));
452 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
454 catch (IOException e)
456 getLog().error("Error while reading properties!", e);
457 throw new MojoExecutionException(e.getMessage());
460 /** Overwrite values from propertie-file or set, if given */
461 if (driverClassName != null)
463 if (properties.containsKey(DRIVER_CLASS))
465 "Overwriting property " +
466 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
467 " with the value " + driverClassName
470 getLog().debug("Using the value " + driverClassName);
471 properties.setProperty(DRIVER_CLASS, driverClassName);
475 if (properties.containsKey(URL))
477 "Overwriting property " +
478 URL + "=" + properties.getProperty(URL) +
479 " with the value " + url
482 getLog().debug("Using the value " + url);
483 properties.setProperty(URL, url);
485 if (username != null)
487 if (properties.containsKey(USERNAME))
489 "Overwriting property " +
490 USERNAME + "=" + properties.getProperty(USERNAME) +
491 " with the value " + username
494 getLog().debug("Using the value " + username);
495 properties.setProperty(USERNAME, username);
497 if (password != null)
499 if (properties.containsKey(PASSWORD))
501 "Overwriting property " +
502 PASSWORD + "=" + properties.getProperty(PASSWORD) +
503 " with the value " + password
506 getLog().debug("Using the value " + password);
507 properties.setProperty(PASSWORD, password);
509 if (hibernateDialect != null)
511 if (properties.containsKey(DIALECT))
513 "Overwriting property " +
514 DIALECT + "=" + properties.getProperty(DIALECT) +
515 " with the value " + hibernateDialect
518 getLog().debug("Using the value " + hibernateDialect);
519 properties.setProperty(DIALECT, hibernateDialect);
521 if ( hibernateNamingStrategy != null )
523 if ( properties.contains(NAMING_STRATEGY))
525 "Overwriting property " +
526 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
527 " with the value " + hibernateNamingStrategy
530 getLog().debug("Using the value " + hibernateNamingStrategy);
531 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
534 /** The generated SQL varies with the dialect! */
535 if (md5s.containsKey(DIALECT))
537 String dialect = properties.getProperty(DIALECT);
538 if (md5s.get(DIALECT).equals(dialect))
539 getLog().debug("SQL-dialect unchanged.");
542 getLog().debug("SQL-dialect changed: " + dialect);
544 md5s.put(DIALECT, dialect);
550 md5s.put(DIALECT, properties.getProperty(DIALECT));
553 if (properties.isEmpty())
555 getLog().error("No properties set!");
556 throw new MojoFailureException("Hibernate-Configuration is missing!");
559 Configuration config = new Configuration();
560 config.setProperties(properties);
562 if ( properties.containsKey(NAMING_STRATEGY))
564 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
565 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
568 @SuppressWarnings("unchecked")
569 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
570 config.setNamingStrategy(namingStrategyClass.newInstance());
574 getLog().error("Error setting NamingStrategy", e);
575 throw new MojoExecutionException(e.getMessage());
579 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
580 for (Class<?> annotatedClass : classes)
582 getLog().debug("Class " + annotatedClass);
583 config.addAnnotatedClass(annotatedClass);
586 if (hibernateMapping != null)
590 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
591 for (String filename : hibernateMapping.split("[\\s,]+"))
593 // First try the filename as absolute/relative path
594 File file = new File(filename);
597 // If the file was not found, search for it in the resource-directories
598 for (Resource resource : project.getResources())
600 file = new File(resource.getDirectory() + File.separator + filename);
605 if (file != null && file.exists())
607 InputStream is = new FileInputStream(file);
608 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
610 while((i = is.read(buffer)) > -1)
611 digest.update(buffer, 0, i);
613 byte[] bytes = digest.digest();
614 BigInteger bi = new BigInteger(1, bytes);
615 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
616 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
617 if (!newMd5.equals(oldMd5))
619 getLog().debug("Found new or modified mapping-file: " + filename);
621 md5s.put(filename, newMd5);
625 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
627 getLog().debug("Adding mappings from XML-configurationfile: " + file);
628 config.addFile(file);
631 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
634 catch (NoSuchAlgorithmException e)
636 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
638 catch (FileNotFoundException e)
640 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
642 catch (IOException e)
644 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
648 Target target = null;
651 target = Target.valueOf(this.target.toUpperCase());
653 catch (IllegalArgumentException e)
655 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
656 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
657 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
662 type = Type.valueOf(this.type.toUpperCase());
664 catch (IllegalArgumentException e)
666 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
667 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
668 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
671 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
673 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
677 && !target.equals(Target.SCRIPT)
678 && !target.equals(Target.NONE)
682 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
683 getLog().info("Skipping schema generation!");
684 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
688 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
689 for (Entry<Object,Object> entry : properties.entrySet())
690 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
692 Connection connection = null;
696 * The connection must be established outside of hibernate, because
697 * hibernate does not use the context-classloader of the current
698 * thread and, hence, would not be able to resolve the driver-class!
700 getLog().debug("Target: " + target + ", Type: " + type);
710 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
711 getLog().debug("Registering JDBC-driver " + driverClass.getName());
712 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
714 "Opening JDBC-connection to "
715 + properties.getProperty(URL)
717 + properties.getProperty(USERNAME)
719 + properties.getProperty(PASSWORD)
721 connection = DriverManager.getConnection(
722 properties.getProperty(URL),
723 properties.getProperty(USERNAME),
724 properties.getProperty(PASSWORD)
729 catch (ClassNotFoundException e)
731 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
732 throw new MojoExecutionException(e.getMessage());
736 getLog().error("Cannot establish connection to database!");
737 Enumeration<Driver> drivers = DriverManager.getDrivers();
738 if (!drivers.hasMoreElements())
739 getLog().error("No drivers registered!");
740 while (drivers.hasMoreElements())
741 getLog().debug("Driver: " + drivers.nextElement());
742 throw new MojoExecutionException(e.getMessage());
745 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
746 MavenLogAppender.startPluginLog(this);
750 * Change class-loader of current thread, so that hibernate can
751 * see all dependencies!
753 Thread.currentThread().setContextClassLoader(classLoader);
755 SchemaExport export = new SchemaExport(config, connection);
756 export.setOutputFile(outputFile);
757 export.setDelimiter(delimiter);
758 export.setFormat(format);
759 export.execute(target, type);
761 for (Object exception : export.getExceptions())
762 getLog().debug(exception.toString());
766 /** Stop Log-Capturing */
767 MavenLogAppender.endPluginLog(this);
769 /** Restore the old class-loader (TODO: is this really necessary?) */
770 Thread.currentThread().setContextClassLoader(contextClassLoader);
772 /** Close the connection */
775 if (connection != null)
778 catch (SQLException e)
780 getLog().error("Error while closing connection: " + e.getMessage());
784 /** Write md5-sums for annotated classes to file */
787 FileOutputStream fos = new FileOutputStream(saved);
788 ObjectOutputStream oos = new ObjectOutputStream(fos);
789 oos.writeObject(md5s);
795 getLog().error("Cannot write md5-sums to file: " + e);
800 * Needed, because DriverManager won't pick up drivers, that were not
801 * loaded by the system-classloader!
803 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
805 static final class DriverProxy implements Driver
807 private final Driver target;
809 DriverProxy(Driver target)
812 throw new NullPointerException();
813 this.target = target;
816 public java.sql.Driver getTarget()
822 public boolean acceptsURL(String url) throws SQLException
824 return target.acceptsURL(url);
828 public java.sql.Connection connect(
830 java.util.Properties info
835 return target.connect(url, info);
839 public int getMajorVersion()
841 return target.getMajorVersion();
845 public int getMinorVersion()
847 return target.getMinorVersion();
851 public DriverPropertyInfo[] getPropertyInfo(
858 return target.getPropertyInfo(url, info);
862 public boolean jdbcCompliant()
864 return target.jdbcCompliant();
868 * This Method cannot be annotated with @Override, becaus the plugin
869 * will not compile then under Java 1.6!
871 public Logger getParentLogger() throws SQLFeatureNotSupportedException
873 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
877 public String toString()
879 return "Proxy: " + target;
883 public int hashCode()
885 return target.hashCode();
889 public boolean equals(Object obj)
891 if (!(obj instanceof DriverProxy))
893 DriverProxy other = (DriverProxy) obj;
894 return this.target.equals(other.target);