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 * @parameter expression="${hibernate.connection.driver_class}
118 private String driverClassName;
123 * @parameter expression="${hibernate.connection.url}"
130 * @parameter expression="${hibernate.connection.username}"
132 private String username;
137 * @parameter expression="${hibernate.connection.password}"
139 private String password;
144 * @parameter expression="${hibernate.dialect}"
146 private String hibernateDialect;
149 * Path to Hibernate configuration file.
151 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
153 private String hibernateProperties;
156 * Target of execution:
158 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
159 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
160 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
161 * <li><strong>BOTH</strong></li>
163 * @parameter expression="${hibernate.export.target}" default-value="EXPORT"
165 private String target;
170 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
171 * <li><strong>CREATE</strong> create database-schema</li>
172 * <li><strong>DROP</strong> drop database-schema</li>
173 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
175 * @parameter expression="${hibernate.export.type}" default-value="BOTH"
182 * @parameter expression="${hibernate.export.schema.filename}" default-value="${project.build.directory}/schema.sql"
184 private String outputFile;
187 * Delimiter in output-file.
189 * @parameter expression="${hibernate.export.schema.delimiter}" default-value=";"
191 private String delimiter;
194 * Format output-file.
196 * @parameter expression="${hibernate.export.schema.format}" default-value="true"
198 private boolean format;
202 public void execute()
204 MojoFailureException,
205 MojoExecutionException
209 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
210 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
214 File dir = new File(outputDirectory);
216 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
218 Map<String,String> md5s;
219 boolean modified = false;
220 File saved = new File(buildDirectory + File.separator + MD5S);
226 FileInputStream fis = new FileInputStream(saved);
227 ObjectInputStream ois = new ObjectInputStream(fis);
228 md5s = (HashMap<String,String>)ois.readObject();
233 md5s = new HashMap<String,String>();
234 getLog().warn("Cannot read timestamps from saved: " + e);
239 md5s = new HashMap<String,String>();
242 saved.createNewFile();
244 catch (IOException e)
246 getLog().warn("Cannot create saved for timestamps: " + e);
250 ClassLoader classLoader = null;
253 getLog().debug("Creating ClassLoader for project-dependencies...");
254 List<String> classpathFiles = project.getCompileClasspathElements();
255 URL[] urls = new URL[classpathFiles.size()];
256 for (int i = 0; i < classpathFiles.size(); ++i)
258 getLog().debug("Dependency: " + classpathFiles.get(i));
259 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
261 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
265 getLog().error("Error while creating ClassLoader!", e);
266 throw new MojoExecutionException(e.getMessage());
269 Set<Class<?>> classes =
270 new TreeSet<Class<?>>(
271 new Comparator<Class<?>>() {
273 public int compare(Class<?> a, Class<?> b)
275 return a.getName().compareTo(b.getName());
282 AnnotationDB db = new AnnotationDB();
283 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
284 URL dirUrl = dir.toURI().toURL();
285 db.scanArchives(dirUrl);
287 Set<String> classNames = new HashSet<String>();
288 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
289 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
290 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
291 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
292 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
293 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
295 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
296 for (String name : classNames)
298 Class<?> annotatedClass = classLoader.loadClass(name);
299 classes.add(annotatedClass);
302 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
303 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
305 while((i = is.read(buffer)) > -1)
306 digest.update(buffer, 0, i);
308 byte[] bytes = digest.digest();
309 BigInteger bi = new BigInteger(1, bytes);
310 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
311 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
312 if (!newMd5.equals(oldMd5))
314 getLog().debug("Found new or modified annotated class: " + name);
316 md5s.put(name, newMd5);
320 getLog().debug(oldMd5 + " -> class unchanged: " + name);
324 catch (ClassNotFoundException e)
326 getLog().error("Error while adding annotated classes!", e);
327 throw new MojoExecutionException(e.getMessage());
331 getLog().error("Error while scanning!", e);
332 throw new MojoFailureException(e.getMessage());
335 if (classes.isEmpty())
336 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
338 getLog().debug("Detected classes with mapping-annotations:");
339 for (Class<?> annotatedClass : classes)
340 getLog().debug(" " + annotatedClass.getName());
343 Properties properties = new Properties();
345 /** Try to read configuration from properties-file */
348 File file = new File(hibernateProperties);
351 getLog().info("Reading properties from file " + hibernateProperties + "...");
352 properties.load(new FileInputStream(file));
355 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
357 catch (IOException e)
359 getLog().error("Error while reading properties!", e);
360 throw new MojoExecutionException(e.getMessage());
363 /** Overwrite values from propertie-file or set, if given */
364 if (driverClassName != null)
366 if (properties.containsKey(DRIVER_CLASS))
368 "Overwriting property " +
369 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
370 " with the value " + driverClassName +
371 " from the plugin-configuration-parameter driverClassName!"
375 "Using the value " + driverClassName +
376 " from the plugin-configuration-parameter driverClassName!"
378 properties.setProperty(DRIVER_CLASS, driverClassName);
382 if (properties.containsKey(URL))
384 "Overwriting property " +
385 URL + "=" + properties.getProperty(URL) +
386 " with the value " + url +
387 " from the plugin-configuration-parameter url!"
391 "Using the value " + url +
392 " from the plugin-configuration-parameter url!"
394 properties.setProperty(URL, url);
396 if (username != null)
398 if (properties.containsKey(USERNAME))
400 "Overwriting property " +
401 USERNAME + "=" + properties.getProperty(USERNAME) +
402 " with the value " + username +
403 " from the plugin-configuration-parameter username!"
407 "Using the value " + username +
408 " from the plugin-configuration-parameter username!"
410 properties.setProperty(USERNAME, username);
412 if (password != null)
414 if (properties.containsKey(PASSWORD))
416 "Overwriting property " +
417 PASSWORD + "=" + properties.getProperty(PASSWORD) +
418 " with the value " + password +
419 " from the plugin-configuration-parameter password!"
423 "Using the value " + password +
424 " from the plugin-configuration-parameter password!"
426 properties.setProperty(PASSWORD, password);
428 if (hibernateDialect != null)
430 if (properties.containsKey(DIALECT))
432 "Overwriting property " +
433 DIALECT + "=" + properties.getProperty(DIALECT) +
434 " with the value " + hibernateDialect +
435 " from the plugin-configuration-parameter hibernateDialect!"
439 "Using the value " + hibernateDialect +
440 " from the plugin-configuration-parameter hibernateDialect!"
442 properties.setProperty(DIALECT, hibernateDialect);
445 /** The generated SQL varies with the dialect! */
446 if (md5s.containsKey(DIALECT))
448 String dialect = properties.getProperty(DIALECT);
449 if (md5s.get(DIALECT).equals(dialect))
450 getLog().debug("SQL-dialect unchanged.");
453 getLog().debug("SQL-dialect changed: " + dialect);
455 md5s.put(DIALECT, dialect);
461 md5s.put(DIALECT, properties.getProperty(DIALECT));
464 if (properties.isEmpty())
466 getLog().error("No properties set!");
467 throw new MojoFailureException("Hibernate-Configuration is missing!");
470 Configuration config = new Configuration();
471 config.setProperties(properties);
472 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
473 for (Class<?> annotatedClass : classes)
475 getLog().debug("Class " + annotatedClass);
476 config.addAnnotatedClass(annotatedClass);
479 Target target = null;
482 target = Target.valueOf(this.target);
484 catch (IllegalArgumentException e)
486 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
487 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
488 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
493 type = Type.valueOf(this.type);
495 catch (IllegalArgumentException e)
497 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
498 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
499 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
502 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
504 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
508 && !target.equals(Target.SCRIPT)
509 && !target.equals(Target.NONE)
512 getLog().info("No modified annotated classes found and dialect unchanged.");
513 getLog().info("Skipping schema generation!");
514 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
518 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
519 for (Entry<Object,Object> entry : properties.entrySet())
520 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
522 Connection connection = null;
526 * The connection must be established outside of hibernate, because
527 * hibernate does not use the context-classloader of the current
528 * thread and, hence, would not be able to resolve the driver-class!
539 Class driverClass = classLoader.loadClass(driverClassName);
540 getLog().debug("Registering JDBC-driver " + driverClass.getName());
541 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
542 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
543 connection = DriverManager.getConnection(url, username, password);
547 catch (ClassNotFoundException e)
549 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
550 throw new MojoExecutionException(e.getMessage());
554 getLog().error("Cannot establish connection to database!");
555 Enumeration<Driver> drivers = DriverManager.getDrivers();
556 if (!drivers.hasMoreElements())
557 getLog().error("No drivers registered!");
558 while (drivers.hasMoreElements())
559 getLog().debug("Driver: " + drivers.nextElement());
560 throw new MojoExecutionException(e.getMessage());
563 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
564 MavenLogAppender.startPluginLog(this);
568 * Change class-loader of current thread, so that hibernate can
569 * see all dependencies!
571 Thread.currentThread().setContextClassLoader(classLoader);
573 SchemaExport export = new SchemaExport(config, connection);
574 export.setOutputFile(outputFile);
575 export.setDelimiter(delimiter);
576 export.setFormat(format);
577 export.execute(target, type);
579 for (Object exception : export.getExceptions())
580 getLog().debug(exception.toString());
584 /** Stop Log-Capturing */
585 MavenLogAppender.endPluginLog(this);
587 /** Restore the old class-loader (TODO: is this really necessary?) */
588 Thread.currentThread().setContextClassLoader(contextClassLoader);
590 /** Close the connection */
595 catch (SQLException e)
597 getLog().error("Error while closing connection: " + e.getMessage());
601 /** Write md5-sums for annotated classes to file */
604 FileOutputStream fos = new FileOutputStream(saved);
605 ObjectOutputStream oos = new ObjectOutputStream(fos);
606 oos.writeObject(md5s);
612 getLog().error("Cannot write md5-sums to file: " + e);
617 * Needed, because DriverManager won't pick up drivers, that were not
618 * loaded by the system-classloader!
620 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
622 static final class DriverProxy implements Driver
624 private final Driver target;
626 DriverProxy(Driver target)
629 throw new NullPointerException();
630 this.target = target;
633 public java.sql.Driver getTarget()
639 public boolean acceptsURL(String url) throws SQLException
641 return target.acceptsURL(url);
645 public java.sql.Connection connect(
647 java.util.Properties info
652 return target.connect(url, info);
656 public int getMajorVersion()
658 return target.getMajorVersion();
662 public int getMinorVersion()
664 return target.getMinorVersion();
668 public DriverPropertyInfo[] getPropertyInfo(
675 return target.getPropertyInfo(url, info);
679 public boolean jdbcCompliant()
681 return target.jdbcCompliant();
685 * This Method cannot be annotated with @Override, becaus the plugin
686 * will not compile then under Java 1.6!
688 public Logger getParentLogger() throws SQLFeatureNotSupportedException
690 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
694 public String toString()
696 return "Proxy: " + target;
700 public int hashCode()
702 return target.hashCode();
706 public boolean equals(Object obj)
708 if (!(obj instanceof DriverProxy))
710 DriverProxy other = (DriverProxy) obj;
711 return this.target.equals(other.target);