1 package de.juplo.plugins.hibernate;
4 import com.pyx4j.log4j.MavenLogAppender;
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.net.MalformedURLException;
11 import java.security.NoSuchAlgorithmException;
12 import java.util.Collections;
13 import java.util.HashSet;
14 import java.util.Iterator;
15 import java.util.LinkedHashSet;
16 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Properties;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 import javax.persistence.Embeddable;
24 import javax.persistence.Entity;
25 import javax.persistence.MappedSuperclass;
26 import javax.persistence.spi.PersistenceUnitTransactionType;
27 import org.apache.maven.artifact.Artifact;
28 import org.apache.maven.model.Resource;
29 import org.apache.maven.plugin.AbstractMojo;
30 import org.apache.maven.plugin.MojoExecutionException;
31 import org.apache.maven.plugin.MojoFailureException;
32 import org.apache.maven.project.MavenProject;
33 import org.hibernate.boot.MetadataBuilder;
34 import org.hibernate.boot.MetadataSources;
35 import org.hibernate.boot.cfgxml.internal.ConfigLoader;
36 import org.hibernate.boot.cfgxml.spi.LoadedConfig;
37 import org.hibernate.boot.cfgxml.spi.MappingReference;
38 import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
39 import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
40 import org.hibernate.boot.registry.BootstrapServiceRegistry;
41 import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
42 import org.hibernate.boot.registry.StandardServiceRegistry;
43 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
44 import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
45 import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
46 import org.hibernate.boot.registry.selector.spi.StrategySelector;
47 import org.hibernate.boot.spi.MetadataImplementor;
48 import static org.hibernate.cfg.AvailableSettings.DIALECT;
49 import static org.hibernate.cfg.AvailableSettings.DRIVER;
50 import static org.hibernate.cfg.AvailableSettings.FORMAT_SQL;
51 import static org.hibernate.cfg.AvailableSettings.HBM2DLL_CREATE_NAMESPACES;
52 import static org.hibernate.cfg.AvailableSettings.IMPLICIT_NAMING_STRATEGY;
53 import static org.hibernate.cfg.AvailableSettings.PASS;
54 import static org.hibernate.cfg.AvailableSettings.PHYSICAL_NAMING_STRATEGY;
55 import static org.hibernate.cfg.AvailableSettings.SHOW_SQL;
56 import static org.hibernate.cfg.AvailableSettings.USER;
57 import static org.hibernate.cfg.AvailableSettings.URL;
58 import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
59 import org.hibernate.internal.util.config.ConfigurationException;
60 import static org.hibernate.jpa.AvailableSettings.JDBC_DRIVER;
61 import static org.hibernate.jpa.AvailableSettings.JDBC_PASSWORD;
62 import static org.hibernate.jpa.AvailableSettings.JDBC_URL;
63 import static org.hibernate.jpa.AvailableSettings.JDBC_USER;
64 import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
65 import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
66 import org.hibernate.jpa.boot.spi.ProviderChecker;
67 import org.scannotation.AnnotationDB;
71 * Baseclass with common attributes and methods.
73 * @phase process-classes
75 * @requiresDependencyResolution runtime
77 public abstract class AbstractSchemaMojo extends AbstractMojo
79 public final static String EXPORT = "hibernate.schema.export";
80 public final static String DELIMITER = "hibernate.schema.delimiter";
81 public final static String OUTPUTDIRECTORY = "project.build.outputDirectory";
82 public final static String SCAN_CLASSES = "hibernate.schema.scan.classes";
83 public final static String SCAN_DEPENDENCIES = "hibernate.schema.scan.dependencies";
84 public final static String SCAN_TESTCLASSES = "hibernate.schema.scan.test_classes";
85 public final static String TEST_OUTPUTDIRECTORY = "project.build.testOutputDirectory";
86 public final static String SKIPPED = "hibernate.schema.skipped";
88 private final static Pattern SPLIT = Pattern.compile("[^,\\s]+");
90 private final Set<String> packages = new HashSet<String>();
95 * Only needed internally.
97 * @parameter property="project"
101 private MavenProject project;
106 * Only needed internally.
108 * @parameter property="project.build.directory"
112 String buildDirectory;
115 /** Parameters to configure the genaration of the SQL *********************/
118 * Export the database-schma to the database.
119 * If set to <code>false</code>, only the SQL-script is created and the
120 * database is not touched.
122 * <strong>Important:</strong>
123 * This configuration value can only be configured through the
124 * <code>pom.xml</code>, or by the definition of a system-property, because
125 * it is not known by Hibernate nor JPA and, hence, not picked up from
126 * their configuration!
128 * @parameter property="hibernate.schema.export" default-value="true"
136 * If set to <code>true</code>, the execution is skipped.
138 * A skipped execution is signaled via the maven-property
139 * <code>${hibernate.export.skipped}</code>.
141 * The execution is skipped automatically, if no modified or newly added
142 * annotated classes are found and the dialect was not changed.
144 * <strong>Important:</strong>
145 * This configuration value can only be configured through the
146 * <code>pom.xml</code>, or by the definition of a system-property, because
147 * it is not known by Hibernate nor JPA and, hence, not picked up from
148 * their configuration!
150 * @parameter property="hibernate.schema.skip" default-value="${maven.test.skip}"
153 private boolean skip;
158 * Force execution, even if no modified or newly added annotated classes
159 * where found and the dialect was not changed.
161 * <code>skip</code> takes precedence over <code>force</code>.
163 * <strong>Important:</strong>
164 * This configuration value can only be configured through the
165 * <code>pom.xml</code>, or by the definition of a system-property, because
166 * it is not known by Hibernate nor JPA and, hence, not picked up from
167 * their configuration!
169 * @parameter property="hibernate.schema.force" default-value="false"
172 private boolean force;
177 * @parameter property="hibernate.dialect"
180 private String dialect;
183 * Delimiter in output-file.
185 * <strong>Important:</strong>
186 * This configuration value can only be configured through the
187 * <code>pom.xml</code>, or by the definition of a system-property, because
188 * it is not known by Hibernate nor JPA and, hence, not picked up from
189 * their configuration!
191 * @parameter property="hibernate.schema.delimiter" default-value=";"
197 * Show the generated SQL in the command-line output.
199 * @parameter property="hibernate.show_sql"
205 * Format output-file.
207 * @parameter property="hibernate.format_sql"
213 * Specifies whether to automatically create also the database schema/catalog.
215 * @parameter property="hibernate.hbm2dll.create_namespaces" default-value="false"
218 Boolean createNamespaces;
221 * Implicit naming strategy
223 * @parameter property="hibernate.implicit_naming_strategy"
226 private String implicitNamingStrategy;
229 * Physical naming strategy
231 * @parameter property="hibernate.physical_naming_strategy"
234 private String physicalNamingStrategy;
237 * Wether the project should be scanned for annotated-classes, or not
239 * This parameter is intended to allow overwriting of the parameter
240 * <code>exclude-unlisted-classes</code> of a <code>persistence-unit</code>.
241 * If not specified, it defaults to <code>true</code>
243 * @parameter property="hibernate.schema.scan.classes"
246 private Boolean scanClasses;
249 * Classes-Directory to scan.
251 * This parameter defaults to the maven build-output-directory for classes.
252 * Additionally, all dependencies are scanned for annotated classes.
254 * <strong>Important:</strong>
255 * This configuration value can only be configured through the
256 * <code>pom.xml</code>, or by the definition of a system-property, because
257 * it is not known by Hibernate nor JPA and, hence, not picked up from
258 * their configuration!
260 * @parameter property="project.build.outputDirectory"
263 private String outputDirectory;
266 * Dependency-Scopes, that should be scanned for annotated classes.
268 * By default, only dependencies in the scope <code>compile</code> are
269 * scanned for annotated classes. Multiple scopes can be seperated by
270 * white space or commas.
272 * If you do not want any dependencies to be scanned for annotated
273 * classes, set this parameter to <code>none</code>.
275 * The plugin does not scan for annotated classes in transitive
276 * dependencies. If some of your annotated classes are hidden in a
277 * transitive dependency, you can simply add that dependency explicitly.
279 * @parameter property="hibernate.schema.scan.dependencies" default-value="compile"
282 private String scanDependencies;
285 * Whether to scan the test-branch of the project for annotated classes, or
288 * If this parameter is set to <code>true</code> the test-classes of the
289 * artifact will be scanned for hibernate-annotated classes additionally.
291 * <strong>Important:</strong>
292 * This configuration value can only be configured through the
293 * <code>pom.xml</code>, or by the definition of a system-property, because
294 * it is not known by Hibernate nor JPA and, hence, not picked up from
295 * their configuration!
297 * @parameter property="hibernate.schema.scan.test_classes" default-value="false"
300 private Boolean scanTestClasses;
303 * Test-Classes-Directory to scan.
305 * This parameter defaults to the maven build-output-directory for
308 * This parameter is only used, when <code>scanTestClasses</code> is set
309 * to <code>true</code>!
311 * <strong>Important:</strong>
312 * This configuration value can only be configured through the
313 * <code>pom.xml</code>, or by the definition of a system-property, because
314 * it is not known by Hibernate nor JPA and, hence, not picked up from
315 * their configuration!
317 * @parameter property="project.build.testOutputDirectory"
320 private String testOutputDirectory;
323 /** Conection parameters *************************************************/
328 * @parameter property="hibernate.connection.driver_class"
331 private String driver;
336 * @parameter property="hibernate.connection.url"
344 * @parameter property="hibernate.connection.username"
347 private String username;
352 * @parameter property="hibernate.connection.password"
355 private String password;
358 /** Parameters to locate configuration sources ****************************/
361 * Path to a file or name of a ressource with hibernate properties.
362 * If this parameter is specified, the plugin will try to load configuration
363 * values from a file with the given path or a ressource on the classpath with
364 * the given name. If both fails, the execution of the plugin will fail.
366 * If this parameter is not set the plugin will load configuration values
367 * from a ressource named <code>hibernate.properties</code> on the classpath,
368 * if it is present, but will not fail if there is no such ressource.
370 * During ressource-lookup, the test-classpath takes precedence.
375 private String hibernateProperties;
378 * Path to Hibernate configuration file (.cfg.xml).
379 * If this parameter is specified, the plugin will try to load configuration
380 * values from a file with the given path or a ressource on the classpath with
381 * the given name. If both fails, the execution of the plugin will fail.
383 * If this parameter is not set the plugin will load configuration values
384 * from a ressource named <code>hibernate.cfg.xml</code> on the classpath,
385 * if it is present, but will not fail if there is no such ressource.
387 * During ressource-lookup, the test-classpath takes precedence.
389 * Settings in this file will overwrite settings in the properties file.
394 private String hibernateConfig;
397 * Name of the persistence-unit.
398 * If this parameter is specified, the plugin will try to load configuration
399 * values from a persistence-unit with the specified name. If no such
400 * persistence-unit can be found, the plugin will throw an exception.
402 * If this parameter is not set and there is only one persistence-unit
403 * available, that unit will be used automatically. But if this parameter is
404 * not set and there are multiple persistence-units available on,
405 * the class-path, the execution of the plugin will fail.
407 * Settings in this file will overwrite settings in the properties or the
408 * configuration file.
413 private String persistenceUnit;
416 * List of Hibernate-Mapping-Files (XML).
417 * Multiple files can be separated with white-spaces and/or commas.
419 * @parameter property="hibernate.mapping"
422 private String mappings;
426 public final void execute(String filename)
428 MojoFailureException,
429 MojoExecutionException
433 getLog().info("Execution of hibernate-maven-plugin was skipped!");
434 project.getProperties().setProperty(SKIPPED, "true");
438 ModificationTracker tracker;
441 tracker = new ModificationTracker(buildDirectory, filename, getLog());
443 catch (NoSuchAlgorithmException e)
445 throw new MojoFailureException("Digest-Algorithm MD5 is missing!", e);
448 SimpleConnectionProvider connectionProvider =
449 new SimpleConnectionProvider(getLog());
453 /** Start extended logging */
454 MavenLogAppender.startPluginLog(this);
456 /** Load checksums for old mapping and configuration */
459 /** Create the ClassLoader */
460 MutableClassLoader classLoader = createClassLoader();
462 /** Create a BootstrapServiceRegistry with the created ClassLoader */
463 BootstrapServiceRegistry bootstrapServiceRegitry =
464 new BootstrapServiceRegistryBuilder()
465 .applyClassLoader(classLoader)
467 ClassLoaderService classLoaderService =
468 bootstrapServiceRegitry.getService(ClassLoaderService.class);
470 Properties properties = new Properties();
471 ConfigLoader configLoader = new ConfigLoader(bootstrapServiceRegitry);
473 /** Loading and merging configuration */
474 properties.putAll(loadProperties(configLoader));
475 LoadedConfig config = loadConfig(configLoader);
477 properties.putAll(config.getConfigurationValues());
478 ParsedPersistenceXmlDescriptor unit =
479 loadPersistenceUnit(classLoaderService, properties);
481 properties.putAll(unit.getProperties());
483 /** Overwriting/Completing configuration */
484 configure(properties, tracker);
486 /** Check configuration for modifications */
487 if(tracker.track(properties))
488 getLog().debug("Configuration has changed.");
490 getLog().debug("Configuration unchanged.");
492 /** Configure Hibernate */
493 StandardServiceRegistry serviceRegistry =
494 new StandardServiceRegistryBuilder(bootstrapServiceRegitry)
495 .applySettings(properties)
496 .addService(ConnectionProvider.class, connectionProvider)
498 MetadataSources sources = new MetadataSources(serviceRegistry);
500 /** Add the remaining class-path-elements */
501 completeClassPath(classLoader);
503 /** Apply mappings from hibernate-configuration, if present */
506 for (MappingReference mapping : config.getMappingReferences())
507 mapping.apply(sources);
513 /** No persistent unit: default behaviour */
514 if (scanClasses == null)
516 Set<URL> urls = new HashSet<URL>();
518 addRoot(urls, outputDirectory);
520 addRoot(urls, testOutputDirectory);
521 addDependencies(urls);
522 classes = scanUrls(urls);
526 /** Follow configuration in persisten unit */
527 if (scanClasses == null)
528 scanClasses = !unit.isExcludeUnlistedClasses();
529 Set<URL> urls = new HashSet<URL>();
533 * Scan the root of the persiten unit and configured jars for
536 urls.add(unit.getPersistenceUnitRootUrl());
537 for (URL url : unit.getJarFileUrls())
541 addRoot(urls, testOutputDirectory);
542 classes = scanUrls(urls);
543 for (String className : unit.getManagedClassNames())
544 classes.add(className);
546 * Add mappings from the default mapping-file
547 * <code>META-INF/orm.xml</code>, if present
551 InputStream is = classLoader.getResourceAsStream("META-INF/orm.xml");
554 getLog().info("Adding default JPA-XML-mapping from META-INF/orm.xml");
555 tracker.track("META-INF/orm.xml", is);
556 sources.addResource("META-INF/orm.xml");
559 * Add mappings from files, that are explicitly configured in the
562 for (String mapping : unit.getMappingFileNames())
564 getLog().info("Adding explicitly configured mapping from " + mapping);
565 tracker.track(mapping, classLoader.getResourceAsStream(mapping));
566 sources.addResource(mapping);
569 catch (IOException e)
571 throw new MojoFailureException("Error reading XML-mappings", e);
575 /** Add the configured/collected annotated classes */
576 for (String className : classes)
577 addAnnotated(className, sources, classLoaderService, tracker);
579 /** Add explicitly configured classes */
580 addMappings(sources, tracker);
582 /** Skip execution, if mapping and configuration is unchanged */
583 if (!tracker.modified())
586 "Mapping and configuration unchanged."
589 getLog().info("Schema generation is forced!");
592 getLog().info("Skipping schema generation!");
593 project.getProperties().setProperty(SKIPPED, "true");
599 /** Create a connection, if sufficient configuration infromation is available */
600 connectionProvider.open(classLoaderService, properties);
602 MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
604 StrategySelector strategySelector =
605 serviceRegistry.getService(StrategySelector.class);
607 if (properties.containsKey(IMPLICIT_NAMING_STRATEGY))
609 metadataBuilder.applyImplicitNamingStrategy(
610 strategySelector.resolveStrategy(
611 ImplicitNamingStrategy.class,
612 properties.getProperty(IMPLICIT_NAMING_STRATEGY)
617 if (properties.containsKey(PHYSICAL_NAMING_STRATEGY))
619 metadataBuilder.applyPhysicalNamingStrategy(
620 strategySelector.resolveStrategy(
621 PhysicalNamingStrategy.class,
622 properties.getProperty(PHYSICAL_NAMING_STRATEGY)
628 * Change class-loader of current thread.
629 * This is necessary, because still not all parts of Hibernate 5 use
630 * the newly introduced ClassLoaderService and will fail otherwise!
632 Thread thread = Thread.currentThread();
633 ClassLoader contextClassLoader = thread.getContextClassLoader();
636 thread.setContextClassLoader(classLoader);
637 build((MetadataImplementor)metadataBuilder.build());
641 thread.setContextClassLoader(contextClassLoader);
646 /** Remember mappings and configuration */
649 /** Close the connection - if one was opened */
650 connectionProvider.close();
652 /** Stop Log-Capturing */
653 MavenLogAppender.endPluginLog(this);
658 abstract void build(MetadataImplementor metadata)
660 MojoFailureException,
661 MojoExecutionException;
664 private MutableClassLoader createClassLoader() throws MojoExecutionException
668 getLog().debug("Creating ClassLoader for project-dependencies...");
669 LinkedHashSet<URL> urls = new LinkedHashSet<URL>();
672 file = new File(testOutputDirectory);
675 getLog().info("Creating test-output-directory: " + testOutputDirectory);
678 urls.add(file.toURI().toURL());
680 file = new File(outputDirectory);
683 getLog().info("Creating output-directory: " + outputDirectory);
686 urls.add(file.toURI().toURL());
688 return new MutableClassLoader(urls, getLog());
692 getLog().error("Error while creating ClassLoader!", e);
693 throw new MojoExecutionException(e.getMessage());
697 private void completeClassPath(MutableClassLoader classLoader)
699 MojoExecutionException
703 getLog().debug("Completing class-paths of the ClassLoader for project-dependencies...");
704 List<String> classpathFiles = project.getCompileClasspathElements();
706 classpathFiles.addAll(project.getTestClasspathElements());
707 LinkedHashSet<URL> urls = new LinkedHashSet<URL>();
708 for (String pathElement : classpathFiles)
710 getLog().debug("Dependency: " + pathElement);
711 urls.add(new File(pathElement).toURI().toURL());
713 classLoader.add(urls);
717 getLog().error("Error while creating ClassLoader!", e);
718 throw new MojoExecutionException(e.getMessage());
722 private Map loadProperties(ConfigLoader configLoader)
724 MojoExecutionException
726 /** Try to read configuration from properties-file */
727 if (hibernateProperties == null)
731 return configLoader.loadProperties("hibernate.properties");
733 catch (ConfigurationException e)
735 getLog().debug(e.getMessage());
736 return Collections.EMPTY_MAP;
743 File file = new File(hibernateProperties);
746 getLog().info("Reading settings from file " + hibernateProperties + "...");
747 return configLoader.loadProperties(file);
750 return configLoader.loadProperties(hibernateProperties);
752 catch (ConfigurationException e)
754 getLog().error("Error while reading properties!", e);
755 throw new MojoExecutionException(e.getMessage());
760 private LoadedConfig loadConfig(ConfigLoader configLoader)
761 throws MojoExecutionException
763 /** Try to read configuration from configuration-file */
764 if (hibernateConfig == null)
768 return configLoader.loadConfigXmlResource("hibernate.cfg.xml");
770 catch (ConfigurationException e)
772 getLog().debug(e.getMessage());
780 File file = new File(hibernateConfig);
783 getLog().info("Reading configuration from file " + hibernateConfig + "...");
784 return configLoader.loadConfigXmlFile(file);
788 return configLoader.loadConfigXmlResource(hibernateConfig);
791 catch (ConfigurationException e)
793 getLog().error("Error while reading configuration!", e);
794 throw new MojoExecutionException(e.getMessage());
799 private void configure(Properties properties, ModificationTracker tracker)
800 throws MojoFailureException
803 * Special treatment for the configuration-value "export": if it is
804 * switched to "true", the genearation fo the schema should be forced!
806 if (tracker.check(EXPORT, export.toString()) && export)
810 * Configure the generation of the SQL.
811 * Overwrite values from properties-file if the configuration parameter is
812 * known to Hibernate.
814 dialect = configure(properties, dialect, DIALECT);
815 tracker.track(DELIMITER, delimiter); // << not reflected in hibernate configuration!
816 format = configure(properties, format, FORMAT_SQL);
817 createNamespaces = configure(properties, createNamespaces, HBM2DLL_CREATE_NAMESPACES);
818 implicitNamingStrategy = configure(properties, implicitNamingStrategy, IMPLICIT_NAMING_STRATEGY);
819 physicalNamingStrategy = configure(properties, physicalNamingStrategy, PHYSICAL_NAMING_STRATEGY);
820 tracker.track(OUTPUTDIRECTORY, outputDirectory); // << not reflected in hibernate configuration!
821 tracker.track(SCAN_DEPENDENCIES, scanDependencies); // << not reflected in hibernate configuration!
822 tracker.track(SCAN_TESTCLASSES, scanTestClasses.toString()); // << not reflected in hibernate configuration!
823 tracker.track(TEST_OUTPUTDIRECTORY, testOutputDirectory); // << not reflected in hibernate configuration!
826 * Special treatment for the configuration-value "show": a change of its
827 * configured value should not lead to a regeneration of the database
831 show = Boolean.valueOf(properties.getProperty(SHOW_SQL));
833 properties.setProperty(SHOW_SQL, show.toString());
836 * Configure the connection parameters.
837 * Overwrite values from properties-file.
839 driver = configure(properties, driver, DRIVER, JDBC_DRIVER);
840 url = configure(properties, url, URL, JDBC_URL);
841 username = configure(properties, username, USER, JDBC_USER);
842 password = configure(properties, password, PASS, JDBC_PASSWORD);
844 if (properties.isEmpty())
846 getLog().error("No properties set!");
847 throw new MojoFailureException("Hibernate configuration is missing!");
850 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
851 for (Entry<Object,Object> entry : properties.entrySet())
852 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
855 private String configure(
856 Properties properties,
859 String alternativeKey
862 value = configure(properties, value, key);
864 return properties.getProperty(alternativeKey);
866 if (properties.containsKey(alternativeKey))
869 "Ignoring property " + alternativeKey + "=" +
870 properties.getProperty(alternativeKey) + " in favour for property " +
871 key + "=" + properties.getProperty(key)
873 properties.remove(alternativeKey);
875 return properties.getProperty(alternativeKey);
878 private String configure(Properties properties, String value, String key)
882 if (properties.containsKey(key))
884 "Overwriting property " + key + "=" + properties.getProperty(key) +
885 " with the value " + value
888 getLog().debug("Using the value " + value + " for property " + key);
889 properties.setProperty(key, value);
891 return properties.getProperty(key);
894 private boolean configure(Properties properties, Boolean value, String key)
898 if (properties.containsKey(key))
900 "Overwriting property " + key + "=" + properties.getProperty(key) +
901 " with the value " + value
904 getLog().debug("Using the value " + value + " for property " + key);
905 properties.setProperty(key, value.toString());
907 return Boolean.valueOf(properties.getProperty(key));
910 private void addMappings(MetadataSources sources, ModificationTracker tracker)
911 throws MojoFailureException
913 getLog().debug("Adding explicitly configured mappings...");
914 if (mappings != null)
918 for (String filename : mappings.split("[\\s,]+"))
920 // First try the filename as absolute/relative path
921 File file = new File(filename);
924 // If the file was not found, search for it in the resource-directories
925 for (Resource resource : project.getResources())
927 file = new File(resource.getDirectory() + File.separator + filename);
934 if (file.isDirectory())
935 // TODO: add support to read all mappings under a directory
936 throw new MojoFailureException(file.getAbsolutePath() + " is a directory");
937 if (tracker.track(filename, new FileInputStream(file)))
938 getLog().debug("Found new or modified mapping-file: " + filename);
940 getLog().debug("Mapping-file unchanged: " + filename);
942 sources.addFile(file);
945 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
948 catch (IOException e)
950 throw new MojoFailureException("Cannot calculate MD5 sums!", e);
955 private void addRoot(Set<URL> urls, String path) throws MojoFailureException
959 File dir = new File(outputDirectory);
962 getLog().info("Adding " + dir.getAbsolutePath() + " to the list of roots to scan...");
963 urls.add(dir.toURI().toURL());
966 catch (MalformedURLException e)
968 getLog().error("error while adding the project-root to the list of roots to scan!", e);
969 throw new MojoFailureException(e.getMessage());
973 private void addDependencies(Set<URL> urls) throws MojoFailureException
977 if (scanDependencies != null)
979 Matcher matcher = SPLIT.matcher(scanDependencies);
980 while (matcher.find())
982 getLog().info("Adding dependencies from scope " + matcher.group() + " to the list of roots to scan");
983 for (Artifact artifact : project.getDependencyArtifacts())
985 if (!artifact.getScope().equalsIgnoreCase(matcher.group()))
987 if (artifact.getFile() == null)
989 getLog().warn("Cannot add dependency " + artifact.getId() + ": no JAR-file available!");
992 getLog().info("Adding dependencies from scope " + artifact.getId() + " to the list of roots to scan");
993 urls.add(artifact.getFile().toURI().toURL());
998 catch (MalformedURLException e)
1000 getLog().error("Error while adding dependencies to the list of roots to scan!", e);
1001 throw new MojoFailureException(e.getMessage());
1005 private Set<String> scanUrls(Set<URL> scanRoots)
1007 MojoFailureException
1011 AnnotationDB db = new AnnotationDB();
1012 for (URL root : scanRoots)
1013 db.scanArchives(root);
1015 Set<String> classes = new HashSet<String>();
1016 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
1017 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
1018 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
1019 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
1020 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
1021 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
1027 getLog().error("Error while scanning!", e);
1028 throw new MojoFailureException(e.getMessage());
1032 private void addAnnotated(
1034 MetadataSources sources,
1035 ClassLoaderService classLoaderService,
1036 ModificationTracker tracker
1039 MojoFailureException,
1040 MojoExecutionException
1044 getLog().info("Adding annotated resource: " + name);
1049 Class<?> annotatedClass = classLoaderService.classForName(name);
1050 String resourceName = annotatedClass.getName();
1052 resourceName.substring(
1053 resourceName.lastIndexOf(".") + 1,
1054 resourceName.length()
1056 InputStream is = annotatedClass.getResourceAsStream(resourceName);
1057 if (tracker.track(name, is))
1058 getLog().debug("New or modified class: " + name);
1060 getLog().debug("Unchanged class: " + name);
1061 sources.addAnnotatedClass(annotatedClass);
1062 packageName = annotatedClass.getPackage().getName();
1064 catch(ClassLoadingException e)
1069 if (!packages.contains(packageName))
1071 String resource = packageName.replace('.', '/') + "/package-info.class";
1072 InputStream is = classLoaderService.locateResourceStream(resource);
1075 // No compiled package-info available: no package-level annotations!
1076 getLog().debug("Package " + packageName + " is not annotated.");
1080 if (tracker.track(packageName, is))
1081 getLog().debug("New or modified package: " + packageName);
1083 getLog().debug("Unchanged package: " + packageName);
1084 getLog().info("Adding annotations from package " + packageName);
1085 sources.addPackage(packageName);
1087 packages.add(packageName);
1092 getLog().error("Error while adding the annotated class " + name, e);
1093 throw new MojoFailureException(e.getMessage());
1097 private ParsedPersistenceXmlDescriptor loadPersistenceUnit(
1098 ClassLoaderService classLoaderService,
1099 Properties properties
1102 MojoFailureException
1104 PersistenceXmlParser parser =
1105 new PersistenceXmlParser(
1107 PersistenceUnitTransactionType.RESOURCE_LOCAL
1110 List<ParsedPersistenceXmlDescriptor> units = parser.doResolve(properties);
1112 if (persistenceUnit == null)
1114 switch (units.size())
1117 getLog().info("Found no META-INF/persistence.xml.");
1120 getLog().info("Using persistence-unit " + units.get(0).getName());
1121 return units.get(0);
1123 StringBuilder builder = new StringBuilder();
1124 builder.append("No name provided and multiple persistence units found: ");
1125 Iterator<ParsedPersistenceXmlDescriptor> it = units.iterator();
1126 builder.append(it.next().getName());
1127 while (it.hasNext())
1129 builder.append(", ");
1130 builder.append(it.next().getName());
1132 builder.append('.');
1133 throw new MojoFailureException(builder.toString());
1137 for (ParsedPersistenceXmlDescriptor unit : units)
1139 getLog().debug("Found persistence-unit " + unit.getName());
1140 if (!unit.getName().equals(persistenceUnit))
1143 // See if we (Hibernate) are the persistence provider
1144 if (!ProviderChecker.isProvider(unit, properties))
1146 getLog().debug("Wrong provider: " + unit.getProviderClassName());
1150 getLog().info("Using persistence-unit " + unit.getName());
1154 throw new MojoFailureException("Could not find persistence-unit " + persistenceUnit);