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 DRIVER_CLASS = "hibernate.connection.driver_class";
74 public final static String URL = "hibernate.connection.url";
75 public final static String USERNAME = "hibernate.connection.username";
76 public final static String PASSWORD = "hibernate.connection.password";
77 public final static String DIALECT = "hibernate.dialect";
79 private final static String MD5S = "schema.md5s";
82 * The project whose project files to create.
84 * @parameter expression="${project}"
88 private MavenProject project;
91 * Directories to scan.
93 * @parameter expression="${project.build.outputDirectory}"
95 private String outputDirectory;
100 * @parameter expression="${maven.test.skip}"
102 private boolean skip;
107 * @parameter expression="${hibernate.connection.driver_class}
109 private String driverClassName;
114 * @parameter expression="${hibernate.connection.url}"
121 * @parameter expression="${hibernate.connection.username}"
123 private String username;
128 * @parameter expression="${hibernate.connection.password}"
130 private String password;
135 * @parameter expression="${hibernate.dialect}"
137 private String hibernateDialect;
140 * Hibernate configuration file.
142 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
144 private String hibernateProperties;
147 * Target of execution:
149 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
150 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
151 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
152 * <li><strong>BOTH</strong></li>
154 * @parameter default-value="EXPORT"
156 private String target;
161 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
162 * <li><strong>CREATE</strong> create database-schema</li>
163 * <li><strong>DROP</strong> drop database-schema</li>
164 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
166 * @parameter default-value="BOTH"
173 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
175 private String outputFile;
178 * Delimiter in output-file.
180 * @parameter default-value=";"
182 private String delimiter;
185 * Format output-file.
187 * @parameter default-value="true"
189 private boolean format;
193 public void execute()
195 MojoFailureException,
196 MojoExecutionException
200 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
204 File dir = new File(outputDirectory);
206 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
208 Map<String,String> md5s;
209 boolean modified = false;
210 File saved = new File(outputDirectory + File.separator + MD5S);
216 FileInputStream fis = new FileInputStream(saved);
217 ObjectInputStream ois = new ObjectInputStream(fis);
218 md5s = (HashMap<String,String>)ois.readObject();
223 md5s = new HashMap<String,String>();
224 getLog().warn("Cannot read timestamps from saved: " + e);
229 md5s = new HashMap<String,String>();
232 saved.createNewFile();
234 catch (IOException e)
236 getLog().warn("Cannot create saved for timestamps: " + e);
240 ClassLoader classLoader = null;
243 getLog().debug("Creating ClassLoader for project-dependencies...");
244 List<String> classpathFiles = project.getCompileClasspathElements();
245 URL[] urls = new URL[classpathFiles.size()];
246 for (int i = 0; i < classpathFiles.size(); ++i)
248 getLog().debug("Dependency: " + classpathFiles.get(i));
249 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
251 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
255 getLog().error("Error while creating ClassLoader!", e);
256 throw new MojoExecutionException(e.getMessage());
259 Set<Class<?>> classes =
260 new TreeSet<Class<?>>(
261 new Comparator<Class<?>>() {
263 public int compare(Class<?> a, Class<?> b)
265 return a.getName().compareTo(b.getName());
272 AnnotationDB db = new AnnotationDB();
273 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
274 URL dirUrl = dir.toURI().toURL();
275 db.scanArchives(dirUrl);
277 Set<String> classNames = new HashSet<String>();
278 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
279 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
280 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
281 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
282 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
283 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
285 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
286 for (String name : classNames)
288 Class<?> annotatedClass = classLoader.loadClass(name);
289 classes.add(annotatedClass);
292 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
293 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
295 while((i = is.read(buffer)) > -1)
296 digest.update(buffer, 0, i);
298 byte[] bytes = digest.digest();
299 BigInteger bi = new BigInteger(1, bytes);
300 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
301 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
302 if (!newMd5.equals(oldMd5))
304 getLog().debug("Found new or modified annotated class: " + name);
306 md5s.put(name, newMd5);
310 getLog().debug(oldMd5 + " -> class unchanged: " + name);
314 catch (ClassNotFoundException e)
316 getLog().error("Error while adding annotated classes!", e);
317 throw new MojoExecutionException(e.getMessage());
321 getLog().error("Error while scanning!", e);
322 throw new MojoFailureException(e.getMessage());
325 if (classes.isEmpty())
326 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
328 getLog().debug("Detected classes with mapping-annotations:");
329 for (Class<?> annotatedClass : classes)
330 getLog().debug(" " + annotatedClass.getName());
333 Properties properties = new Properties();
335 /** Try to read configuration from properties-file */
338 File file = new File(hibernateProperties);
341 getLog().info("Reading properties from file " + hibernateProperties + "...");
342 properties.load(new FileInputStream(file));
345 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
347 catch (IOException e)
349 getLog().error("Error while reading properties!", e);
350 throw new MojoExecutionException(e.getMessage());
353 /** Overwrite values from propertie-file or set, if given */
354 if (driverClassName != null)
356 if (properties.containsKey(DRIVER_CLASS))
358 "Overwriting property " +
359 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
360 " with the value " + driverClassName +
361 " from the plugin-configuration-parameter driverClassName!"
365 "Using the value " + driverClassName +
366 " from the plugin-configuration-parameter driverClassName!"
368 properties.setProperty(DRIVER_CLASS, driverClassName);
372 if (properties.containsKey(URL))
374 "Overwriting property " +
375 URL + "=" + properties.getProperty(URL) +
376 " with the value " + url +
377 " from the plugin-configuration-parameter url!"
381 "Using the value " + url +
382 " from the plugin-configuration-parameter url!"
384 properties.setProperty(URL, url);
386 if (username != null)
388 if (properties.containsKey(USERNAME))
390 "Overwriting property " +
391 USERNAME + "=" + properties.getProperty(USERNAME) +
392 " with the value " + username +
393 " from the plugin-configuration-parameter username!"
397 "Using the value " + username +
398 " from the plugin-configuration-parameter username!"
400 properties.setProperty(USERNAME, username);
402 if (password != null)
404 if (properties.containsKey(PASSWORD))
406 "Overwriting property " +
407 PASSWORD + "=" + properties.getProperty(PASSWORD) +
408 " with the value " + password +
409 " from the plugin-configuration-parameter password!"
413 "Using the value " + password +
414 " from the plugin-configuration-parameter password!"
416 properties.setProperty(PASSWORD, password);
418 if (hibernateDialect != null)
420 if (properties.containsKey(DIALECT))
422 "Overwriting property " +
423 DIALECT + "=" + properties.getProperty(DIALECT) +
424 " with the value " + hibernateDialect +
425 " from the plugin-configuration-parameter hibernateDialect!"
429 "Using the value " + hibernateDialect +
430 " from the plugin-configuration-parameter 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));
456 getLog().info("No modified annotated classes found and dialect unchanged.");
457 getLog().info("Skipping schema generation!");
458 project.getProperties().setProperty("hibernate4.skipped", "true");
462 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
463 if (properties.isEmpty())
465 getLog().error("No properties set!");
466 throw new MojoFailureException("Hibernate-Configuration is missing!");
468 for (Entry<Object,Object> entry : properties.entrySet())
469 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
471 Configuration config = new Configuration();
472 config.setProperties(properties);
473 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
474 for (Class<?> annotatedClass : classes)
476 getLog().debug("Class " + annotatedClass);
477 config.addAnnotatedClass(annotatedClass);
480 Target target = null;
483 target = Target.valueOf(this.target);
485 catch (IllegalArgumentException e)
487 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
488 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
489 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
494 type = Type.valueOf(this.type);
496 catch (IllegalArgumentException e)
498 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
499 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
500 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
503 Connection connection = null;
507 * The connection must be established outside of hibernate, because
508 * hibernate does not use the context-classloader of the current
509 * thread and, hence, would not be able to resolve the driver-class!
520 Class driverClass = classLoader.loadClass(driverClassName);
521 getLog().debug("Registering JDBC-driver " + driverClass.getName());
522 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
523 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
524 connection = DriverManager.getConnection(url, username, password);
528 catch (ClassNotFoundException e)
530 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
531 throw new MojoExecutionException(e.getMessage());
535 getLog().error("Cannot establish connection to database!");
536 Enumeration<Driver> drivers = DriverManager.getDrivers();
537 if (!drivers.hasMoreElements())
538 getLog().error("No drivers registered!");
539 while (drivers.hasMoreElements())
540 getLog().debug("Driver: " + drivers.nextElement());
541 throw new MojoExecutionException(e.getMessage());
544 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
545 MavenLogAppender.startPluginLog(this);
549 * Change class-loader of current thread, so that hibernate can
550 * see all dependencies!
552 Thread.currentThread().setContextClassLoader(classLoader);
554 SchemaExport export = new SchemaExport(config, connection);
555 export.setOutputFile(outputFile);
556 export.setDelimiter(delimiter);
557 export.setFormat(format);
558 export.execute(target, type);
560 for (Object exception : export.getExceptions())
561 getLog().debug(exception.toString());
565 /** Stop Log-Capturing */
566 MavenLogAppender.endPluginLog(this);
568 /** Restore the old class-loader (TODO: is this really necessary?) */
569 Thread.currentThread().setContextClassLoader(contextClassLoader);
571 /** Close the connection */
576 catch (SQLException e)
578 getLog().error("Error while closing connection: " + e.getMessage());
582 /** Write timestamps for annotated classes to file */
585 FileOutputStream fos = new FileOutputStream(saved);
586 ObjectOutputStream oos = new ObjectOutputStream(fos);
587 oos.writeObject(md5s);
593 getLog().error("Cannot write timestamps to file: " + e);
598 * Needed, because DriverManager won't pick up drivers, that were not
599 * loaded by the system-classloader!
601 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
603 static final class DriverProxy implements Driver
605 private final Driver target;
607 DriverProxy(Driver target)
610 throw new NullPointerException();
611 this.target = target;
614 public java.sql.Driver getTarget()
620 public boolean acceptsURL(String url) throws SQLException
622 return target.acceptsURL(url);
626 public java.sql.Connection connect(
628 java.util.Properties info
633 return target.connect(url, info);
637 public int getMajorVersion()
639 return target.getMajorVersion();
643 public int getMinorVersion()
645 return target.getMinorVersion();
649 public DriverPropertyInfo[] getPropertyInfo(
656 return target.getPropertyInfo(url, info);
660 public boolean jdbcCompliant()
662 return target.jdbcCompliant();
666 * This Method cannot be annotated with @Override, becaus the plugin
667 * will not compile then under Java 1.6!
669 public Logger getParentLogger() throws SQLFeatureNotSupportedException
671 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
675 public String toString()
677 return "Proxy: " + target;
681 public int hashCode()
683 return target.hashCode();
687 public boolean equals(Object obj)
689 if (!(obj instanceof DriverProxy))
691 DriverProxy other = (DriverProxy) obj;
692 return this.target.equals(other.target);