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);
330 getLog().info("No modified annotated classes found.");
331 getLog().info("Skipping schema generation!");
332 project.getProperties().setProperty("hibernate4.skipped", "true");
336 getLog().debug("Detected classes with mapping-annotations:");
337 for (Class<?> annotatedClass : classes)
338 getLog().debug(" " + annotatedClass.getName());
341 Properties properties = new Properties();
343 /** Try to read configuration from properties-file */
346 File file = new File(hibernateProperties);
349 getLog().info("Reading properties from file " + hibernateProperties + "...");
350 properties.load(new FileInputStream(file));
353 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
355 catch (IOException e)
357 getLog().error("Error while reading properties!", e);
358 throw new MojoExecutionException(e.getMessage());
361 /** Overwrite values from propertie-file or set, if given */
362 if (driverClassName != null)
364 if (properties.containsKey(DRIVER_CLASS))
366 "Overwriting property " +
367 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
368 " with the value " + driverClassName +
369 " from the plugin-configuration-parameter driverClassName!"
373 "Using the value " + driverClassName +
374 " from the plugin-configuration-parameter driverClassName!"
376 properties.setProperty(DRIVER_CLASS, driverClassName);
380 if (properties.containsKey(URL))
382 "Overwriting property " +
383 URL + "=" + properties.getProperty(URL) +
384 " with the value " + url +
385 " from the plugin-configuration-parameter url!"
389 "Using the value " + url +
390 " from the plugin-configuration-parameter url!"
392 properties.setProperty(URL, url);
394 if (username != null)
396 if (properties.containsKey(USERNAME))
398 "Overwriting property " +
399 USERNAME + "=" + properties.getProperty(USERNAME) +
400 " with the value " + username +
401 " from the plugin-configuration-parameter username!"
405 "Using the value " + username +
406 " from the plugin-configuration-parameter 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 +
417 " from the plugin-configuration-parameter password!"
421 "Using the value " + password +
422 " from the plugin-configuration-parameter password!"
424 properties.setProperty(PASSWORD, password);
426 if (hibernateDialect != null)
428 if (properties.containsKey(DIALECT))
430 "Overwriting property " +
431 DIALECT + "=" + properties.getProperty(DIALECT) +
432 " with the value " + hibernateDialect +
433 " from the plugin-configuration-parameter hibernateDialect!"
437 "Using the value " + hibernateDialect +
438 " from the plugin-configuration-parameter hibernateDialect!"
440 properties.setProperty(DIALECT, hibernateDialect);
443 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
444 if (properties.isEmpty())
446 getLog().error("No properties set!");
447 throw new MojoFailureException("Hibernate-Configuration is missing!");
449 for (Entry<Object,Object> entry : properties.entrySet())
450 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
452 Configuration config = new Configuration();
453 config.setProperties(properties);
454 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
455 for (Class<?> annotatedClass : classes)
457 getLog().debug("Class " + annotatedClass);
458 config.addAnnotatedClass(annotatedClass);
461 Target target = null;
464 target = Target.valueOf(this.target);
466 catch (IllegalArgumentException e)
468 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
469 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
470 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
475 type = Type.valueOf(this.type);
477 catch (IllegalArgumentException e)
479 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
480 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
481 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
484 Connection connection = null;
488 * The connection must be established outside of hibernate, because
489 * hibernate does not use the context-classloader of the current
490 * thread and, hence, would not be able to resolve the driver-class!
501 Class driverClass = classLoader.loadClass(driverClassName);
502 getLog().debug("Registering JDBC-driver " + driverClass.getName());
503 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
504 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
505 connection = DriverManager.getConnection(url, username, password);
509 catch (ClassNotFoundException e)
511 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
512 throw new MojoExecutionException(e.getMessage());
516 getLog().error("Cannot establish connection to database!");
517 Enumeration<Driver> drivers = DriverManager.getDrivers();
518 if (!drivers.hasMoreElements())
519 getLog().error("No drivers registered!");
520 while (drivers.hasMoreElements())
521 getLog().debug("Driver: " + drivers.nextElement());
522 throw new MojoExecutionException(e.getMessage());
525 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
526 MavenLogAppender.startPluginLog(this);
530 * Change class-loader of current thread, so that hibernate can
531 * see all dependencies!
533 Thread.currentThread().setContextClassLoader(classLoader);
535 SchemaExport export = new SchemaExport(config, connection);
536 export.setOutputFile(outputFile);
537 export.setDelimiter(delimiter);
538 export.setFormat(format);
539 export.execute(target, type);
541 for (Object exception : export.getExceptions())
542 getLog().debug(exception.toString());
546 /** Stop Log-Capturing */
547 MavenLogAppender.endPluginLog(this);
549 /** Restore the old class-loader (TODO: is this really necessary?) */
550 Thread.currentThread().setContextClassLoader(contextClassLoader);
552 /** Close the connection */
557 catch (SQLException e)
559 getLog().error("Error while closing connection: " + e.getMessage());
563 /** Write timestamps for annotated classes to file */
566 FileOutputStream fos = new FileOutputStream(saved);
567 ObjectOutputStream oos = new ObjectOutputStream(fos);
568 oos.writeObject(md5s);
574 getLog().error("Cannot write timestamps to file: " + e);
579 * Needed, because DriverManager won't pick up drivers, that were not
580 * loaded by the system-classloader!
582 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
584 static final class DriverProxy implements Driver
586 private final Driver target;
588 DriverProxy(Driver target)
591 throw new NullPointerException();
592 this.target = target;
595 public java.sql.Driver getTarget()
601 public boolean acceptsURL(String url) throws SQLException
603 return target.acceptsURL(url);
607 public java.sql.Connection connect(
609 java.util.Properties info
614 return target.connect(url, info);
618 public int getMajorVersion()
620 return target.getMajorVersion();
624 public int getMinorVersion()
626 return target.getMinorVersion();
630 public DriverPropertyInfo[] getPropertyInfo(
637 return target.getPropertyInfo(url, info);
641 public boolean jdbcCompliant()
643 return target.jdbcCompliant();
647 * This Method cannot be annotated with @Override, becaus the plugin
648 * will not compile then under Java 1.6!
650 public Logger getParentLogger() throws SQLFeatureNotSupportedException
652 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
656 public String toString()
658 return "Proxy: " + target;
662 public int hashCode()
664 return target.hashCode();
668 public boolean equals(Object obj)
670 if (!(obj instanceof DriverProxy))
672 DriverProxy other = (DriverProxy) obj;
673 return this.target.equals(other.target);