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.Entity;
37 import javax.persistence.Embeddable;
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
62 * The project whose project files to create.
64 * @parameter expression="${project}"
68 private MavenProject project;
71 * Directories to scan.
73 * @parameter expression="${project.build.outputDirectory}"
75 private String outputDirectory;
80 * @parameter default-value="false"
87 * @parameter expression="${hibernate.connection.driver_class}
89 private String driverClassName;
94 * @parameter expression="${hibernate.connection.url}"
101 * @parameter expression="${hibernate.connection.username}"
103 private String username;
108 * @parameter expression="${hibernate.connection.password}"
110 private String password;
115 * @parameter expression="${hibernate.dialect}"
117 private String hibernateDialect;
120 * Hibernate configuration file.
122 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
124 private String hibernateProperties;
127 * Target of execution:
129 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
130 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
131 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
132 * <li><strong>BOTH</strong></li>
134 * @parameter default-value="EXPORT"
136 private String target;
141 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
142 * <li><strong>CREATE</strong> create database-schema</li>
143 * <li><strong>DROP</strong> drop database-schema</li>
144 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
146 * @parameter default-value="BOTH"
153 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
155 private String outputFile;
158 * Delimiter in output-file.
160 * @parameter default-value=";"
162 private String delimiter;
165 * Format output-file.
167 * @parameter default-value="true"
169 private boolean format;
173 public void execute()
175 MojoFailureException,
176 MojoExecutionException
181 File dir = new File(outputDirectory);
183 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
186 Set<String> classes = new HashSet<String>();
189 AnnotationDB db = new AnnotationDB();
190 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
191 dirUrl = dir.toURI().toURL();
192 db.scanArchives(dirUrl);
193 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
194 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
195 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
196 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
197 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
198 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
200 catch (IOException e) {
201 getLog().error("Error while scanning!", e);
202 throw new MojoFailureException(e.getMessage());
204 if (classes.isEmpty())
205 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
207 Properties properties = new Properties();
209 /** Try to read configuration from properties-file */
211 File file = new File(hibernateProperties);
213 getLog().info("Reading properties from file " + hibernateProperties + "...");
214 properties.load(new FileInputStream(file));
217 getLog().info("Ignoring nonexistent properties-file " + hibernateProperties + "!");
219 catch (IOException e) {
220 getLog().error("Error while reading properties!", e);
221 throw new MojoExecutionException(e.getMessage());
224 /** Overwrite values from propertie-file or set if given */
225 if (driverClassName != null)
226 properties.setProperty("hibernate.connection.driver_class", driverClassName);
228 properties.setProperty("hibernate.connection.url", url);
229 if (username != null)
230 properties.setProperty("hibernate.connection.username", username);
231 if (password != null)
232 properties.setProperty("hibernate.connection.password", password);
233 if (hibernateDialect != null)
234 properties.setProperty("hibernate.dialect", hibernateDialect);
236 if (properties.isEmpty())
237 getLog().warn("No properties set!");
238 for (Entry<Object,Object> entry : properties.entrySet())
239 getLog().debug(entry.getKey() + " = " + entry.getValue());
241 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) {
247 getLog().debug("Dependency: " + classpathFiles.get(i));
248 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
250 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
252 catch (Exception e) {
253 getLog().error("Error while creating ClassLoader!", e);
254 throw new MojoExecutionException(e.getMessage());
257 Configuration config = new Configuration();
258 config.setProperties(properties);
260 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
261 for (String annotatedClass : classes) {
262 getLog().debug("Class " + annotatedClass);
263 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
266 catch (ClassNotFoundException e) {
267 getLog().error("Error while adding annotated classes!", e);
268 throw new MojoExecutionException(e.getMessage());
271 Target target = null;
273 target = Target.valueOf(this.target);
275 catch (IllegalArgumentException e) {
276 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
277 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
278 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
282 type = Type.valueOf(this.type);
284 catch (IllegalArgumentException e) {
285 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
286 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
287 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
290 Connection connection = null;
293 * The connection must be established outside of hibernate, because
294 * hibernate does not use the context-classloader of the current
295 * thread and, hence, would not be able to resolve the driver-class!
304 Class driverClass = classLoader.loadClass(driverClassName);
305 getLog().debug("Registering JDBC-driver " + driverClass.getName());
306 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
307 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
308 connection = DriverManager.getConnection(url, username, password);
312 catch (ClassNotFoundException e) {
313 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
314 throw new MojoExecutionException(e.getMessage());
316 catch (Exception e) {
317 getLog().error("Cannot establish connection to database!");
318 Enumeration<Driver> drivers = DriverManager.getDrivers();
319 if (!drivers.hasMoreElements())
320 getLog().error("No drivers registered!");
321 while (drivers.hasMoreElements())
322 getLog().debug("Driver: " + drivers.nextElement());
323 throw new MojoExecutionException(e.getMessage());
326 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
327 MavenLogAppender.startPluginLog(this);
330 * Change class-loader of current thread, so that hibernate can
331 * see all dependencies!
333 Thread.currentThread().setContextClassLoader(classLoader);
335 SchemaExport export = new SchemaExport(config, connection);
336 export.setOutputFile(outputFile);
337 export.setDelimiter(delimiter);
338 export.setFormat(format);
339 export.execute(target, type);
341 for (Object exception : export.getExceptions())
342 getLog().debug(exception.toString());
345 /** Stop Log-Capturing */
346 MavenLogAppender.endPluginLog(this);
348 /** Restore the old class-loader (TODO: is this really necessary?) */
349 Thread.currentThread().setContextClassLoader(contextClassLoader);
351 /** Close the connection */
355 catch (SQLException e) {
356 getLog().error("Error while closing connection: " + e.getMessage());
362 * Needed, because DriverManager won't pick up drivers, that were not
363 * loaded by the system-classloader!
365 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
367 static final class DriverProxy implements Driver {
369 private final Driver target;
371 DriverProxy(Driver target) {
372 if (target == null) {
373 throw new NullPointerException();
375 this.target = target;
378 public java.sql.Driver getTarget() {
383 public boolean acceptsURL(String url) throws SQLException {
384 return target.acceptsURL(url);
388 public java.sql.Connection connect(
389 String url, java.util.Properties info) throws SQLException {
390 return target.connect(url, info);
394 public int getMajorVersion() {
395 return target.getMajorVersion();
399 public int getMinorVersion() {
400 return target.getMinorVersion();
404 public DriverPropertyInfo[] getPropertyInfo(
405 String url, Properties info) throws SQLException {
406 return target.getPropertyInfo(url, info);
410 public boolean jdbcCompliant() {
411 return target.jdbcCompliant();
415 public String toString() {
416 return "Proxy: " + target;
420 public int hashCode() {
421 return target.hashCode();
425 public boolean equals(Object obj) {
426 if (!(obj instanceof DriverProxy)) {
429 DriverProxy other = (DriverProxy) obj;
430 return this.target.equals(other.target);