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.IOException;
24 import java.net.URLClassLoader;
25 import java.sql.Connection;
26 import java.sql.Driver;
27 import java.sql.DriverManager;
28 import java.sql.DriverPropertyInfo;
29 import java.sql.SQLException;
30 import java.sql.SQLFeatureNotSupportedException;
31 import java.util.Enumeration;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.Properties;
37 import java.util.logging.Logger;
38 import javax.persistence.Embeddable;
39 import javax.persistence.Entity;
40 import javax.persistence.MappedSuperclass;
41 import org.apache.maven.plugin.AbstractMojo;
42 import org.apache.maven.plugin.MojoExecutionException;
43 import org.apache.maven.plugin.MojoFailureException;
44 import org.apache.maven.project.MavenProject;
45 import org.hibernate.cfg.Configuration;
46 import org.hibernate.tool.hbm2ddl.SchemaExport;
47 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
48 import org.hibernate.tool.hbm2ddl.Target;
49 import org.scannotation.AnnotationDB;
53 * Goal which extracts the hibernate-mapping-configuration and
54 * exports an according SQL-database-schema.
57 * @phase process-classes
59 * @requiresDependencyResolution runtime
61 public class Hbm2DdlMojo extends AbstractMojo
63 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
64 public final static String URL = "hibernate.connection.url";
65 public final static String USERNAME = "hibernate.connection.username";
66 public final static String PASSWORD = "hibernate.connection.password";
67 public final static String DIALECT = "hibernate.dialect";
71 * The project whose project files to create.
73 * @parameter expression="${project}"
77 private MavenProject project;
80 * Directories to scan.
82 * @parameter expression="${project.build.outputDirectory}"
84 private String outputDirectory;
89 * @parameter expression="${maven.test.skip}"
96 * @parameter expression="${hibernate.connection.driver_class}
98 private String driverClassName;
103 * @parameter expression="${hibernate.connection.url}"
110 * @parameter expression="${hibernate.connection.username}"
112 private String username;
117 * @parameter expression="${hibernate.connection.password}"
119 private String password;
124 * @parameter expression="${hibernate.dialect}"
126 private String hibernateDialect;
129 * Hibernate configuration file.
131 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
133 private String hibernateProperties;
136 * Target of execution:
138 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
139 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
140 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
141 * <li><strong>BOTH</strong></li>
143 * @parameter default-value="EXPORT"
145 private String target;
150 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
151 * <li><strong>CREATE</strong> create database-schema</li>
152 * <li><strong>DROP</strong> drop database-schema</li>
153 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
155 * @parameter default-value="BOTH"
162 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
164 private String outputFile;
167 * Delimiter in output-file.
169 * @parameter default-value=";"
171 private String delimiter;
174 * Format output-file.
176 * @parameter default-value="true"
178 private boolean format;
182 public void execute()
184 MojoFailureException,
185 MojoExecutionException
189 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
193 File dir = new File(outputDirectory);
195 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
198 Set<String> classes = new HashSet<String>();
201 AnnotationDB db = new AnnotationDB();
202 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
203 URL dirUrl = dir.toURI().toURL();
204 db.scanArchives(dirUrl);
205 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
206 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
207 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
208 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
209 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
210 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
212 catch (IOException e)
214 getLog().error("Error while scanning!", e);
215 throw new MojoFailureException(e.getMessage());
217 if (classes.isEmpty())
218 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
220 Properties properties = new Properties();
222 /** Try to read configuration from properties-file */
225 File file = new File(hibernateProperties);
228 getLog().info("Reading properties from file " + hibernateProperties + "...");
229 properties.load(new FileInputStream(file));
232 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
234 catch (IOException e)
236 getLog().error("Error while reading properties!", e);
237 throw new MojoExecutionException(e.getMessage());
240 /** Overwrite values from propertie-file or set, if given */
241 if (driverClassName != null)
243 if (properties.containsKey(DRIVER_CLASS))
245 "Overwriting property " +
246 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
247 " with the value " + driverClassName +
248 " from the plugin-configuration-parameter driverClassName!"
252 "Using the value " + driverClassName +
253 " from the plugin-configuration-parameter driverClassName!"
255 properties.setProperty(DRIVER_CLASS, driverClassName);
259 if (properties.containsKey(URL))
261 "Overwriting property " +
262 URL + "=" + properties.getProperty(URL) +
263 " with the value " + url +
264 " from the plugin-configuration-parameter url!"
268 "Using the value " + url +
269 " from the plugin-configuration-parameter url!"
271 properties.setProperty(URL, url);
273 if (username != null)
275 if (properties.containsKey(USERNAME))
277 "Overwriting property " +
278 USERNAME + "=" + properties.getProperty(USERNAME) +
279 " with the value " + username +
280 " from the plugin-configuration-parameter username!"
284 "Using the value " + username +
285 " from the plugin-configuration-parameter username!"
287 properties.setProperty(USERNAME, username);
289 if (password != null)
291 if (properties.containsKey(PASSWORD))
293 "Overwriting property " +
294 PASSWORD + "=" + properties.getProperty(PASSWORD) +
295 " with the value " + password +
296 " from the plugin-configuration-parameter password!"
300 "Using the value " + password +
301 " from the plugin-configuration-parameter password!"
303 properties.setProperty(PASSWORD, password);
305 if (hibernateDialect != null)
307 if (properties.containsKey(DIALECT))
309 "Overwriting property " +
310 DIALECT + "=" + properties.getProperty(DIALECT) +
311 " with the value " + hibernateDialect +
312 " from the plugin-configuration-parameter hibernateDialect!"
316 "Using the value " + hibernateDialect +
317 " from the plugin-configuration-parameter hibernateDialect!"
319 properties.setProperty(DIALECT, hibernateDialect);
322 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
323 if (properties.isEmpty())
325 getLog().error("No properties set!");
326 throw new MojoFailureException("Hibernate-Configuration is missing!");
328 for (Entry<Object,Object> entry : properties.entrySet())
329 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
331 ClassLoader classLoader = null;
334 getLog().debug("Creating ClassLoader for project-dependencies...");
335 List<String> classpathFiles = project.getCompileClasspathElements();
336 URL[] urls = new URL[classpathFiles.size()];
337 for (int i = 0; i < classpathFiles.size(); ++i)
339 getLog().debug("Dependency: " + classpathFiles.get(i));
340 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
342 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
346 getLog().error("Error while creating ClassLoader!", e);
347 throw new MojoExecutionException(e.getMessage());
350 Configuration config = new Configuration();
351 config.setProperties(properties);
354 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
355 for (String annotatedClass : classes)
357 getLog().debug("Class " + annotatedClass);
358 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
361 catch (ClassNotFoundException e)
363 getLog().error("Error while adding annotated classes!", e);
364 throw new MojoExecutionException(e.getMessage());
367 Target target = null;
370 target = Target.valueOf(this.target);
372 catch (IllegalArgumentException e)
374 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
375 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
376 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
381 type = Type.valueOf(this.type);
383 catch (IllegalArgumentException e)
385 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
386 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
387 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
390 Connection connection = null;
394 * The connection must be established outside of hibernate, because
395 * hibernate does not use the context-classloader of the current
396 * thread and, hence, would not be able to resolve the driver-class!
407 Class driverClass = classLoader.loadClass(driverClassName);
408 getLog().debug("Registering JDBC-driver " + driverClass.getName());
409 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
410 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
411 connection = DriverManager.getConnection(url, username, password);
415 catch (ClassNotFoundException e)
417 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
418 throw new MojoExecutionException(e.getMessage());
422 getLog().error("Cannot establish connection to database!");
423 Enumeration<Driver> drivers = DriverManager.getDrivers();
424 if (!drivers.hasMoreElements())
425 getLog().error("No drivers registered!");
426 while (drivers.hasMoreElements())
427 getLog().debug("Driver: " + drivers.nextElement());
428 throw new MojoExecutionException(e.getMessage());
431 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
432 MavenLogAppender.startPluginLog(this);
436 * Change class-loader of current thread, so that hibernate can
437 * see all dependencies!
439 Thread.currentThread().setContextClassLoader(classLoader);
441 SchemaExport export = new SchemaExport(config, connection);
442 export.setOutputFile(outputFile);
443 export.setDelimiter(delimiter);
444 export.setFormat(format);
445 export.execute(target, type);
447 for (Object exception : export.getExceptions())
448 getLog().debug(exception.toString());
452 /** Stop Log-Capturing */
453 MavenLogAppender.endPluginLog(this);
455 /** Restore the old class-loader (TODO: is this really necessary?) */
456 Thread.currentThread().setContextClassLoader(contextClassLoader);
458 /** Close the connection */
463 catch (SQLException e)
465 getLog().error("Error while closing connection: " + e.getMessage());
471 * Needed, because DriverManager won't pick up drivers, that were not
472 * loaded by the system-classloader!
474 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
476 static final class DriverProxy implements Driver
478 private final Driver target;
480 DriverProxy(Driver target)
483 throw new NullPointerException();
484 this.target = target;
487 public java.sql.Driver getTarget()
493 public boolean acceptsURL(String url) throws SQLException
495 return target.acceptsURL(url);
499 public java.sql.Connection connect(
501 java.util.Properties info
506 return target.connect(url, info);
510 public int getMajorVersion()
512 return target.getMajorVersion();
516 public int getMinorVersion()
518 return target.getMinorVersion();
522 public DriverPropertyInfo[] getPropertyInfo(
529 return target.getPropertyInfo(url, info);
533 public boolean jdbcCompliant()
535 return target.jdbcCompliant();
539 * This Method cannot be annotated with @Override, becaus the plugin
540 * will not compile then under Java 1.6!
542 public Logger getParentLogger() throws SQLFeatureNotSupportedException
544 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
548 public String toString()
550 return "Proxy: " + target;
554 public int hashCode()
556 return target.hashCode();
560 public boolean equals(Object obj)
562 if (!(obj instanceof DriverProxy))
564 DriverProxy other = (DriverProxy) obj;
565 return this.target.equals(other.target);