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 * @parameter expression="${project}"
90 private MavenProject project;
95 * @parameter expression="${project.build.directory}"
97 private String buildDirectory;
100 * Class-directory to scan.
102 * @parameter expression="${project.build.outputDirectory}"
104 private String outputDirectory;
109 * @parameter expression="${maven.test.skip}" default-value="false"
111 private boolean skip;
116 * Force execution, even if no modified or newly added annotated classes
117 * where found. <code>skip</code> takes precedence over <code>force</code>.
119 * @parameter expression="${hibernate.export.force}" default-value="false"
121 private boolean force;
126 * @parameter expression="${hibernate.connection.driver_class}
128 private String driverClassName;
133 * @parameter expression="${hibernate.connection.url}"
140 * @parameter expression="${hibernate.connection.username}"
142 private String username;
147 * @parameter expression="${hibernate.connection.password}"
149 private String password;
154 * @parameter expression="${hibernate.dialect}"
156 private String hibernateDialect;
159 * Path to Hibernate configuration file.
161 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
163 private String hibernateProperties;
166 * Target of execution:
168 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
169 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
170 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
171 * <li><strong>BOTH</strong></li>
173 * @parameter expression="${hibernate.export.target}" default-value="EXPORT"
175 private String target;
180 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
181 * <li><strong>CREATE</strong> create database-schema</li>
182 * <li><strong>DROP</strong> drop database-schema</li>
183 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
185 * @parameter expression="${hibernate.export.type}" default-value="BOTH"
192 * @parameter expression="${hibernate.export.schema.filename}" default-value="${project.build.directory}/schema.sql"
194 private String outputFile;
197 * Delimiter in output-file.
199 * @parameter expression="${hibernate.export.schema.delimiter}" default-value=";"
201 private String delimiter;
204 * Format output-file.
206 * @parameter expression="${hibernate.export.schema.format}" default-value="true"
208 private boolean format;
212 public void execute()
214 MojoFailureException,
215 MojoExecutionException
219 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
220 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
224 File dir = new File(outputDirectory);
226 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
228 Map<String,String> md5s;
229 boolean modified = false;
230 File saved = new File(buildDirectory + File.separator + MD5S);
236 FileInputStream fis = new FileInputStream(saved);
237 ObjectInputStream ois = new ObjectInputStream(fis);
238 md5s = (HashMap<String,String>)ois.readObject();
243 md5s = new HashMap<String,String>();
244 getLog().warn("Cannot read timestamps from saved: " + e);
249 md5s = new HashMap<String,String>();
252 saved.createNewFile();
254 catch (IOException e)
256 getLog().warn("Cannot create saved for timestamps: " + e);
260 ClassLoader classLoader = null;
263 getLog().debug("Creating ClassLoader for project-dependencies...");
264 List<String> classpathFiles = project.getCompileClasspathElements();
265 URL[] urls = new URL[classpathFiles.size()];
266 for (int i = 0; i < classpathFiles.size(); ++i)
268 getLog().debug("Dependency: " + classpathFiles.get(i));
269 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
271 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
275 getLog().error("Error while creating ClassLoader!", e);
276 throw new MojoExecutionException(e.getMessage());
279 Set<Class<?>> classes =
280 new TreeSet<Class<?>>(
281 new Comparator<Class<?>>() {
283 public int compare(Class<?> a, Class<?> b)
285 return a.getName().compareTo(b.getName());
292 AnnotationDB db = new AnnotationDB();
293 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
294 URL dirUrl = dir.toURI().toURL();
295 db.scanArchives(dirUrl);
297 Set<String> classNames = new HashSet<String>();
298 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
299 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
300 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
301 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
302 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
303 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
305 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
306 for (String name : classNames)
308 Class<?> annotatedClass = classLoader.loadClass(name);
309 classes.add(annotatedClass);
312 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
313 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
315 while((i = is.read(buffer)) > -1)
316 digest.update(buffer, 0, i);
318 byte[] bytes = digest.digest();
319 BigInteger bi = new BigInteger(1, bytes);
320 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
321 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
322 if (!newMd5.equals(oldMd5))
324 getLog().debug("Found new or modified annotated class: " + name);
326 md5s.put(name, newMd5);
330 getLog().debug(oldMd5 + " -> class unchanged: " + name);
334 catch (ClassNotFoundException e)
336 getLog().error("Error while adding annotated classes!", e);
337 throw new MojoExecutionException(e.getMessage());
341 getLog().error("Error while scanning!", e);
342 throw new MojoFailureException(e.getMessage());
345 if (classes.isEmpty())
346 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
348 getLog().debug("Detected classes with mapping-annotations:");
349 for (Class<?> annotatedClass : classes)
350 getLog().debug(" " + annotatedClass.getName());
353 Properties properties = new Properties();
355 /** Try to read configuration from properties-file */
358 File file = new File(hibernateProperties);
361 getLog().info("Reading properties from file " + hibernateProperties + "...");
362 properties.load(new FileInputStream(file));
365 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
367 catch (IOException e)
369 getLog().error("Error while reading properties!", e);
370 throw new MojoExecutionException(e.getMessage());
373 /** Overwrite values from propertie-file or set, if given */
374 if (driverClassName != null)
376 if (properties.containsKey(DRIVER_CLASS))
378 "Overwriting property " +
379 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
380 " with the value " + driverClassName
383 getLog().debug("Using the value " + driverClassName);
384 properties.setProperty(DRIVER_CLASS, driverClassName);
388 if (properties.containsKey(URL))
390 "Overwriting property " +
391 URL + "=" + properties.getProperty(URL) +
392 " with the value " + url
395 getLog().debug("Using the value " + url);
396 properties.setProperty(URL, url);
398 if (username != null)
400 if (properties.containsKey(USERNAME))
402 "Overwriting property " +
403 USERNAME + "=" + properties.getProperty(USERNAME) +
404 " with the value " + username
407 getLog().debug("Using the value " + username);
408 properties.setProperty(USERNAME, username);
410 if (password != null)
412 if (properties.containsKey(PASSWORD))
414 "Overwriting property " +
415 PASSWORD + "=" + properties.getProperty(PASSWORD) +
416 " with the value " + password
419 getLog().debug("Using the value " + password);
420 properties.setProperty(PASSWORD, password);
422 if (hibernateDialect != null)
424 if (properties.containsKey(DIALECT))
426 "Overwriting property " +
427 DIALECT + "=" + properties.getProperty(DIALECT) +
428 " with the value " + hibernateDialect
431 getLog().debug("Using the value " + hibernateDialect);
432 properties.setProperty(DIALECT, hibernateDialect);
435 /** The generated SQL varies with the dialect! */
436 if (md5s.containsKey(DIALECT))
438 String dialect = properties.getProperty(DIALECT);
439 if (md5s.get(DIALECT).equals(dialect))
440 getLog().debug("SQL-dialect unchanged.");
443 getLog().debug("SQL-dialect changed: " + dialect);
445 md5s.put(DIALECT, dialect);
451 md5s.put(DIALECT, properties.getProperty(DIALECT));
454 if (properties.isEmpty())
456 getLog().error("No properties set!");
457 throw new MojoFailureException("Hibernate-Configuration is missing!");
460 Configuration config = new Configuration();
461 config.setProperties(properties);
462 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
463 for (Class<?> annotatedClass : classes)
465 getLog().debug("Class " + annotatedClass);
466 config.addAnnotatedClass(annotatedClass);
469 Target target = null;
472 target = Target.valueOf(this.target.toUpperCase());
474 catch (IllegalArgumentException e)
476 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
477 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
478 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
483 type = Type.valueOf(this.type.toUpperCase());
485 catch (IllegalArgumentException e)
487 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
488 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
489 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
492 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
494 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
498 && !target.equals(Target.SCRIPT)
499 && !target.equals(Target.NONE)
503 getLog().info("No modified annotated classes found and dialect unchanged.");
504 getLog().info("Skipping schema generation!");
505 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
509 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
510 for (Entry<Object,Object> entry : properties.entrySet())
511 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
513 Connection connection = null;
517 * The connection must be established outside of hibernate, because
518 * hibernate does not use the context-classloader of the current
519 * thread and, hence, would not be able to resolve the driver-class!
530 Class driverClass = classLoader.loadClass(driverClassName);
531 getLog().debug("Registering JDBC-driver " + driverClass.getName());
532 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
533 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
534 connection = DriverManager.getConnection(url, username, password);
538 catch (ClassNotFoundException e)
540 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
541 throw new MojoExecutionException(e.getMessage());
545 getLog().error("Cannot establish connection to database!");
546 Enumeration<Driver> drivers = DriverManager.getDrivers();
547 if (!drivers.hasMoreElements())
548 getLog().error("No drivers registered!");
549 while (drivers.hasMoreElements())
550 getLog().debug("Driver: " + drivers.nextElement());
551 throw new MojoExecutionException(e.getMessage());
554 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
555 MavenLogAppender.startPluginLog(this);
559 * Change class-loader of current thread, so that hibernate can
560 * see all dependencies!
562 Thread.currentThread().setContextClassLoader(classLoader);
564 SchemaExport export = new SchemaExport(config, connection);
565 export.setOutputFile(outputFile);
566 export.setDelimiter(delimiter);
567 export.setFormat(format);
568 export.execute(target, type);
570 for (Object exception : export.getExceptions())
571 getLog().debug(exception.toString());
575 /** Stop Log-Capturing */
576 MavenLogAppender.endPluginLog(this);
578 /** Restore the old class-loader (TODO: is this really necessary?) */
579 Thread.currentThread().setContextClassLoader(contextClassLoader);
581 /** Close the connection */
584 if (connection != null)
587 catch (SQLException e)
589 getLog().error("Error while closing connection: " + e.getMessage());
593 /** Write md5-sums for annotated classes to file */
596 FileOutputStream fos = new FileOutputStream(saved);
597 ObjectOutputStream oos = new ObjectOutputStream(fos);
598 oos.writeObject(md5s);
604 getLog().error("Cannot write md5-sums to file: " + e);
609 * Needed, because DriverManager won't pick up drivers, that were not
610 * loaded by the system-classloader!
612 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
614 static final class DriverProxy implements Driver
616 private final Driver target;
618 DriverProxy(Driver target)
621 throw new NullPointerException();
622 this.target = target;
625 public java.sql.Driver getTarget()
631 public boolean acceptsURL(String url) throws SQLException
633 return target.acceptsURL(url);
637 public java.sql.Connection connect(
639 java.util.Properties info
644 return target.connect(url, info);
648 public int getMajorVersion()
650 return target.getMajorVersion();
654 public int getMinorVersion()
656 return target.getMinorVersion();
660 public DriverPropertyInfo[] getPropertyInfo(
667 return target.getPropertyInfo(url, info);
671 public boolean jdbcCompliant()
673 return target.jdbcCompliant();
677 * This Method cannot be annotated with @Override, becaus the plugin
678 * will not compile then under Java 1.6!
680 public Logger getParentLogger() throws SQLFeatureNotSupportedException
682 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
686 public String toString()
688 return "Proxy: " + target;
692 public int hashCode()
694 return target.hashCode();
698 public boolean equals(Object obj)
700 if (!(obj instanceof DriverProxy))
702 DriverProxy other = (DriverProxy) obj;
703 return this.target.equals(other.target);