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 File dir = new File(outputDirectory);
294 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
296 Map<String,String> md5s;
297 boolean modified = false;
298 File saved = new File(buildDirectory + File.separator + MD5S);
304 FileInputStream fis = new FileInputStream(saved);
305 ObjectInputStream ois = new ObjectInputStream(fis);
306 md5s = (HashMap<String,String>)ois.readObject();
311 md5s = new HashMap<String,String>();
312 getLog().warn("Cannot read timestamps from saved: " + e);
317 md5s = new HashMap<String,String>();
320 saved.createNewFile();
322 catch (IOException e)
324 getLog().warn("Cannot create saved for timestamps: " + e);
328 ClassLoader classLoader = null;
331 getLog().debug("Creating ClassLoader for project-dependencies...");
332 List<String> classpathFiles = project.getCompileClasspathElements();
334 classpathFiles.addAll(project.getTestClasspathElements());
335 URL[] urls = new URL[classpathFiles.size()];
336 for (int i = 0; i < classpathFiles.size(); ++i)
338 getLog().debug("Dependency: " + classpathFiles.get(i));
339 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
341 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
345 getLog().error("Error while creating ClassLoader!", e);
346 throw new MojoExecutionException(e.getMessage());
349 Set<Class<?>> classes =
350 new TreeSet<Class<?>>(
351 new Comparator<Class<?>>() {
353 public int compare(Class<?> a, Class<?> b)
355 return a.getName().compareTo(b.getName());
362 AnnotationDB db = new AnnotationDB();
363 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
364 URL dirUrl = dir.toURI().toURL();
365 db.scanArchives(dirUrl);
368 dir = new File(testOutputDirectory);
370 throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
371 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
372 dirUrl = dir.toURI().toURL();
373 db.scanArchives(dirUrl);
376 Set<String> classNames = new HashSet<String>();
377 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
378 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
379 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
380 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
381 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
382 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
384 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
385 for (String name : classNames)
387 Class<?> annotatedClass = classLoader.loadClass(name);
388 classes.add(annotatedClass);
391 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
392 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
394 while((i = is.read(buffer)) > -1)
395 digest.update(buffer, 0, i);
397 byte[] bytes = digest.digest();
398 BigInteger bi = new BigInteger(1, bytes);
399 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
400 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
401 if (!newMd5.equals(oldMd5))
403 getLog().debug("Found new or modified annotated class: " + name);
405 md5s.put(name, newMd5);
409 getLog().debug(oldMd5 + " -> class unchanged: " + name);
413 catch (ClassNotFoundException e)
415 getLog().error("Error while adding annotated classes!", e);
416 throw new MojoExecutionException(e.getMessage());
420 getLog().error("Error while scanning!", e);
421 throw new MojoFailureException(e.getMessage());
424 if (classes.isEmpty())
426 if (hibernateMapping == null || hibernateMapping.isEmpty())
427 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
431 getLog().debug("Detected classes with mapping-annotations:");
432 for (Class<?> annotatedClass : classes)
433 getLog().debug(" " + annotatedClass.getName());
437 Properties properties = new Properties();
439 /** Try to read configuration from properties-file */
442 File file = new File(hibernateProperties);
445 getLog().info("Reading properties from file " + hibernateProperties + "...");
446 properties.load(new FileInputStream(file));
449 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
451 catch (IOException e)
453 getLog().error("Error while reading properties!", e);
454 throw new MojoExecutionException(e.getMessage());
457 /** Overwrite values from propertie-file or set, if given */
458 if (driverClassName != null)
460 if (properties.containsKey(DRIVER_CLASS))
462 "Overwriting property " +
463 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
464 " with the value " + driverClassName
467 getLog().debug("Using the value " + driverClassName);
468 properties.setProperty(DRIVER_CLASS, driverClassName);
472 if (properties.containsKey(URL))
474 "Overwriting property " +
475 URL + "=" + properties.getProperty(URL) +
476 " with the value " + url
479 getLog().debug("Using the value " + url);
480 properties.setProperty(URL, url);
482 if (username != null)
484 if (properties.containsKey(USERNAME))
486 "Overwriting property " +
487 USERNAME + "=" + properties.getProperty(USERNAME) +
488 " with the value " + username
491 getLog().debug("Using the value " + username);
492 properties.setProperty(USERNAME, username);
494 if (password != null)
496 if (properties.containsKey(PASSWORD))
498 "Overwriting property " +
499 PASSWORD + "=" + properties.getProperty(PASSWORD) +
500 " with the value " + password
503 getLog().debug("Using the value " + password);
504 properties.setProperty(PASSWORD, password);
506 if (hibernateDialect != null)
508 if (properties.containsKey(DIALECT))
510 "Overwriting property " +
511 DIALECT + "=" + properties.getProperty(DIALECT) +
512 " with the value " + hibernateDialect
515 getLog().debug("Using the value " + hibernateDialect);
516 properties.setProperty(DIALECT, hibernateDialect);
518 if ( hibernateNamingStrategy != null )
520 if ( properties.contains(NAMING_STRATEGY))
522 "Overwriting property " +
523 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
524 " with the value " + hibernateNamingStrategy
527 getLog().debug("Using the value " + hibernateNamingStrategy);
528 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
531 /** The generated SQL varies with the dialect! */
532 if (md5s.containsKey(DIALECT))
534 String dialect = properties.getProperty(DIALECT);
535 if (md5s.get(DIALECT).equals(dialect))
536 getLog().debug("SQL-dialect unchanged.");
539 getLog().debug("SQL-dialect changed: " + dialect);
541 md5s.put(DIALECT, dialect);
547 md5s.put(DIALECT, properties.getProperty(DIALECT));
550 if (properties.isEmpty())
552 getLog().error("No properties set!");
553 throw new MojoFailureException("Hibernate-Configuration is missing!");
556 Configuration config = new Configuration();
557 config.setProperties(properties);
559 if ( properties.containsKey(NAMING_STRATEGY))
561 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
562 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
565 @SuppressWarnings("unchecked")
566 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
567 config.setNamingStrategy(namingStrategyClass.newInstance());
571 getLog().error("Error setting NamingStrategy", e);
572 throw new MojoExecutionException(e.getMessage());
576 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
577 for (Class<?> annotatedClass : classes)
579 getLog().debug("Class " + annotatedClass);
580 config.addAnnotatedClass(annotatedClass);
583 if (hibernateMapping != null)
587 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
588 for (String filename : hibernateMapping.split("[\\s,]+"))
590 // First try the filename as absolute/relative path
591 File file = new File(filename);
594 // If the file was not found, search for it in the resource-directories
595 for (Resource resource : project.getResources())
597 file = new File(resource.getDirectory() + File.separator + filename);
602 if (file != null && file.exists())
604 InputStream is = new FileInputStream(file);
605 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
607 while((i = is.read(buffer)) > -1)
608 digest.update(buffer, 0, i);
610 byte[] bytes = digest.digest();
611 BigInteger bi = new BigInteger(1, bytes);
612 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
613 String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
614 if (!newMd5.equals(oldMd5))
616 getLog().debug("Found new or modified mapping-file: " + filename);
618 md5s.put(filename, newMd5);
622 getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
624 getLog().debug("Adding mappings from XML-configurationfile: " + file);
625 config.addFile(file);
628 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
631 catch (NoSuchAlgorithmException e)
633 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
635 catch (FileNotFoundException e)
637 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
639 catch (IOException e)
641 throw new MojoFailureException("Cannot calculate MD5-summs!", e);
645 Target target = null;
648 target = Target.valueOf(this.target.toUpperCase());
650 catch (IllegalArgumentException e)
652 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
653 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
654 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
659 type = Type.valueOf(this.type.toUpperCase());
661 catch (IllegalArgumentException e)
663 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
664 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
665 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
668 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
670 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
674 && !target.equals(Target.SCRIPT)
675 && !target.equals(Target.NONE)
679 getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
680 getLog().info("Skipping schema generation!");
681 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
685 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
686 for (Entry<Object,Object> entry : properties.entrySet())
687 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
689 Connection connection = null;
693 * The connection must be established outside of hibernate, because
694 * hibernate does not use the context-classloader of the current
695 * thread and, hence, would not be able to resolve the driver-class!
697 getLog().debug("Target: " + target + ", Type: " + type);
707 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
708 getLog().debug("Registering JDBC-driver " + driverClass.getName());
709 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
711 "Opening JDBC-connection to "
712 + properties.getProperty(URL)
714 + properties.getProperty(USERNAME)
716 + properties.getProperty(PASSWORD)
718 connection = DriverManager.getConnection(
719 properties.getProperty(URL),
720 properties.getProperty(USERNAME),
721 properties.getProperty(PASSWORD)
726 catch (ClassNotFoundException e)
728 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
729 throw new MojoExecutionException(e.getMessage());
733 getLog().error("Cannot establish connection to database!");
734 Enumeration<Driver> drivers = DriverManager.getDrivers();
735 if (!drivers.hasMoreElements())
736 getLog().error("No drivers registered!");
737 while (drivers.hasMoreElements())
738 getLog().debug("Driver: " + drivers.nextElement());
739 throw new MojoExecutionException(e.getMessage());
742 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
743 MavenLogAppender.startPluginLog(this);
747 * Change class-loader of current thread, so that hibernate can
748 * see all dependencies!
750 Thread.currentThread().setContextClassLoader(classLoader);
752 SchemaExport export = new SchemaExport(config, connection);
753 export.setOutputFile(outputFile);
754 export.setDelimiter(delimiter);
755 export.setFormat(format);
756 export.execute(target, type);
758 for (Object exception : export.getExceptions())
759 getLog().debug(exception.toString());
763 /** Stop Log-Capturing */
764 MavenLogAppender.endPluginLog(this);
766 /** Restore the old class-loader (TODO: is this really necessary?) */
767 Thread.currentThread().setContextClassLoader(contextClassLoader);
769 /** Close the connection */
772 if (connection != null)
775 catch (SQLException e)
777 getLog().error("Error while closing connection: " + e.getMessage());
781 /** Write md5-sums for annotated classes to file */
784 FileOutputStream fos = new FileOutputStream(saved);
785 ObjectOutputStream oos = new ObjectOutputStream(fos);
786 oos.writeObject(md5s);
792 getLog().error("Cannot write md5-sums to file: " + e);
797 * Needed, because DriverManager won't pick up drivers, that were not
798 * loaded by the system-classloader!
800 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
802 static final class DriverProxy implements Driver
804 private final Driver target;
806 DriverProxy(Driver target)
809 throw new NullPointerException();
810 this.target = target;
813 public java.sql.Driver getTarget()
819 public boolean acceptsURL(String url) throws SQLException
821 return target.acceptsURL(url);
825 public java.sql.Connection connect(
827 java.util.Properties info
832 return target.connect(url, info);
836 public int getMajorVersion()
838 return target.getMajorVersion();
842 public int getMinorVersion()
844 return target.getMinorVersion();
848 public DriverPropertyInfo[] getPropertyInfo(
855 return target.getPropertyInfo(url, info);
859 public boolean jdbcCompliant()
861 return target.jdbcCompliant();
865 * This Method cannot be annotated with @Override, becaus the plugin
866 * will not compile then under Java 1.6!
868 public Logger getParentLogger() throws SQLFeatureNotSupportedException
870 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
874 public String toString()
876 return "Proxy: " + target;
880 public int hashCode()
882 return target.hashCode();
886 public boolean equals(Object obj)
888 if (!(obj instanceof DriverProxy))
890 DriverProxy other = (DriverProxy) obj;
891 return this.target.equals(other.target);