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.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
36 import java.util.TreeSet;
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 TreeSet<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 getLog().info("Detected classes with mapping-annotations:");
221 for (String classname : classes)
222 getLog().info(" " + classname);
224 Properties properties = new Properties();
226 /** Try to read configuration from properties-file */
229 File file = new File(hibernateProperties);
232 getLog().info("Reading properties from file " + hibernateProperties + "...");
233 properties.load(new FileInputStream(file));
236 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
238 catch (IOException e)
240 getLog().error("Error while reading properties!", e);
241 throw new MojoExecutionException(e.getMessage());
244 /** Overwrite values from propertie-file or set, if given */
245 if (driverClassName != null)
247 if (properties.containsKey(DRIVER_CLASS))
249 "Overwriting property " +
250 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
251 " with the value " + driverClassName +
252 " from the plugin-configuration-parameter driverClassName!"
256 "Using the value " + driverClassName +
257 " from the plugin-configuration-parameter driverClassName!"
259 properties.setProperty(DRIVER_CLASS, driverClassName);
263 if (properties.containsKey(URL))
265 "Overwriting property " +
266 URL + "=" + properties.getProperty(URL) +
267 " with the value " + url +
268 " from the plugin-configuration-parameter url!"
272 "Using the value " + url +
273 " from the plugin-configuration-parameter url!"
275 properties.setProperty(URL, url);
277 if (username != null)
279 if (properties.containsKey(USERNAME))
281 "Overwriting property " +
282 USERNAME + "=" + properties.getProperty(USERNAME) +
283 " with the value " + username +
284 " from the plugin-configuration-parameter username!"
288 "Using the value " + username +
289 " from the plugin-configuration-parameter username!"
291 properties.setProperty(USERNAME, username);
293 if (password != null)
295 if (properties.containsKey(PASSWORD))
297 "Overwriting property " +
298 PASSWORD + "=" + properties.getProperty(PASSWORD) +
299 " with the value " + password +
300 " from the plugin-configuration-parameter password!"
304 "Using the value " + password +
305 " from the plugin-configuration-parameter password!"
307 properties.setProperty(PASSWORD, password);
309 if (hibernateDialect != null)
311 if (properties.containsKey(DIALECT))
313 "Overwriting property " +
314 DIALECT + "=" + properties.getProperty(DIALECT) +
315 " with the value " + hibernateDialect +
316 " from the plugin-configuration-parameter hibernateDialect!"
320 "Using the value " + hibernateDialect +
321 " from the plugin-configuration-parameter hibernateDialect!"
323 properties.setProperty(DIALECT, hibernateDialect);
326 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
327 if (properties.isEmpty())
329 getLog().error("No properties set!");
330 throw new MojoFailureException("Hibernate-Configuration is missing!");
332 for (Entry<Object,Object> entry : properties.entrySet())
333 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
335 ClassLoader classLoader = null;
338 getLog().debug("Creating ClassLoader for project-dependencies...");
339 List<String> classpathFiles = project.getCompileClasspathElements();
340 URL[] urls = new URL[classpathFiles.size()];
341 for (int i = 0; i < classpathFiles.size(); ++i)
343 getLog().debug("Dependency: " + classpathFiles.get(i));
344 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
346 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
350 getLog().error("Error while creating ClassLoader!", e);
351 throw new MojoExecutionException(e.getMessage());
354 Configuration config = new Configuration();
355 config.setProperties(properties);
358 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
359 for (String annotatedClass : classes)
361 getLog().debug("Class " + annotatedClass);
362 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
365 catch (ClassNotFoundException e)
367 getLog().error("Error while adding annotated classes!", e);
368 throw new MojoExecutionException(e.getMessage());
371 Target target = null;
374 target = Target.valueOf(this.target);
376 catch (IllegalArgumentException e)
378 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
379 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
380 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
385 type = Type.valueOf(this.type);
387 catch (IllegalArgumentException e)
389 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
390 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
391 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
394 Connection connection = null;
398 * The connection must be established outside of hibernate, because
399 * hibernate does not use the context-classloader of the current
400 * thread and, hence, would not be able to resolve the driver-class!
411 Class driverClass = classLoader.loadClass(driverClassName);
412 getLog().debug("Registering JDBC-driver " + driverClass.getName());
413 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
414 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
415 connection = DriverManager.getConnection(url, username, password);
419 catch (ClassNotFoundException e)
421 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
422 throw new MojoExecutionException(e.getMessage());
426 getLog().error("Cannot establish connection to database!");
427 Enumeration<Driver> drivers = DriverManager.getDrivers();
428 if (!drivers.hasMoreElements())
429 getLog().error("No drivers registered!");
430 while (drivers.hasMoreElements())
431 getLog().debug("Driver: " + drivers.nextElement());
432 throw new MojoExecutionException(e.getMessage());
435 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
436 MavenLogAppender.startPluginLog(this);
440 * Change class-loader of current thread, so that hibernate can
441 * see all dependencies!
443 Thread.currentThread().setContextClassLoader(classLoader);
445 SchemaExport export = new SchemaExport(config, connection);
446 export.setOutputFile(outputFile);
447 export.setDelimiter(delimiter);
448 export.setFormat(format);
449 export.execute(target, type);
451 for (Object exception : export.getExceptions())
452 getLog().debug(exception.toString());
456 /** Stop Log-Capturing */
457 MavenLogAppender.endPluginLog(this);
459 /** Restore the old class-loader (TODO: is this really necessary?) */
460 Thread.currentThread().setContextClassLoader(contextClassLoader);
462 /** Close the connection */
467 catch (SQLException e)
469 getLog().error("Error while closing connection: " + e.getMessage());
475 * Needed, because DriverManager won't pick up drivers, that were not
476 * loaded by the system-classloader!
478 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
480 static final class DriverProxy implements Driver
482 private final Driver target;
484 DriverProxy(Driver target)
487 throw new NullPointerException();
488 this.target = target;
491 public java.sql.Driver getTarget()
497 public boolean acceptsURL(String url) throws SQLException
499 return target.acceptsURL(url);
503 public java.sql.Connection connect(
505 java.util.Properties info
510 return target.connect(url, info);
514 public int getMajorVersion()
516 return target.getMajorVersion();
520 public int getMinorVersion()
522 return target.getMinorVersion();
526 public DriverPropertyInfo[] getPropertyInfo(
533 return target.getPropertyInfo(url, info);
537 public boolean jdbcCompliant()
539 return target.jdbcCompliant();
543 * This Method cannot be annotated with @Override, becaus the plugin
544 * will not compile then under Java 1.6!
546 public Logger getParentLogger() throws SQLFeatureNotSupportedException
548 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
552 public String toString()
554 return "Proxy: " + target;
558 public int hashCode()
560 return target.hashCode();
564 public boolean equals(Object obj)
566 if (!(obj instanceof DriverProxy))
568 DriverProxy other = (DriverProxy) obj;
569 return this.target.equals(other.target);