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.tool.hbm2ddl.SchemaExport;
57 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
58 import org.hibernate.tool.hbm2ddl.Target;
59 import org.scannotation.AnnotationDB;
63 * Goal which extracts the hibernate-mapping-configuration and
64 * exports an according SQL-database-schema.
67 * @phase process-classes
69 * @requiresDependencyResolution runtime
71 public class Hbm2DdlMojo extends AbstractMojo
73 public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
75 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
76 public final static String URL = "hibernate.connection.url";
77 public final static String USERNAME = "hibernate.connection.username";
78 public final static String PASSWORD = "hibernate.connection.password";
79 public final static String DIALECT = "hibernate.dialect";
81 private final static String MD5S = "schema.md5s";
86 * Only needed internally.
88 * @parameter expression="${project}"
92 private MavenProject project;
97 * Only needed internally.
99 * @parameter expression="${project.build.directory}"
103 private String buildDirectory;
106 * Classes-Directory to scan.
108 * This parameter defaults to the maven build-output-directory for classes.
109 * Additonally, all dependencies are scanned for annotated classes.
111 * @parameter expression="${project.build.outputDirectory}"
113 private String outputDirectory;
116 * Wether to scan test-classes too, or not.
118 * If this parameter is set to <code>true</code> the test-classes of the
119 * artifact will be scanned for hibernate-annotated classes additionally.
121 * @parameter expression="${hibernate.export.scann_testclasses}" default-value="false"
123 private boolean scanTestClasses;
126 * Test-Classes-Directory to scan.
128 * This parameter defaults to the maven build-output-directory for
131 * This parameter is only used, when <code>scanTestClasses</code> is set
132 * to <code>true</code>!
134 * @parameter expression="${project.build.testOutputDirectory}"
136 private String testOutputDirectory;
141 * If set to <code>true</code>, the execution is skipped.
143 * A skipped excecution is signaled via the maven-property
144 * <code>${hibernate.export.skipped}</code>.
146 * The excecution is skipped automatically, if no modified or newly added
147 * annotated classes are found and the dialect was not changed.
149 * @parameter expression="${maven.test.skip}" default-value="false"
151 private boolean skip;
156 * Force execution, even if no modified or newly added annotated classes
157 * where found and the dialect was not changed.
159 * <code>skip</code> takes precedence over <code>force</code>.
161 * @parameter expression="${hibernate.export.force}" default-value="false"
163 private boolean force;
168 * @parameter expression="${hibernate.connection.driver_class}
170 private String driverClassName;
175 * @parameter expression="${hibernate.connection.url}"
182 * @parameter expression="${hibernate.connection.username}"
184 private String username;
189 * @parameter expression="${hibernate.connection.password}"
191 private String password;
196 * @parameter expression="${hibernate.dialect}"
198 private String hibernateDialect;
201 * Path to Hibernate configuration file.
203 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
205 private String hibernateProperties;
208 * Target of execution:
210 * <li><strong>NONE</strong> do nothing - just validate the configuration (forces excecution, signals skip)</li>
211 * <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>. forces excecution, signals skip)</li>
212 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
213 * <li><strong>BOTH</strong></li>
215 * @parameter expression="${hibernate.export.target}" default-value="EXPORT"
217 private String target;
222 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
223 * <li><strong>CREATE</strong> create database-schema</li>
224 * <li><strong>DROP</strong> drop database-schema</li>
225 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
227 * @parameter expression="${hibernate.export.type}" default-value="BOTH"
234 * @parameter expression="${hibernate.export.schema.filename}" default-value="${project.build.directory}/schema.sql"
236 private String outputFile;
239 * Delimiter in output-file.
241 * @parameter expression="${hibernate.export.schema.delimiter}" default-value=";"
243 private String delimiter;
246 * Format output-file.
248 * @parameter expression="${hibernate.export.schema.format}" default-value="true"
250 private boolean format;
254 public void execute()
256 MojoFailureException,
257 MojoExecutionException
261 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
262 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
266 File dir = new File(outputDirectory);
268 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
270 Map<String,String> md5s;
271 boolean modified = false;
272 File saved = new File(buildDirectory + File.separator + MD5S);
278 FileInputStream fis = new FileInputStream(saved);
279 ObjectInputStream ois = new ObjectInputStream(fis);
280 md5s = (HashMap<String,String>)ois.readObject();
285 md5s = new HashMap<String,String>();
286 getLog().warn("Cannot read timestamps from saved: " + e);
291 md5s = new HashMap<String,String>();
294 saved.createNewFile();
296 catch (IOException e)
298 getLog().warn("Cannot create saved for timestamps: " + e);
302 ClassLoader classLoader = null;
305 getLog().debug("Creating ClassLoader for project-dependencies...");
306 List<String> classpathFiles = project.getCompileClasspathElements();
308 classpathFiles.addAll(project.getTestClasspathElements());
309 URL[] urls = new URL[classpathFiles.size()];
310 for (int i = 0; i < classpathFiles.size(); ++i)
312 getLog().debug("Dependency: " + classpathFiles.get(i));
313 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
315 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
319 getLog().error("Error while creating ClassLoader!", e);
320 throw new MojoExecutionException(e.getMessage());
323 Set<Class<?>> classes =
324 new TreeSet<Class<?>>(
325 new Comparator<Class<?>>() {
327 public int compare(Class<?> a, Class<?> b)
329 return a.getName().compareTo(b.getName());
336 AnnotationDB db = new AnnotationDB();
337 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
338 URL dirUrl = dir.toURI().toURL();
339 db.scanArchives(dirUrl);
342 dir = new File(testOutputDirectory);
344 throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
345 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
346 dirUrl = dir.toURI().toURL();
347 db.scanArchives(dirUrl);
350 Set<String> classNames = new HashSet<String>();
351 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
352 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
353 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
354 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
355 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
356 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
358 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
359 for (String name : classNames)
361 Class<?> annotatedClass = classLoader.loadClass(name);
362 classes.add(annotatedClass);
365 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
366 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
368 while((i = is.read(buffer)) > -1)
369 digest.update(buffer, 0, i);
371 byte[] bytes = digest.digest();
372 BigInteger bi = new BigInteger(1, bytes);
373 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
374 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
375 if (!newMd5.equals(oldMd5))
377 getLog().debug("Found new or modified annotated class: " + name);
379 md5s.put(name, newMd5);
383 getLog().debug(oldMd5 + " -> class unchanged: " + name);
387 catch (ClassNotFoundException e)
389 getLog().error("Error while adding annotated classes!", e);
390 throw new MojoExecutionException(e.getMessage());
394 getLog().error("Error while scanning!", e);
395 throw new MojoFailureException(e.getMessage());
398 if (classes.isEmpty())
399 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
401 getLog().debug("Detected classes with mapping-annotations:");
402 for (Class<?> annotatedClass : classes)
403 getLog().debug(" " + annotatedClass.getName());
406 Properties properties = new Properties();
408 /** Try to read configuration from properties-file */
411 File file = new File(hibernateProperties);
414 getLog().info("Reading properties from file " + hibernateProperties + "...");
415 properties.load(new FileInputStream(file));
418 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
420 catch (IOException e)
422 getLog().error("Error while reading properties!", e);
423 throw new MojoExecutionException(e.getMessage());
426 /** Overwrite values from propertie-file or set, if given */
427 if (driverClassName != null)
429 if (properties.containsKey(DRIVER_CLASS))
431 "Overwriting property " +
432 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
433 " with the value " + driverClassName
436 getLog().debug("Using the value " + driverClassName);
437 properties.setProperty(DRIVER_CLASS, driverClassName);
441 if (properties.containsKey(URL))
443 "Overwriting property " +
444 URL + "=" + properties.getProperty(URL) +
445 " with the value " + url
448 getLog().debug("Using the value " + url);
449 properties.setProperty(URL, url);
451 if (username != null)
453 if (properties.containsKey(USERNAME))
455 "Overwriting property " +
456 USERNAME + "=" + properties.getProperty(USERNAME) +
457 " with the value " + username
460 getLog().debug("Using the value " + username);
461 properties.setProperty(USERNAME, username);
463 if (password != null)
465 if (properties.containsKey(PASSWORD))
467 "Overwriting property " +
468 PASSWORD + "=" + properties.getProperty(PASSWORD) +
469 " with the value " + password
472 getLog().debug("Using the value " + password);
473 properties.setProperty(PASSWORD, password);
475 if (hibernateDialect != null)
477 if (properties.containsKey(DIALECT))
479 "Overwriting property " +
480 DIALECT + "=" + properties.getProperty(DIALECT) +
481 " with the value " + hibernateDialect
484 getLog().debug("Using the value " + hibernateDialect);
485 properties.setProperty(DIALECT, hibernateDialect);
488 /** The generated SQL varies with the dialect! */
489 if (md5s.containsKey(DIALECT))
491 String dialect = properties.getProperty(DIALECT);
492 if (md5s.get(DIALECT).equals(dialect))
493 getLog().debug("SQL-dialect unchanged.");
496 getLog().debug("SQL-dialect changed: " + dialect);
498 md5s.put(DIALECT, dialect);
504 md5s.put(DIALECT, properties.getProperty(DIALECT));
507 if (properties.isEmpty())
509 getLog().error("No properties set!");
510 throw new MojoFailureException("Hibernate-Configuration is missing!");
513 Configuration config = new Configuration();
514 config.setProperties(properties);
515 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
516 for (Class<?> annotatedClass : classes)
518 getLog().debug("Class " + annotatedClass);
519 config.addAnnotatedClass(annotatedClass);
522 Target target = null;
525 target = Target.valueOf(this.target.toUpperCase());
527 catch (IllegalArgumentException e)
529 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
530 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
531 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
536 type = Type.valueOf(this.type.toUpperCase());
538 catch (IllegalArgumentException e)
540 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
541 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
542 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
545 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
547 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
551 && !target.equals(Target.SCRIPT)
552 && !target.equals(Target.NONE)
556 getLog().info("No modified annotated classes found and dialect unchanged.");
557 getLog().info("Skipping schema generation!");
558 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
562 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
563 for (Entry<Object,Object> entry : properties.entrySet())
564 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
566 Connection connection = null;
570 * The connection must be established outside of hibernate, because
571 * hibernate does not use the context-classloader of the current
572 * thread and, hence, would not be able to resolve the driver-class!
583 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
584 getLog().debug("Registering JDBC-driver " + driverClass.getName());
585 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
587 "Opening JDBC-connection to "
588 + properties.getProperty(URL)
590 + properties.getProperty(USERNAME)
592 + properties.getProperty(PASSWORD)
594 connection = DriverManager.getConnection(
595 properties.getProperty(URL),
596 properties.getProperty(USERNAME),
597 properties.getProperty(PASSWORD)
602 catch (ClassNotFoundException e)
604 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
605 throw new MojoExecutionException(e.getMessage());
609 getLog().error("Cannot establish connection to database!");
610 Enumeration<Driver> drivers = DriverManager.getDrivers();
611 if (!drivers.hasMoreElements())
612 getLog().error("No drivers registered!");
613 while (drivers.hasMoreElements())
614 getLog().debug("Driver: " + drivers.nextElement());
615 throw new MojoExecutionException(e.getMessage());
618 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
619 MavenLogAppender.startPluginLog(this);
623 * Change class-loader of current thread, so that hibernate can
624 * see all dependencies!
626 Thread.currentThread().setContextClassLoader(classLoader);
628 SchemaExport export = new SchemaExport(config, connection);
629 export.setOutputFile(outputFile);
630 export.setDelimiter(delimiter);
631 export.setFormat(format);
632 export.execute(target, type);
634 for (Object exception : export.getExceptions())
635 getLog().debug(exception.toString());
639 /** Stop Log-Capturing */
640 MavenLogAppender.endPluginLog(this);
642 /** Restore the old class-loader (TODO: is this really necessary?) */
643 Thread.currentThread().setContextClassLoader(contextClassLoader);
645 /** Close the connection */
648 if (connection != null)
651 catch (SQLException e)
653 getLog().error("Error while closing connection: " + e.getMessage());
657 /** Write md5-sums for annotated classes to file */
660 FileOutputStream fos = new FileOutputStream(saved);
661 ObjectOutputStream oos = new ObjectOutputStream(fos);
662 oos.writeObject(md5s);
668 getLog().error("Cannot write md5-sums to file: " + e);
673 * Needed, because DriverManager won't pick up drivers, that were not
674 * loaded by the system-classloader!
676 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
678 static final class DriverProxy implements Driver
680 private final Driver target;
682 DriverProxy(Driver target)
685 throw new NullPointerException();
686 this.target = target;
689 public java.sql.Driver getTarget()
695 public boolean acceptsURL(String url) throws SQLException
697 return target.acceptsURL(url);
701 public java.sql.Connection connect(
703 java.util.Properties info
708 return target.connect(url, info);
712 public int getMajorVersion()
714 return target.getMajorVersion();
718 public int getMinorVersion()
720 return target.getMinorVersion();
724 public DriverPropertyInfo[] getPropertyInfo(
731 return target.getPropertyInfo(url, info);
735 public boolean jdbcCompliant()
737 return target.jdbcCompliant();
741 * This Method cannot be annotated with @Override, becaus the plugin
742 * will not compile then under Java 1.6!
744 public Logger getParentLogger() throws SQLFeatureNotSupportedException
746 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
750 public String toString()
752 return "Proxy: " + target;
756 public int hashCode()
758 return target.hashCode();
762 public boolean equals(Object obj)
764 if (!(obj instanceof DriverProxy))
766 DriverProxy other = (DriverProxy) obj;
767 return this.target.equals(other.target);