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.util.Enumeration;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
36 import javax.persistence.Embeddable;
37 import javax.persistence.Entity;
38 import javax.persistence.MappedSuperclass;
39 import org.apache.maven.plugin.AbstractMojo;
40 import org.apache.maven.plugin.MojoExecutionException;
41 import org.apache.maven.plugin.MojoFailureException;
42 import org.apache.maven.project.MavenProject;
43 import org.hibernate.cfg.Configuration;
44 import org.hibernate.tool.hbm2ddl.SchemaExport;
45 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
46 import org.hibernate.tool.hbm2ddl.Target;
47 import org.scannotation.AnnotationDB;
51 * Goal which extracts the hibernate-mapping-configuration and
52 * exports an according SQL-database-schema.
55 * @phase process-classes
57 * @requiresDependencyResolution runtime
59 public class Hbm2DdlMojo extends AbstractMojo
61 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
62 public final static String URL = "hibernate.connection.url";
63 public final static String USERNAME = "hibernate.connection.username";
64 public final static String PASSWORD = "hibernate.connection.password";
65 public final static String DIALECT = "hibernate.dialect";
69 * The project whose project files to create.
71 * @parameter expression="${project}"
75 private MavenProject project;
78 * Directories to scan.
80 * @parameter expression="${project.build.outputDirectory}"
82 private String outputDirectory;
87 * @parameter expression="${maven.test.skip}"
94 * @parameter expression="${hibernate.connection.driver_class}
96 private String driverClassName;
101 * @parameter expression="${hibernate.connection.url}"
108 * @parameter expression="${hibernate.connection.username}"
110 private String username;
115 * @parameter expression="${hibernate.connection.password}"
117 private String password;
122 * @parameter expression="${hibernate.dialect}"
124 private String hibernateDialect;
127 * Hibernate configuration file.
129 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
131 private String hibernateProperties;
134 * Target of execution:
136 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
137 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
138 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
139 * <li><strong>BOTH</strong></li>
141 * @parameter default-value="EXPORT"
143 private String target;
148 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
149 * <li><strong>CREATE</strong> create database-schema</li>
150 * <li><strong>DROP</strong> drop database-schema</li>
151 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
153 * @parameter default-value="BOTH"
160 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
162 private String outputFile;
165 * Delimiter in output-file.
167 * @parameter default-value=";"
169 private String delimiter;
172 * Format output-file.
174 * @parameter default-value="true"
176 private boolean format;
180 public void execute()
182 MojoFailureException,
183 MojoExecutionException
188 File dir = new File(outputDirectory);
190 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
193 Set<String> classes = new HashSet<String>();
196 AnnotationDB db = new AnnotationDB();
197 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
198 URL dirUrl = dir.toURI().toURL();
199 db.scanArchives(dirUrl);
200 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
201 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
202 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
203 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
204 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
205 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
207 catch (IOException e)
209 getLog().error("Error while scanning!", e);
210 throw new MojoFailureException(e.getMessage());
212 if (classes.isEmpty())
213 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
215 Properties properties = new Properties();
217 /** Try to read configuration from properties-file */
220 File file = new File(hibernateProperties);
223 getLog().info("Reading properties from file " + hibernateProperties + "...");
224 properties.load(new FileInputStream(file));
227 getLog().info("No hibernate-properties-file found! Checked path: " + hibernateProperties);
229 catch (IOException e)
231 getLog().error("Error while reading properties!", e);
232 throw new MojoExecutionException(e.getMessage());
235 /** Overwrite values from propertie-file or set, if given */
236 if (driverClassName != null)
238 if (properties.containsKey(DRIVER_CLASS))
240 "Overwriting property " +
241 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
242 " with the value " + driverClassName +
243 " from the plugin-configuration-parameter driverClassName!"
247 "Using the value " + driverClassName +
248 " from the plugin-configuration-parameter driverClassName!"
250 properties.setProperty(DRIVER_CLASS, driverClassName);
254 if (properties.containsKey(URL))
256 "Overwriting property " +
257 URL + "=" + properties.getProperty(URL) +
258 " with the value " + url +
259 " from the plugin-configuration-parameter url!"
263 "Using the value " + url +
264 " from the plugin-configuration-parameter url!"
266 properties.setProperty(URL, url);
268 if (username != null)
270 if (properties.containsKey(USERNAME))
272 "Overwriting property " +
273 USERNAME + "=" + properties.getProperty(USERNAME) +
274 " with the value " + username +
275 " from the plugin-configuration-parameter username!"
279 "Using the value " + username +
280 " from the plugin-configuration-parameter username!"
282 properties.setProperty(USERNAME, username);
284 if (password != null)
286 if (properties.containsKey(PASSWORD))
288 "Overwriting property " +
289 PASSWORD + "=" + properties.getProperty(PASSWORD) +
290 " with the value " + password +
291 " from the plugin-configuration-parameter password!"
295 "Using the value " + password +
296 " from the plugin-configuration-parameter password!"
298 properties.setProperty(PASSWORD, password);
300 if (hibernateDialect != null)
302 if (properties.containsKey(DIALECT))
304 "Overwriting property " +
305 DIALECT + "=" + properties.getProperty(DIALECT) +
306 " with the value " + hibernateDialect +
307 " from the plugin-configuration-parameter hibernateDialect!"
311 "Using the value " + hibernateDialect +
312 " from the plugin-configuration-parameter hibernateDialect!"
314 properties.setProperty(DIALECT, hibernateDialect);
317 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
318 if (properties.isEmpty())
320 getLog().error("No properties set!");
321 throw new MojoFailureException("Hibernate-Configuration is missing!");
323 for (Entry<Object,Object> entry : properties.entrySet())
324 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
326 ClassLoader classLoader = null;
329 getLog().debug("Creating ClassLoader for project-dependencies...");
330 List<String> classpathFiles = project.getCompileClasspathElements();
331 URL[] urls = new URL[classpathFiles.size()];
332 for (int i = 0; i < classpathFiles.size(); ++i)
334 getLog().debug("Dependency: " + classpathFiles.get(i));
335 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
337 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
341 getLog().error("Error while creating ClassLoader!", e);
342 throw new MojoExecutionException(e.getMessage());
345 Configuration config = new Configuration();
346 config.setProperties(properties);
349 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
350 for (String annotatedClass : classes)
352 getLog().debug("Class " + annotatedClass);
353 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
356 catch (ClassNotFoundException e)
358 getLog().error("Error while adding annotated classes!", e);
359 throw new MojoExecutionException(e.getMessage());
362 Target target = null;
365 target = Target.valueOf(this.target);
367 catch (IllegalArgumentException e)
369 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
370 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
371 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
376 type = Type.valueOf(this.type);
378 catch (IllegalArgumentException e)
380 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
381 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
382 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
385 Connection connection = null;
389 * The connection must be established outside of hibernate, because
390 * hibernate does not use the context-classloader of the current
391 * thread and, hence, would not be able to resolve the driver-class!
402 Class driverClass = classLoader.loadClass(driverClassName);
403 getLog().debug("Registering JDBC-driver " + driverClass.getName());
404 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
405 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
406 connection = DriverManager.getConnection(url, username, password);
410 catch (ClassNotFoundException e)
412 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
413 throw new MojoExecutionException(e.getMessage());
417 getLog().error("Cannot establish connection to database!");
418 Enumeration<Driver> drivers = DriverManager.getDrivers();
419 if (!drivers.hasMoreElements())
420 getLog().error("No drivers registered!");
421 while (drivers.hasMoreElements())
422 getLog().debug("Driver: " + drivers.nextElement());
423 throw new MojoExecutionException(e.getMessage());
426 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
427 MavenLogAppender.startPluginLog(this);
431 * Change class-loader of current thread, so that hibernate can
432 * see all dependencies!
434 Thread.currentThread().setContextClassLoader(classLoader);
436 SchemaExport export = new SchemaExport(config, connection);
437 export.setOutputFile(outputFile);
438 export.setDelimiter(delimiter);
439 export.setFormat(format);
440 export.execute(target, type);
442 for (Object exception : export.getExceptions())
443 getLog().debug(exception.toString());
447 /** Stop Log-Capturing */
448 MavenLogAppender.endPluginLog(this);
450 /** Restore the old class-loader (TODO: is this really necessary?) */
451 Thread.currentThread().setContextClassLoader(contextClassLoader);
453 /** Close the connection */
458 catch (SQLException e)
460 getLog().error("Error while closing connection: " + e.getMessage());
466 * Needed, because DriverManager won't pick up drivers, that were not
467 * loaded by the system-classloader!
469 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
471 static final class DriverProxy implements Driver
473 private final Driver target;
475 DriverProxy(Driver target)
478 throw new NullPointerException();
479 this.target = target;
482 public java.sql.Driver getTarget()
488 public boolean acceptsURL(String url) throws SQLException
490 return target.acceptsURL(url);
494 public java.sql.Connection connect(
496 java.util.Properties info
501 return target.connect(url, info);
505 public int getMajorVersion()
507 return target.getMajorVersion();
511 public int getMinorVersion()
513 return target.getMinorVersion();
517 public DriverPropertyInfo[] getPropertyInfo(
524 return target.getPropertyInfo(url, info);
528 public boolean jdbcCompliant()
530 return target.jdbcCompliant();
534 public String toString()
536 return "Proxy: " + target;
540 public int hashCode()
542 return target.hashCode();
546 public boolean equals(Object obj)
548 if (!(obj instanceof DriverProxy))
550 DriverProxy other = (DriverProxy) obj;
551 return this.target.equals(other.target);