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.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.math.BigInteger;
29 import java.net.URLClassLoader;
30 import java.security.MessageDigest;
31 import java.sql.Connection;
32 import java.sql.Driver;
33 import java.sql.DriverManager;
34 import java.sql.DriverPropertyInfo;
35 import java.sql.SQLException;
36 import java.sql.SQLFeatureNotSupportedException;
37 import java.util.Comparator;
38 import java.util.Enumeration;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Properties;
46 import java.util.TreeSet;
47 import java.util.logging.Logger;
48 import javax.persistence.Embeddable;
49 import javax.persistence.Entity;
50 import javax.persistence.MappedSuperclass;
51 import org.apache.maven.plugin.AbstractMojo;
52 import org.apache.maven.plugin.MojoExecutionException;
53 import org.apache.maven.plugin.MojoFailureException;
54 import org.apache.maven.project.MavenProject;
55 import org.hibernate.cfg.Configuration;
56 import org.hibernate.cfg.NamingStrategy;
57 import org.hibernate.tool.hbm2ddl.SchemaExport;
58 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
59 import org.hibernate.tool.hbm2ddl.Target;
60 import org.scannotation.AnnotationDB;
64 * Goal which extracts the hibernate-mapping-configuration and
65 * exports an according SQL-database-schema.
68 * @phase process-classes
70 * @requiresDependencyResolution runtime
72 public class Hbm2DdlMojo extends AbstractMojo
74 public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
76 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
77 public final static String URL = "hibernate.connection.url";
78 public final static String USERNAME = "hibernate.connection.username";
79 public final static String PASSWORD = "hibernate.connection.password";
80 public final static String DIALECT = "hibernate.dialect";
81 public final static String NAMING_STRATEGY="hibernate.ejb.naming_strategy";
83 private final static String MD5S = "schema.md5s";
88 * Only needed internally.
90 * @parameter property="project"
94 private MavenProject project;
99 * Only needed internally.
101 * @parameter property="project.build.directory"
105 private String buildDirectory;
108 * Classes-Directory to scan.
110 * This parameter defaults to the maven build-output-directory for classes.
111 * Additonally, all dependencies are scanned for annotated classes.
113 * @parameter property="project.build.outputDirectory"
115 private String outputDirectory;
118 * Wether to scan test-classes too, or not.
120 * If this parameter is set to <code>true</code> the test-classes of the
121 * artifact will be scanned for hibernate-annotated classes additionally.
123 * @parameter property="hibernate.export.scan_testclasses" default-value="false"
125 private boolean scanTestClasses;
128 * Test-Classes-Directory to scan.
130 * This parameter defaults to the maven build-output-directory for
133 * This parameter is only used, when <code>scanTestClasses</code> is set
134 * to <code>true</code>!
136 * @parameter property="project.build.testOutputDirectory"
138 private String testOutputDirectory;
143 * If set to <code>true</code>, the execution is skipped.
145 * A skipped excecution is signaled via the maven-property
146 * <code>${hibernate.export.skipped}</code>.
148 * The excecution is skipped automatically, if no modified or newly added
149 * annotated classes are found and the dialect was not changed.
151 * @parameter property="maven.test.skip" default-value="false"
153 private boolean skip;
158 * Force execution, even if no modified or newly added annotated classes
159 * where found and the dialect was not changed.
161 * <code>skip</code> takes precedence over <code>force</code>.
163 * @parameter property="hibernate.export.force" default-value="false"
165 private boolean force;
170 * @parameter property="hibernate.connection.driver_class"
172 private String driverClassName;
177 * @parameter property="hibernate.connection.url"
184 * @parameter property="hibernate.connection.username"
186 private String username;
191 * @parameter property="hibernate.connection.password"
193 private String password;
198 * @parameter property="hibernate.dialect"
200 private String hibernateDialect;
203 * Hibernate Naming Strategy
204 * @parameter property="hibernate.ejb.naming_strategy"
207 private String hibernateNamingStrategy;
210 * Path to Hibernate configuration file.
212 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
214 private String hibernateProperties;
217 * Target of execution:
219 * <li><strong>NONE</strong> do nothing - just validate the configuration (forces excecution, signals skip)</li>
220 * <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>. forces excecution, signals skip)</li>
221 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
222 * <li><strong>BOTH</strong></li>
225 * @parameter property="hibernate.export.target" default-value="EXPORT"
227 private String target;
232 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
233 * <li><strong>CREATE</strong> create database-schema</li>
234 * <li><strong>DROP</strong> drop database-schema</li>
235 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
238 * @parameter property="hibernate.export.type" default-value="BOTH"
245 * @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
247 private String outputFile;
250 * Delimiter in output-file.
252 * @parameter property="hibernate.export.schema.delimiter" default-value=";"
254 private String delimiter;
257 * Format output-file.
259 * @parameter property="hibernate.export.schema.format" default-value="true"
261 private boolean format;
265 public void execute()
267 MojoFailureException,
268 MojoExecutionException
272 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
273 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
277 File dir = new File(outputDirectory);
279 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
281 Map<String,String> md5s;
282 boolean modified = false;
283 File saved = new File(buildDirectory + File.separator + MD5S);
289 FileInputStream fis = new FileInputStream(saved);
290 ObjectInputStream ois = new ObjectInputStream(fis);
291 md5s = (HashMap<String,String>)ois.readObject();
296 md5s = new HashMap<String,String>();
297 getLog().warn("Cannot read timestamps from saved: " + e);
302 md5s = new HashMap<String,String>();
305 saved.createNewFile();
307 catch (IOException e)
309 getLog().warn("Cannot create saved for timestamps: " + e);
313 ClassLoader classLoader = null;
316 getLog().debug("Creating ClassLoader for project-dependencies...");
317 List<String> classpathFiles = project.getCompileClasspathElements();
319 classpathFiles.addAll(project.getTestClasspathElements());
320 URL[] urls = new URL[classpathFiles.size()];
321 for (int i = 0; i < classpathFiles.size(); ++i)
323 getLog().debug("Dependency: " + classpathFiles.get(i));
324 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
326 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
330 getLog().error("Error while creating ClassLoader!", e);
331 throw new MojoExecutionException(e.getMessage());
334 Set<Class<?>> classes =
335 new TreeSet<Class<?>>(
336 new Comparator<Class<?>>() {
338 public int compare(Class<?> a, Class<?> b)
340 return a.getName().compareTo(b.getName());
347 AnnotationDB db = new AnnotationDB();
348 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
349 URL dirUrl = dir.toURI().toURL();
350 db.scanArchives(dirUrl);
353 dir = new File(testOutputDirectory);
355 throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
356 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
357 dirUrl = dir.toURI().toURL();
358 db.scanArchives(dirUrl);
361 Set<String> classNames = new HashSet<String>();
362 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
363 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
364 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
365 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
366 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
367 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
369 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
370 for (String name : classNames)
372 Class<?> annotatedClass = classLoader.loadClass(name);
373 classes.add(annotatedClass);
376 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
377 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
379 while((i = is.read(buffer)) > -1)
380 digest.update(buffer, 0, i);
382 byte[] bytes = digest.digest();
383 BigInteger bi = new BigInteger(1, bytes);
384 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
385 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
386 if (!newMd5.equals(oldMd5))
388 getLog().debug("Found new or modified annotated class: " + name);
390 md5s.put(name, newMd5);
394 getLog().debug(oldMd5 + " -> class unchanged: " + name);
398 catch (ClassNotFoundException e)
400 getLog().error("Error while adding annotated classes!", e);
401 throw new MojoExecutionException(e.getMessage());
405 getLog().error("Error while scanning!", e);
406 throw new MojoFailureException(e.getMessage());
409 if (classes.isEmpty())
410 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
412 getLog().debug("Detected classes with mapping-annotations:");
413 for (Class<?> annotatedClass : classes)
414 getLog().debug(" " + annotatedClass.getName());
417 Properties properties = new Properties();
419 /** Try to read configuration from properties-file */
422 File file = new File(hibernateProperties);
425 getLog().info("Reading properties from file " + hibernateProperties + "...");
426 properties.load(new FileInputStream(file));
429 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
431 catch (IOException e)
433 getLog().error("Error while reading properties!", e);
434 throw new MojoExecutionException(e.getMessage());
437 /** Overwrite values from propertie-file or set, if given */
438 if (driverClassName != null)
440 if (properties.containsKey(DRIVER_CLASS))
442 "Overwriting property " +
443 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
444 " with the value " + driverClassName
447 getLog().debug("Using the value " + driverClassName);
448 properties.setProperty(DRIVER_CLASS, driverClassName);
452 if (properties.containsKey(URL))
454 "Overwriting property " +
455 URL + "=" + properties.getProperty(URL) +
456 " with the value " + url
459 getLog().debug("Using the value " + url);
460 properties.setProperty(URL, url);
462 if (username != null)
464 if (properties.containsKey(USERNAME))
466 "Overwriting property " +
467 USERNAME + "=" + properties.getProperty(USERNAME) +
468 " with the value " + username
471 getLog().debug("Using the value " + username);
472 properties.setProperty(USERNAME, username);
474 if (password != null)
476 if (properties.containsKey(PASSWORD))
478 "Overwriting property " +
479 PASSWORD + "=" + properties.getProperty(PASSWORD) +
480 " with the value " + password
483 getLog().debug("Using the value " + password);
484 properties.setProperty(PASSWORD, password);
486 if (hibernateDialect != null)
488 if (properties.containsKey(DIALECT))
490 "Overwriting property " +
491 DIALECT + "=" + properties.getProperty(DIALECT) +
492 " with the value " + hibernateDialect
495 getLog().debug("Using the value " + hibernateDialect);
496 properties.setProperty(DIALECT, hibernateDialect);
498 if ( hibernateNamingStrategy != null )
500 if ( properties.contains(NAMING_STRATEGY))
502 "Overwriting property " +
503 NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
504 " with the value " + hibernateNamingStrategy
507 getLog().debug("Using the value " + hibernateNamingStrategy);
508 properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
511 /** The generated SQL varies with the dialect! */
512 if (md5s.containsKey(DIALECT))
514 String dialect = properties.getProperty(DIALECT);
515 if (md5s.get(DIALECT).equals(dialect))
516 getLog().debug("SQL-dialect unchanged.");
519 getLog().debug("SQL-dialect changed: " + dialect);
521 md5s.put(DIALECT, dialect);
527 md5s.put(DIALECT, properties.getProperty(DIALECT));
530 if (properties.isEmpty())
532 getLog().error("No properties set!");
533 throw new MojoFailureException("Hibernate-Configuration is missing!");
536 Configuration config = new Configuration();
537 config.setProperties(properties);
539 if ( properties.containsKey(NAMING_STRATEGY))
541 String namingStrategy = properties.getProperty(NAMING_STRATEGY);
542 getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
545 @SuppressWarnings("unchecked")
546 Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
547 config.setNamingStrategy(namingStrategyClass.newInstance());
551 getLog().error("Error setting NamingStrategy", e);
552 throw new MojoExecutionException(e.getMessage());
556 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
557 for (Class<?> annotatedClass : classes)
559 getLog().debug("Class " + annotatedClass);
560 config.addAnnotatedClass(annotatedClass);
563 Target target = null;
566 target = Target.valueOf(this.target.toUpperCase());
568 catch (IllegalArgumentException e)
570 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
571 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
572 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
577 type = Type.valueOf(this.type.toUpperCase());
579 catch (IllegalArgumentException e)
581 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
582 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
583 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
586 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
588 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
592 && !target.equals(Target.SCRIPT)
593 && !target.equals(Target.NONE)
597 getLog().info("No modified annotated classes found and dialect unchanged.");
598 getLog().info("Skipping schema generation!");
599 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
603 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
604 for (Entry<Object,Object> entry : properties.entrySet())
605 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
607 Connection connection = null;
611 * The connection must be established outside of hibernate, because
612 * hibernate does not use the context-classloader of the current
613 * thread and, hence, would not be able to resolve the driver-class!
624 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
625 getLog().debug("Registering JDBC-driver " + driverClass.getName());
626 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
628 "Opening JDBC-connection to "
629 + properties.getProperty(URL)
631 + properties.getProperty(USERNAME)
633 + properties.getProperty(PASSWORD)
635 connection = DriverManager.getConnection(
636 properties.getProperty(URL),
637 properties.getProperty(USERNAME),
638 properties.getProperty(PASSWORD)
643 catch (ClassNotFoundException e)
645 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
646 throw new MojoExecutionException(e.getMessage());
650 getLog().error("Cannot establish connection to database!");
651 Enumeration<Driver> drivers = DriverManager.getDrivers();
652 if (!drivers.hasMoreElements())
653 getLog().error("No drivers registered!");
654 while (drivers.hasMoreElements())
655 getLog().debug("Driver: " + drivers.nextElement());
656 throw new MojoExecutionException(e.getMessage());
659 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
660 MavenLogAppender.startPluginLog(this);
664 * Change class-loader of current thread, so that hibernate can
665 * see all dependencies!
667 Thread.currentThread().setContextClassLoader(classLoader);
669 SchemaExport export = new SchemaExport(config, connection);
670 export.setOutputFile(outputFile);
671 export.setDelimiter(delimiter);
672 export.setFormat(format);
673 export.execute(target, type);
675 for (Object exception : export.getExceptions())
676 getLog().debug(exception.toString());
680 /** Stop Log-Capturing */
681 MavenLogAppender.endPluginLog(this);
683 /** Restore the old class-loader (TODO: is this really necessary?) */
684 Thread.currentThread().setContextClassLoader(contextClassLoader);
686 /** Close the connection */
689 if (connection != null)
692 catch (SQLException e)
694 getLog().error("Error while closing connection: " + e.getMessage());
698 /** Write md5-sums for annotated classes to file */
701 FileOutputStream fos = new FileOutputStream(saved);
702 ObjectOutputStream oos = new ObjectOutputStream(fos);
703 oos.writeObject(md5s);
709 getLog().error("Cannot write md5-sums to file: " + e);
714 * Needed, because DriverManager won't pick up drivers, that were not
715 * loaded by the system-classloader!
717 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
719 static final class DriverProxy implements Driver
721 private final Driver target;
723 DriverProxy(Driver target)
726 throw new NullPointerException();
727 this.target = target;
730 public java.sql.Driver getTarget()
736 public boolean acceptsURL(String url) throws SQLException
738 return target.acceptsURL(url);
742 public java.sql.Connection connect(
744 java.util.Properties info
749 return target.connect(url, info);
753 public int getMajorVersion()
755 return target.getMajorVersion();
759 public int getMinorVersion()
761 return target.getMinorVersion();
765 public DriverPropertyInfo[] getPropertyInfo(
772 return target.getPropertyInfo(url, info);
776 public boolean jdbcCompliant()
778 return target.jdbcCompliant();
782 * This Method cannot be annotated with @Override, becaus the plugin
783 * will not compile then under Java 1.6!
785 public Logger getParentLogger() throws SQLFeatureNotSupportedException
787 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
791 public String toString()
793 return "Proxy: " + target;
797 public int hashCode()
799 return target.hashCode();
803 public boolean equals(Object obj)
805 if (!(obj instanceof DriverProxy))
807 DriverProxy other = (DriverProxy) obj;
808 return this.target.equals(other.target);