diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/cfg/CfgExporter.java b/orm/src/main/java/org/hibernate/tool/internal/export/cfg/CfgExporter.java
index e13f09941c..918c8922f2 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/cfg/CfgExporter.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/cfg/CfgExporter.java
@@ -23,7 +23,6 @@
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
@@ -42,162 +41,147 @@
*/
public class CfgExporter extends AbstractExporter {
- private Writer output;
+ private Writer output;
private Properties customProperties = new Properties();
-
- public Properties getCustomProperties() {
- return customProperties;
- }
-
- public void setCustomProperties(Properties customProperties) {
- this.customProperties = customProperties;
- }
-
- public Writer getOutput() {
- return output;
- }
-
- public void setOutput(Writer output) {
- this.output = output;
- }
-
- /* (non-Javadoc)
- * @see org.hibernate.tool.hbm2x.Exporter#finish()
- */
- public void doStart() {
- PrintWriter pw = null;
- File file = null;
- try {
- if(output==null) {
- file = new File(getOutputDirectory(), "hibernate.cfg.xml");
- getTemplateHelper().ensureExistence(file);
- pw = new PrintWriter(new FileWriter(file) );
- getArtifactCollector().addFile(file, "cfg.xml");
- }
- else {
- pw = new PrintWriter(output);
+
+ public Properties getCustomProperties() {
+ return customProperties;
+ }
+
+ public void setCustomProperties(Properties customProperties) {
+ this.customProperties = customProperties;
+ }
+
+ public Writer getOutput() {
+ return output;
+ }
+
+ public void setOutput(Writer output) {
+ this.output = output;
+ }
+
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.hbm2x.Exporter#finish()
+ */
+ public void doStart() {
+ PrintWriter pw = null;
+ File file;
+ try {
+ if(output==null) {
+ file = new File(getOutputDirectory(), "hibernate.cfg.xml");
+ getTemplateHelper().ensureExistence(file);
+ pw = new PrintWriter(new FileWriter(file) );
+ getArtifactCollector().addFile(file, "cfg.xml");
+ }
+ else {
+ pw = new PrintWriter(output);
+ }
+
+
+ pw.println( """
+
+ \r
+ """ );
+
+ boolean ejb3 = Boolean.parseBoolean( (String) getProperties().get( "ejb3" ) );
+
+ Map");
+
+ }
+
+ catch (IOException e) {
+ throw new RuntimeException("Problems while creating hibernate.cfg.xml", e);
+ }
+ finally {
+ if(pw!=null) {
+ pw.flush();
+ pw.close();
+ }
}
-
-
- pw.println("\n" +
- "\r\n" +
- "");
-
- boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue();
-
- Map props = new TreeMap();
- if (getProperties() != null) {
- props.putAll(getProperties());
+
+ }
+
+ private void dump(PrintWriter pw, boolean useClass, PersistentClass element) {
+ if(useClass) {
+ pw.println("");
}
- if(customProperties!=null) {
- props.putAll(customProperties);
+ else {
+ pw.println("");
}
-
- String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME);
- pw.println(" ");
-
- Map ignoredProperties = new HashMap();
- ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null);
- ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" );
- ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null );
- ignoredProperties.put(Environment.TRANSACTION_COORDINATOR_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup");
-
- Set> set = props.entrySet();
- Iterator> iterator = set.iterator();
- while (iterator.hasNext() ) {
- Entry element = iterator.next();
- String key = (String) element.getKey();
- if(ignoredProperties.containsKey( key )) {
- Object ignoredValue = ignoredProperties.get( key );
- if(ignoredValue == null || element.getValue().equals(ignoredValue)) {
- continue;
- }
- }
- if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml
- pw.println(" " + forXML(element.getValue().toString()) + "");
+
+ for ( Subclass value : element.getDirectSubclasses() ) {
+ dump( pw, useClass, value );
+ }
+
+ }
+
+ private String getMappingFileResource(PersistentClass element) {
+
+ return element.getClassName().replace('.', '/') + ".hbm.xml";
+ }
+
+ public String getName() {
+ return "cfg2cfgxml";
+ }
+
+ public static String forXML(String text) {
+ if (text == null) return null;
+ final StringBuilder result = new StringBuilder();
+ char[] chars = text.toCharArray();
+ for ( char character : chars ) {
+ if ( character == '<' ) {
+ result.append( "<" );
+ }
+ else if ( character == '>' ) {
+ result.append( ">" );
+ }
+ else {
+ result.append( character );
}
}
-
- if(getMetadata()!=null) {
- Iterator classMappings = getMetadata().getEntityBindings().iterator();
- while (classMappings.hasNext() ) {
- PersistentClass element = classMappings.next();
- if(element instanceof RootClass) {
- dump(pw, ejb3, element);
- }
- }
- }
- pw.println(" \r\n" +
- "");
-
- }
-
- catch (IOException e) {
- throw new RuntimeException("Problems while creating hibernate.cfg.xml", e);
- }
- finally {
- if(pw!=null) {
- pw.flush();
- pw.close();
- }
- }
-
- }
-
- /**
- * @param pw
- * @param element
- */
- private void dump(PrintWriter pw, boolean useClass, PersistentClass element) {
- if(useClass) {
- pw.println("");
- } else {
- pw.println("");
- }
-
- Iterator directSubclasses = element.getDirectSubclasses().iterator();
- while (directSubclasses.hasNext() ) {
- PersistentClass subclass = (PersistentClass)directSubclasses.next();
- dump(pw, useClass, subclass);
- }
-
- }
-
- /**
- * @param element
- * @return
- */
- private String getMappingFileResource(PersistentClass element) {
-
- return element.getClassName().replace('.', '/') + ".hbm.xml";
- }
-
- public String getName() {
- return "cfg2cfgxml";
- }
-
- /**
- *
- * @param text
- * @return String with escaped [<,>] special characters.
- */
- public static String forXML(String text) {
- if (text == null) return null;
- final StringBuilder result = new StringBuilder();
- char[] chars = text.toCharArray();
- for (int i = 0; i < chars.length; i++){
- char character = chars[i];
- if (character == '<') {
- result.append("<");
- } else if (character == '>'){
- result.append(">");
- } else {
- result.append(character);
- }
- }
- return result.toString();
- }
-
+ return result.toString();
+ }
+
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/common/ConfigurationNavigator.java b/orm/src/main/java/org/hibernate/tool/internal/export/common/ConfigurationNavigator.java
index 2206681950..d536f487fc 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/common/ConfigurationNavigator.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/common/ConfigurationNavigator.java
@@ -34,54 +34,49 @@
*/
public class ConfigurationNavigator {
- private static final Logger log = Logger.getLogger(ConfigurationNavigator.class);
-
- /**
- * @param clazz
- */
- public static void collectComponents(Map components, PersistentClass clazz) {
- Iterator iter = new Cfg2JavaTool().getPOJOClass(clazz).getAllPropertiesIterator();
- collectComponents( components, iter );
- }
+ private static final Logger log = Logger.getLogger(ConfigurationNavigator.class);
- public static void collectComponents(Map components, POJOClass clazz) {
- Iterator iter = clazz.getAllPropertiesIterator();
- collectComponents( components, iter );
- }
-
- private static void collectComponents(Map components, Iterator iter) {
- while(iter.hasNext()) {
- Property property = iter.next();
- if (!"embedded".equals(property.getPropertyAccessorName()) && // HBX-267, embedded property for should not be generated as component.
- property.getValue() instanceof Component) {
- Component comp = (Component) property.getValue();
- addComponent( components, comp );
- }
- else if (property.getValue() instanceof Collection) {
- // compisite-element in collection
- Collection collection = (Collection) property.getValue();
- if ( collection.getElement() instanceof Component) {
- Component comp = (Component) collection.getElement();
- addComponent(components, comp);
- }
- }
- }
- }
+ public static void collectComponents(Map components, PersistentClass clazz) {
+ Iterator iter = new Cfg2JavaTool().getPOJOClass(clazz).getAllPropertiesIterator();
+ collectComponents( components, iter );
+ }
+
+ public static void collectComponents(Map components, POJOClass clazz) {
+ Iterator iter = clazz.getAllPropertiesIterator();
+ collectComponents( components, iter );
+ }
+
+ private static void collectComponents(Map components, Iterator iter) {
+ while(iter.hasNext()) {
+ Property property = iter.next();
+ if (!"embedded".equals(property.getPropertyAccessorName()) && // HBX-267, embedded property for should not be generated as component.
+ property.getValue() instanceof Component comp ) {
+ addComponent( components, comp );
+ }
+ else if ( property.getValue() instanceof Collection collection ) {
+ // compisite-element in collection
+ if ( collection.getElement() instanceof Component comp ) {
+ addComponent(components, comp);
+ }
+ }
+ }
+ }
+
+ private static void addComponent(Map components, Component comp) {
+ if(!comp.isDynamic()) {
+ Component existing = components.put(
+ comp.getComponentClassName(),
+ comp);
+ if(existing!=null) {
+ log.warn("Component " + existing.getComponentClassName() + " found more than once! Will only generate the last found.");
+ }
+ }
+ else {
+ log.debug("dynamic-component found. Ignoring it as a component, but will collect any embedded components.");
+ }
+ collectComponents(
+ components,
+ new ComponentPOJOClass(comp, new Cfg2JavaTool()).getAllPropertiesIterator());
+ }
- private static void addComponent(Map components, Component comp) {
- if(!comp.isDynamic()) {
- Component existing = (Component) components.put(
- comp.getComponentClassName(),
- comp);
- if(existing!=null) {
- log.warn("Component " + existing.getComponentClassName() + " found more than once! Will only generate the last found.");
- }
- } else {
- log.debug("dynamic-component found. Ignoring it as a component, but will collect any embedded components.");
- }
- collectComponents(
- components,
- new ComponentPOJOClass(comp, new Cfg2JavaTool()).getAllPropertiesIterator());
- }
-
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/common/DefaultArtifactCollector.java b/orm/src/main/java/org/hibernate/tool/internal/export/common/DefaultArtifactCollector.java
index 858dd0d24d..c06e06b369 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/common/DefaultArtifactCollector.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/common/DefaultArtifactCollector.java
@@ -21,7 +21,6 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -38,77 +37,74 @@
*/
public class DefaultArtifactCollector implements ArtifactCollector {
- final protected Map> files = new HashMap>();
+ final protected Map> files = new HashMap<>();
- /* (non-Javadoc)
- * @see org.hibernate.tool.internal.export.ArtifactCollector#addFile(java.io.File, java.lang.String)
- */
- @Override
- public void addFile(File file, String type) {
- List existing = files.get(type);
- if (existing == null) {
- existing = new ArrayList();
- files.put(type, existing);
- }
- existing.add(file);
- }
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.internal.export.ArtifactCollector#addFile(java.io.File, java.lang.String)
+ */
+ @Override
+ public void addFile(File file, String type) {
+ List existing = files.computeIfAbsent( type, k -> new ArrayList<>() );
+ existing.add(file);
+ }
- /* (non-Javadoc)
- * @see org.hibernate.tool.internal.export.ArtifactCollector#getFileCount(java.lang.String)
- */
- @Override
- public int getFileCount(String type) {
- List existing = files.get(type);
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.internal.export.ArtifactCollector#getFileCount(java.lang.String)
+ */
+ @Override
+ public int getFileCount(String type) {
+ List existing = files.get(type);
- return (existing == null) ? 0 : existing.size();
- }
+ return (existing == null) ? 0 : existing.size();
+ }
- /* (non-Javadoc)
- * @see org.hibernate.tool.internal.export.ArtifactCollector#getFiles(java.lang.String)
- */
- @Override
- public File[] getFiles(String type) {
- List existing = files.get(type);
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.internal.export.ArtifactCollector#getFiles(java.lang.String)
+ */
+ @Override
+ public File[] getFiles(String type) {
+ List existing = files.get(type);
- if (existing == null) {
- return new File[0];
- } else {
- return (File[]) existing.toArray(new File[existing.size()]);
- }
- }
+ if (existing == null) {
+ return new File[0];
+ }
+ else {
+ return existing.toArray( new File[0] );
+ }
+ }
- /* (non-Javadoc)
- * @see org.hibernate.tool.internal.export.ArtifactCollector#getFileTypes()
- */
- @Override
- public Set getFileTypes() {
- return files.keySet();
- }
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.internal.export.ArtifactCollector#getFileTypes()
+ */
+ @Override
+ public Set getFileTypes() {
+ return files.keySet();
+ }
- /* (non-Javadoc)
- * @see org.hibernate.tool.internal.export.ArtifactCollector#formatFiles()
- */
- @Override
- public void formatFiles() {
+ /* (non-Javadoc)
+ * @see org.hibernate.tool.internal.export.ArtifactCollector#formatFiles()
+ */
+ @Override
+ public void formatFiles() {
- formatXml("xml");
- formatXml("hbm.xml");
- formatXml("cfg.xml");
+ formatXml("xml");
+ formatXml("hbm.xml");
+ formatXml("cfg.xml");
- }
+ }
- private void formatXml(String type) {
- List list = files.get(type);
- if (list != null && !list.isEmpty()) {
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- File xmlFile = iter.next();
- try {
- XMLPrettyPrinter.prettyPrintFile(xmlFile);
- } catch (IOException e) {
- throw new RuntimeException("Could not format XML file: " + xmlFile, e);
- }
- }
- }
- }
+ private void formatXml(String type) {
+ List list = files.get(type);
+ if (list != null && !list.isEmpty()) {
+ for ( File xmlFile : list ) {
+ try {
+ XMLPrettyPrinter.prettyPrintFile( xmlFile );
+ }
+ catch (IOException e) {
+ throw new RuntimeException( "Could not format XML file: " + xmlFile, e );
+ }
+ }
+ }
+ }
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/common/GenericExporter.java b/orm/src/main/java/org/hibernate/tool/internal/export/common/GenericExporter.java
index 6a79ea8046..cd752f8c4a 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/common/GenericExporter.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/common/GenericExporter.java
@@ -33,153 +33,153 @@
public class GenericExporter extends AbstractExporter {
-
- static abstract class ModelIterator {
- abstract void process(GenericExporter ge);
- }
-
- static Map modelIterators = new HashMap();
- static {
- modelIterators.put( "configuration", new ModelIterator() {
- void process(GenericExporter ge) {
- TemplateProducer producer =
- new TemplateProducer(
- ge.getTemplateHelper(),
- ge.getArtifactCollector());
- producer.produce(
- new HashMap(),
- ge.getTemplateName(),
- new File(ge.getOutputDirectory(),ge.getFilePattern()),
- ge.getTemplateName(),
- "Configuration");
- }
- });
- modelIterators.put("entity", new ModelIterator() {
- void process(GenericExporter ge) {
- Iterator> iterator =
- ge.getCfg2JavaTool().getPOJOIterator(
- ge.getMetadata().getEntityBindings().iterator());
- Map additionalContext = new HashMap();
- while ( iterator.hasNext() ) {
- POJOClass element = (POJOClass) iterator.next();
- ge.exportPersistentClass( additionalContext, element );
- }
- }
- });
- modelIterators.put("component", new ModelIterator() {
-
- void process(GenericExporter ge) {
- Map components = new HashMap();
-
- Iterator> iterator =
- ge.getCfg2JavaTool().getPOJOIterator(
- ge.getMetadata().getEntityBindings().iterator());
- Map additionalContext = new HashMap();
- while ( iterator.hasNext() ) {
- POJOClass element = (POJOClass) iterator.next();
- ConfigurationNavigator.collectComponents(components, element);
- }
-
- iterator = components.values().iterator();
- while ( iterator.hasNext() ) {
- Component component = (Component) iterator.next();
- ComponentPOJOClass element = new ComponentPOJOClass(component,ge.getCfg2JavaTool());
- ge.exportComponent( additionalContext, element );
- }
- }
- });
- }
-
- protected String getTemplateName() {
- return (String)getProperties().get(ExporterConstants.TEMPLATE_NAME);
- }
-
- protected void doStart() {
-
- if(getFilePattern()==null) {
- throw new RuntimeException("File pattern not set on " + this.getClass());
- }
- if(getTemplateName()==null) {
- throw new RuntimeException("Template name not set on " + this.getClass());
- }
-
- List exporters = new ArrayList();
-
- if(StringHelper.isEmpty( getForEach() )) {
- if(getFilePattern().indexOf("{class-name}")>=0) {
- exporters.add( modelIterators.get( "entity" ) );
- exporters.add( modelIterators.get( "component") );
- } else {
- exporters.add( modelIterators.get( "configuration" ));
- }
- } else {
- StringTokenizer tokens = new StringTokenizer(getForEach(), ",");
-
- while ( tokens.hasMoreTokens() ) {
- String nextToken = tokens.nextToken();
- ModelIterator modelIterator = modelIterators.get(nextToken);
- if(modelIterator==null) {
- throw new RuntimeException("for-each does not support [" + nextToken + "]");
- }
- exporters.add(modelIterator);
- }
- }
-
- Iterator it = exporters.iterator();
- while(it.hasNext()) {
- ModelIterator mit = it.next();
- mit.process( this );
- }
- }
-
- protected void exportComponent(Map additionalContext, POJOClass element) {
- exportPOJO(additionalContext, element);
- }
-
- protected void exportPersistentClass(Map additionalContext, POJOClass element) {
- exportPOJO(additionalContext, element);
- }
-
- protected void exportPOJO(Map additionalContext, POJOClass element) {
- TemplateProducer producer = new TemplateProducer(getTemplateHelper(),getArtifactCollector());
- additionalContext.put("pojo", element);
- additionalContext.put("clazz", element.getDecoratedObject());
- String filename = resolveFilename( element );
- if(filename.endsWith(".java") && filename.indexOf('$')>=0) {
- log.warn("Filename for " + getClassNameForFile( element ) + " contains a $. Innerclass generation is not supported.");
- }
- producer.produce(
- additionalContext,
- getTemplateName(),
- new File(getOutputDirectory(),filename),
- getTemplateName(),
- element.toString());
- }
-
- protected String resolveFilename(POJOClass element) {
- String filename = StringHelper.replace(getFilePattern(), "{class-name}", getClassNameForFile( element ));
- String packageLocation = StringHelper.replace(getPackageNameForFile( element ),".", "/");
- if(StringHelper.isEmpty(packageLocation)) {
- packageLocation = "."; // done to ensure default package classes doesn't end up in the root of the filesystem when outputdir=""
- }
- filename = StringHelper.replace(filename, "{package-name}", packageLocation);
- return filename;
- }
-
- protected String getPackageNameForFile(POJOClass element) {
- return element.getPackageName();
- }
-
- protected String getClassNameForFile(POJOClass element) {
- return element.getDeclarationName();
- }
-
- private String getFilePattern() {
- return (String)getProperties().get(FILE_PATTERN);
- }
-
- private String getForEach() {
- return (String)getProperties().get(FOR_EACH);
- }
-
+
+ static abstract class ModelIterator {
+ abstract void process(GenericExporter ge);
+ }
+
+ static Map modelIterators = new HashMap<>();
+ static {
+ modelIterators.put( "configuration", new ModelIterator() {
+ void process(GenericExporter ge) {
+ TemplateProducer producer =
+ new TemplateProducer(
+ ge.getTemplateHelper(),
+ ge.getArtifactCollector());
+ producer.produce(
+ new HashMap<>(),
+ ge.getTemplateName(),
+ new File(ge.getOutputDirectory(),ge.getFilePattern()),
+ ge.getTemplateName(),
+ "Configuration");
+ }
+ });
+ modelIterators.put("entity", new ModelIterator() {
+ void process(GenericExporter ge) {
+ Iterator> iterator =
+ ge.getCfg2JavaTool().getPOJOIterator(
+ ge.getMetadata().getEntityBindings().iterator());
+ Map additionalContext = new HashMap<>();
+ while ( iterator.hasNext() ) {
+ POJOClass element = (POJOClass) iterator.next();
+ ge.exportPersistentClass( additionalContext, element );
+ }
+ }
+ });
+ modelIterators.put("component", new ModelIterator() {
+
+ void process(GenericExporter ge) {
+ Map components = new HashMap<>();
+
+ Iterator> iterator =
+ ge.getCfg2JavaTool().getPOJOIterator(
+ ge.getMetadata().getEntityBindings().iterator());
+ Map additionalContext = new HashMap<>();
+ while ( iterator.hasNext() ) {
+ POJOClass element = (POJOClass) iterator.next();
+ ConfigurationNavigator.collectComponents(components, element);
+ }
+
+ iterator = components.values().iterator();
+ while ( iterator.hasNext() ) {
+ Component component = (Component) iterator.next();
+ ComponentPOJOClass element = new ComponentPOJOClass(component,ge.getCfg2JavaTool());
+ ge.exportComponent( additionalContext, element );
+ }
+ }
+ });
+ }
+
+ protected String getTemplateName() {
+ return (String)getProperties().get(ExporterConstants.TEMPLATE_NAME);
+ }
+
+ protected void doStart() {
+
+ if(getFilePattern()==null) {
+ throw new RuntimeException("File pattern not set on " + this.getClass());
+ }
+ if(getTemplateName()==null) {
+ throw new RuntimeException("Template name not set on " + this.getClass());
+ }
+
+ List exporters = new ArrayList<>();
+
+ if(StringHelper.isEmpty( getForEach() )) {
+ if( getFilePattern().contains( "{class-name}" ) ) {
+ exporters.add( modelIterators.get( "entity" ) );
+ exporters.add( modelIterators.get( "component") );
+ }
+ else {
+ exporters.add( modelIterators.get( "configuration" ));
+ }
+ }
+ else {
+ StringTokenizer tokens = new StringTokenizer(getForEach(), ",");
+
+ while ( tokens.hasMoreTokens() ) {
+ String nextToken = tokens.nextToken();
+ ModelIterator modelIterator = modelIterators.get(nextToken);
+ if(modelIterator==null) {
+ throw new RuntimeException("for-each does not support [" + nextToken + "]");
+ }
+ exporters.add(modelIterator);
+ }
+ }
+
+ for ( ModelIterator mit : exporters ) {
+ mit.process( this );
+ }
+ }
+
+ protected void exportComponent(Map additionalContext, POJOClass element) {
+ exportPOJO(additionalContext, element);
+ }
+
+ protected void exportPersistentClass(Map additionalContext, POJOClass element) {
+ exportPOJO(additionalContext, element);
+ }
+
+ protected void exportPOJO(Map additionalContext, POJOClass element) {
+ TemplateProducer producer = new TemplateProducer(getTemplateHelper(),getArtifactCollector());
+ additionalContext.put("pojo", element);
+ additionalContext.put("clazz", element.getDecoratedObject());
+ String filename = resolveFilename( element );
+ if(filename.endsWith(".java") && filename.indexOf('$')>=0) {
+ log.warn("Filename for " + getClassNameForFile( element ) + " contains a $. Inner class generation is not supported.");
+ }
+ producer.produce(
+ additionalContext,
+ getTemplateName(),
+ new File(getOutputDirectory(),filename),
+ getTemplateName(),
+ element.toString());
+ }
+
+ protected String resolveFilename(POJOClass element) {
+ String filename = StringHelper.replace(getFilePattern(), "{class-name}", getClassNameForFile( element ));
+ String packageLocation = StringHelper.replace(getPackageNameForFile( element ),".", "/");
+ if(StringHelper.isEmpty(packageLocation)) {
+ packageLocation = "."; // done to ensure default package classes doesn't end up in the root of the filesystem when outputdir=""
+ }
+ filename = StringHelper.replace(filename, "{package-name}", packageLocation);
+ return filename;
+ }
+
+ protected String getPackageNameForFile(POJOClass element) {
+ return element.getPackageName();
+ }
+
+ protected String getClassNameForFile(POJOClass element) {
+ return element.getDeclarationName();
+ }
+
+ private String getFilePattern() {
+ return (String)getProperties().get(FILE_PATTERN);
+ }
+
+ private String getForEach() {
+ return (String)getProperties().get(FOR_EACH);
+ }
+
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateHelper.java b/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateHelper.java
index 3857d742d0..bdc59b59ab 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateHelper.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateHelper.java
@@ -58,197 +58,200 @@
*/
public class TemplateHelper {
- static final Logger log = Logger.getLogger(TemplateHelper.class);
-
- private File outputDirectory;
-
- protected Configuration freeMarkerEngine;
-
- protected SimpleHash context;
-
- public TemplateHelper() {
-
- }
-
- public void init(File outputDirectory, String[] templatePaths) {
- this.outputDirectory = outputDirectory;
-
- context = new SimpleHash(new BeansWrapperBuilder(Configuration.VERSION_2_3_0).build());
- freeMarkerEngine = new Configuration(Configuration.VERSION_2_3_0);
-
- List loaders = new ArrayList<>();
-
- for ( String templatePath : templatePaths ) {
- File file = new File( templatePath );
- if ( file.exists() ) {
- if ( file.isDirectory() ) {
- try {
- loaders.add( new FileTemplateLoader( file ) );
- }
- catch (IOException e) {
- throw new RuntimeException( "Problems with templatepath " + file, e );
- }
- }
- else if ( file.getName().endsWith( ".zip" ) || file.getName().endsWith( ".jar" ) ) {
- final URLClassLoader classLoaderForZip;
- try {
- classLoaderForZip = new URLClassLoader( new URL[] {file.toURI().toURL()}, null );
- }
- catch (MalformedURLException e) {
- throw new RuntimeException( "template path " + file + " is not a valid zip file", e );
- }
-
- loaders.add( new ClassTemplateLoader( classLoaderForZip, "/" ) );
- }
- else {
- log.warn( "template path " + file + " is not a directory" );
- }
- }
- else {
- log.warn( "template path " + file + " does not exist" );
- }
- }
- loaders.add(new ClassTemplateLoader(this.getClass(),"/")); // the template names are like pojo/Somewhere so have to be a rooted classpathloader
-
- freeMarkerEngine.setTemplateLoader(new MultiTemplateLoader( loaders.toArray( new TemplateLoader[0] ) ));
-
- }
-
-
- public class Templates {
-
- public void createFile(String content, String fileName) {
- Writer fw = null;
- try {
- fw = new BufferedWriter(new FileWriter(new File(getOutputDirectory(), fileName)));
- fw.write(content);
- } catch(IOException io) {
- throw new RuntimeException("Problem when writing to " + fileName, io);
- } finally {
- if(fw!=null) {
- try {
- fw.flush();
- fw.close();
- } catch(IOException io ) {
- //TODO: warn
- }
- }
- }
- }
- }
-
- public File getOutputDirectory() {
- return outputDirectory;
- }
-
-
-
- public void putInContext(String key, Object value) {
- if(value == null) throw new IllegalStateException("value must not be null for " + key);
- Object replaced = internalPutInContext(key,value);
- if(replaced!=null) {
- log.warn( "Overwriting context: " + replaced + ".");
- }
- }
-
- public void removeFromContext(String key) {
- Object replaced = internalRemoveFromContext(key);
- if(replaced==null) throw new IllegalStateException(key + " did not exist in template context.");
- }
-
- public void ensureExistence(File destination) {
- // if the directory exists, make sure it is a directory
- File dir = destination.getAbsoluteFile().getParentFile();
- if ( dir.exists() && !dir.isDirectory() ) {
- throw new RuntimeException("The path: " + dir.getAbsolutePath() + " exists, but is not a directory");
- } // else make the directory and any non-existent parent directories
- else if ( !dir.exists() ) {
- if ( !dir.mkdirs() ) {
- if(dir.getName().equals(".")) { // Workaround that Linux/JVM apparently can't handle mkdirs of File's with current dir references.
- if(dir.getParentFile().mkdirs()) {
- return;
- }
- }
- throw new RuntimeException( "unable to create directory: " + dir.getAbsolutePath() );
- }
- }
- }
-
- protected SimpleHash getContext() {
- return context;
- }
-
- public void processString(String template, Writer output) {
-
- try {
- Reader r = new StringReader(template);
- Template t = new Template("unknown", r, freeMarkerEngine);
-
- t.process(getContext(), output);
- }
- catch (Exception e) {
- throw new RuntimeException("Error while processing template string", e);
- }
- }
-
- public void setupContext() {
- getContext().put("version", Version.versionString());
- getContext().put("ctx", getContext() ); //TODO: I would like to remove this, but don't know another way to actually get the list possible "root" keys for debugging.
- getContext().put("templates", new Templates());
-
- getContext().put("date", new SimpleDate(new Date(), TemplateDateModel.DATETIME));
-
- }
-
- protected Object internalPutInContext(String key, Object value) {
- TemplateModel model;
- try {
- model = getContext().get(key);
- }
- catch (TemplateModelException e) {
- throw new RuntimeException("Could not get key " + key, e);
- }
- getContext().put(key, value);
- return model;
- }
-
- protected Object internalRemoveFromContext(String key) {
- TemplateModel model;
- try {
- model = getContext().get(key);
- }
- catch (TemplateModelException e) {
- throw new RuntimeException("Could not get key " + key, e);
- }
- getContext().remove(key);
- return model;
- }
-
- /** look up the template named templateName via the paths and print the content to the output */
- public void processTemplate(String templateName, Writer output, String rootContext) {
- if(rootContext == null) {
- rootContext = "Unknown context";
- }
-
- try {
- Template template = freeMarkerEngine.getTemplate(templateName);
- template.process(getContext(), output);
- }
- catch (Exception e) {
- throw new RuntimeException("Error while processing " + rootContext + " with template " + templateName, e);
- }
- }
-
-
- public boolean templateExists(String templateName) {
- TemplateLoader templateLoader = freeMarkerEngine.getTemplateLoader();
-
- try {
- return templateLoader.findTemplateSource(templateName)!=null;
- }
- catch (IOException e) {
- throw new RuntimeException("templateExists for " + templateName + " failed", e);
- }
- }
+ static final Logger log = Logger.getLogger(TemplateHelper.class);
+
+ private File outputDirectory;
+
+ protected Configuration freeMarkerEngine;
+
+ protected SimpleHash context;
+
+ public TemplateHelper() {
+
+ }
+
+ public void init(File outputDirectory, String[] templatePaths) {
+ this.outputDirectory = outputDirectory;
+
+ context = new SimpleHash(new BeansWrapperBuilder(Configuration.VERSION_2_3_0).build());
+ freeMarkerEngine = new Configuration(Configuration.VERSION_2_3_0);
+
+ List loaders = new ArrayList<>();
+
+ for ( String templatePath : templatePaths ) {
+ File file = new File( templatePath );
+ if ( file.exists() ) {
+ if ( file.isDirectory() ) {
+ try {
+ loaders.add( new FileTemplateLoader( file ) );
+ }
+ catch (IOException e) {
+ throw new RuntimeException( "Problems with templatepath " + file, e );
+ }
+ }
+ else if ( file.getName().endsWith( ".zip" ) || file.getName().endsWith( ".jar" ) ) {
+ final URLClassLoader classLoaderForZip;
+ try {
+ classLoaderForZip = new URLClassLoader( new URL[] {file.toURI().toURL()}, null );
+ }
+ catch (MalformedURLException e) {
+ throw new RuntimeException( "template path " + file + " is not a valid zip file", e );
+ }
+
+ loaders.add( new ClassTemplateLoader( classLoaderForZip, "/" ) );
+ }
+ else {
+ log.warn( "template path " + file + " is not a directory" );
+ }
+ }
+ else {
+ log.warn( "template path " + file + " does not exist" );
+ }
+ }
+ loaders.add(new ClassTemplateLoader(this.getClass(),"/")); // the template names are like pojo/Somewhere so have to be a rooted classpathloader
+
+ freeMarkerEngine.setTemplateLoader(new MultiTemplateLoader( loaders.toArray( new TemplateLoader[0] ) ));
+
+ }
+
+
+ public class Templates {
+
+ public void createFile(String content, String fileName) {
+ Writer fw = null;
+ try {
+ fw = new BufferedWriter(new FileWriter(new File(getOutputDirectory(), fileName)));
+ fw.write(content);
+ }
+ catch(IOException io) {
+ throw new RuntimeException("Problem when writing to " + fileName, io);
+ }
+ finally {
+ if(fw!=null) {
+ try {
+ fw.flush();
+ fw.close();
+ }
+ catch(IOException io ) {
+ //TODO: warn
+ }
+ }
+ }
+ }
+ }
+
+ public File getOutputDirectory() {
+ return outputDirectory;
+ }
+
+
+
+ public void putInContext(String key, Object value) {
+ if(value == null) throw new IllegalStateException("value must not be null for " + key);
+ Object replaced = internalPutInContext(key,value);
+ if(replaced!=null) {
+ log.warn( "Overwriting context: " + replaced + ".");
+ }
+ }
+
+ public void removeFromContext(String key) {
+ Object replaced = internalRemoveFromContext(key);
+ if(replaced==null) throw new IllegalStateException(key + " did not exist in template context.");
+ }
+
+ public void ensureExistence(File destination) {
+ // if the directory exists, make sure it is a directory
+ File dir = destination.getAbsoluteFile().getParentFile();
+ if ( dir.exists() && !dir.isDirectory() ) {
+ throw new RuntimeException("The path: " + dir.getAbsolutePath() + " exists, but is not a directory");
+ } // else make the directory and any non-existent parent directories
+ else if ( !dir.exists() ) {
+ if ( !dir.mkdirs() ) {
+ if(dir.getName().equals(".")) { // Workaround that Linux/JVM apparently can't handle mkdirs of File's with current dir references.
+ if(dir.getParentFile().mkdirs()) {
+ return;
+ }
+ }
+ throw new RuntimeException( "unable to create directory: " + dir.getAbsolutePath() );
+ }
+ }
+ }
+
+ protected SimpleHash getContext() {
+ return context;
+ }
+
+ public void processString(String template, Writer output) {
+
+ try {
+ Reader r = new StringReader(template);
+ Template t = new Template("unknown", r, freeMarkerEngine);
+
+ t.process(getContext(), output);
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Error while processing template string", e);
+ }
+ }
+
+ public void setupContext() {
+ getContext().put("version", Version.versionString());
+ getContext().put("ctx", getContext() ); //TODO: I would like to remove this, but don't know another way to actually get the list possible "root" keys for debugging.
+ getContext().put("templates", new Templates());
+
+ getContext().put("date", new SimpleDate(new Date(), TemplateDateModel.DATETIME));
+
+ }
+
+ protected Object internalPutInContext(String key, Object value) {
+ TemplateModel model;
+ try {
+ model = getContext().get(key);
+ }
+ catch (TemplateModelException e) {
+ throw new RuntimeException("Could not get key " + key, e);
+ }
+ getContext().put(key, value);
+ return model;
+ }
+
+ protected Object internalRemoveFromContext(String key) {
+ TemplateModel model;
+ try {
+ model = getContext().get(key);
+ }
+ catch (TemplateModelException e) {
+ throw new RuntimeException("Could not get key " + key, e);
+ }
+ getContext().remove(key);
+ return model;
+ }
+
+ /** look up the template named templateName via the paths and print the content to the output */
+ public void processTemplate(String templateName, Writer output, String rootContext) {
+ if(rootContext == null) {
+ rootContext = "Unknown context";
+ }
+
+ try {
+ Template template = freeMarkerEngine.getTemplate(templateName);
+ template.process(getContext(), output);
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Error while processing " + rootContext + " with template " + templateName, e);
+ }
+ }
+
+
+ public boolean templateExists(String templateName) {
+ TemplateLoader templateLoader = freeMarkerEngine.getTemplateLoader();
+
+ try {
+ return templateLoader.findTemplateSource(templateName)!=null;
+ }
+ catch (IOException e) {
+ throw new RuntimeException("templateExists for " + templateName + " failed", e);
+ }
+ }
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateProducer.java b/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateProducer.java
index ef46146fca..a88c532832 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateProducer.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/common/TemplateProducer.java
@@ -31,87 +31,88 @@
public class TemplateProducer {
- private static final Logger log = Logger.getLogger(TemplateProducer.class);
- private final TemplateHelper th;
- private final ArtifactCollector ac;
-
- public TemplateProducer(TemplateHelper th, ArtifactCollector ac) {
- this.th = th;
- this.ac = ac;
- }
-
- public void produce(Map additionalContext, String templateName, File destination, String identifier, String fileType, String rootContext) {
-
- String tempResult = produceToString( additionalContext, templateName, rootContext );
-
- if( tempResult.trim().isEmpty() ) {
- log.warn("Generated output is empty. Skipped creation for file " + destination);
- return;
- }
- FileWriter fileWriter = null;
- try {
-
- th.ensureExistence( destination );
-
- ac.addFile(destination, fileType);
- log.debug("Writing " + identifier + " to " + destination.getAbsolutePath() );
- fileWriter = new FileWriter(destination);
- fileWriter.write(tempResult);
- }
- catch (Exception e) {
- throw new RuntimeException("Error while writing result to file", e);
- } finally {
- if(fileWriter!=null) {
- try {
- fileWriter.flush();
- fileWriter.close();
- }
- catch (IOException e) {
- log.warn("Exception while flushing/closing " + destination,e);
- }
- }
- }
-
- }
-
-
- private String produceToString(Map additionalContext, String templateName, String rootContext) {
- putInContext( th, additionalContext );
- StringWriter tempWriter = new StringWriter();
- BufferedWriter bw = new BufferedWriter(tempWriter);
- // First run - writes to in-memory string
- th.processTemplate(templateName, bw, rootContext);
- removeFromContext( th, additionalContext );
- try {
- bw.flush();
- }
- catch (IOException e) {
- throw new RuntimeException("Error while flushing to string",e);
- }
- return tempWriter.toString();
- }
-
- private void removeFromContext(TemplateHelper templateHelper, Map context) {
- for ( Entry element : context.entrySet() ) {
- templateHelper.removeFromContext( element.getKey() );
- }
- }
-
- private void putInContext(TemplateHelper templateHelper, Map context) {
- for ( Entry element : context.entrySet() ) {
- templateHelper.putInContext( element.getKey(), element.getValue() );
- }
- }
-
- public void produce(Map additionalContext, String templateName, File outputFile, String identifier) {
- String fileType = outputFile.getName();
- fileType = fileType.substring(fileType.indexOf('.')+1);
- produce(additionalContext, templateName, outputFile, identifier, fileType, null);
- }
-
- public void produce(Map additionalContext, String templateName, File outputFile, String identifier, String rootContext) {
- String fileType = outputFile.getName();
- fileType = fileType.substring(fileType.indexOf('.')+1);
- produce(additionalContext, templateName, outputFile, identifier, fileType, rootContext);
- }
+ private static final Logger log = Logger.getLogger(TemplateProducer.class);
+ private final TemplateHelper th;
+ private final ArtifactCollector ac;
+
+ public TemplateProducer(TemplateHelper th, ArtifactCollector ac) {
+ this.th = th;
+ this.ac = ac;
+ }
+
+ public void produce(Map additionalContext, String templateName, File destination, String identifier, String fileType, String rootContext) {
+
+ String tempResult = produceToString( additionalContext, templateName, rootContext );
+
+ if( tempResult.trim().isEmpty() ) {
+ log.warn("Generated output is empty. Skipped creation for file " + destination);
+ return;
+ }
+ FileWriter fileWriter = null;
+ try {
+
+ th.ensureExistence( destination );
+
+ ac.addFile(destination, fileType);
+ log.debug("Writing " + identifier + " to " + destination.getAbsolutePath() );
+ fileWriter = new FileWriter(destination);
+ fileWriter.write(tempResult);
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Error while writing result to file", e);
+ }
+ finally {
+ if(fileWriter!=null) {
+ try {
+ fileWriter.flush();
+ fileWriter.close();
+ }
+ catch (IOException e) {
+ log.warn("Exception while flushing/closing " + destination,e);
+ }
+ }
+ }
+
+ }
+
+
+ private String produceToString(Map additionalContext, String templateName, String rootContext) {
+ putInContext( th, additionalContext );
+ StringWriter tempWriter = new StringWriter();
+ BufferedWriter bw = new BufferedWriter(tempWriter);
+ // First run - writes to in-memory string
+ th.processTemplate(templateName, bw, rootContext);
+ removeFromContext( th, additionalContext );
+ try {
+ bw.flush();
+ }
+ catch (IOException e) {
+ throw new RuntimeException("Error while flushing to string",e);
+ }
+ return tempWriter.toString();
+ }
+
+ private void removeFromContext(TemplateHelper templateHelper, Map context) {
+ for ( Entry element : context.entrySet() ) {
+ templateHelper.removeFromContext( element.getKey() );
+ }
+ }
+
+ private void putInContext(TemplateHelper templateHelper, Map context) {
+ for ( Entry element : context.entrySet() ) {
+ templateHelper.putInContext( element.getKey(), element.getValue() );
+ }
+ }
+
+ public void produce(Map additionalContext, String templateName, File outputFile, String identifier) {
+ String fileType = outputFile.getName();
+ fileType = fileType.substring(fileType.indexOf('.')+1);
+ produce(additionalContext, templateName, outputFile, identifier, fileType, null);
+ }
+
+ public void produce(Map additionalContext, String templateName, File outputFile, String identifier, String rootContext) {
+ String fileType = outputFile.getName();
+ fileType = fileType.substring(fileType.indexOf('.')+1);
+ produce(additionalContext, templateName, outputFile, identifier, fileType, rootContext);
+ }
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/ddl/DdlExporter.java b/orm/src/main/java/org/hibernate/tool/internal/export/ddl/DdlExporter.java
index 2fd3205e6d..6d5cd9ef49 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/ddl/DdlExporter.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/ddl/DdlExporter.java
@@ -36,133 +36,144 @@
*/
public class DdlExporter extends AbstractExporter {
- protected void doStart() {
- String outputFileName = getProperties().getProperty(OUTPUT_FILE_NAME);
- Metadata metadata = getMetadata();
- final EnumSet targetTypes = EnumSet.noneOf( TargetType.class );
- if (getExportToConsole()) targetTypes.add(TargetType.STDOUT);
- if (getExportToDatabase()) targetTypes.add(TargetType.DATABASE);
- if (null != outputFileName) targetTypes.add(TargetType.SCRIPT);
- if (getSchemaUpdate()) {
- SchemaUpdate update = new SchemaUpdate();
- if(outputFileName == null && getDelimiter() == null && getHaltOnError() && getFormat()) {
- update.execute(targetTypes, metadata);
- }
- else {
- if (null != outputFileName) {
- File outputFile = new File(getOutputDirectory(), outputFileName);
- update.setOutputFile(outputFile.getPath());
- log.debug("delimiter ='"+ getDelimiter() + "'");
- update.setDelimiter(getDelimiter());
- update.setFormat(Boolean.valueOf(getFormat()));
- }
-
- if (getHaltOnError()) {
- update.setHaltOnError(Boolean.valueOf(getHaltOnError()));
- }
-
- update.execute(targetTypes, metadata);
- if (!update.getExceptions().isEmpty()) {
- int i = 1;
- for (Iterator> iterator = update.getExceptions().iterator(); iterator
- .hasNext(); i++) {
- Throwable element = (Throwable) iterator.next();
- log.warn("Error #" + i + ": ", element);
-
- }
- log.error(i - 1 + " errors occurred while performing Hbm2DDLExporter.");
- if (getHaltOnError()) {
- throw new RuntimeException(
- "Errors while performing Hbm2DDLExporter");
- }
- }
- }
-
- } else {
- SchemaExport export = new SchemaExport();
- if (null != outputFileName) {
- export.setOutputFile(new File(getOutputDirectory(),
- outputFileName).toString());
- }
- if (null != getDelimiter()) {
- export.setDelimiter(getDelimiter());
- }
- export.setHaltOnError(getHaltOnError());
- export.setFormat(getFormat());
- if (getDrop() && getCreate()) {
- export.execute(targetTypes, Action.BOTH, metadata);
- } else if (getDrop()) {
- export.execute(targetTypes, Action.DROP, metadata);
- } else if (getCreate()) {
- export.execute(targetTypes, Action.CREATE, metadata);
- } else {
- export.execute(targetTypes, Action.NONE, metadata);
- }
- }
-
- }
-
- private boolean getCreate() {
- if (!getProperties().containsKey(CREATE_DATABASE)) {
- return true;
- } else {
- return (boolean)getProperties().get(CREATE_DATABASE);
- }
- }
-
- private String getDelimiter() {
- if (!getProperties().containsKey(DELIMITER)) {
- return ";";
- }
- return (String)getProperties().get(DELIMITER);
- }
-
- private boolean getDrop() {
- if (!getProperties().containsKey(DROP_DATABASE)) {
- return false;
- } else {
- return (boolean)getProperties().get(DROP_DATABASE);
- }
- }
-
- private boolean getExportToConsole() {
- if (!getProperties().containsKey(EXPORT_TO_CONSOLE)) {
- return true;
- } else {
- return (boolean)getProperties().get(EXPORT_TO_CONSOLE);
- }
- }
-
- private boolean getExportToDatabase() {
- if (!getProperties().containsKey(EXPORT_TO_DATABASE)) {
- return true;
- } else {
- return (boolean)getProperties().get(EXPORT_TO_DATABASE);
- }
- }
-
- private boolean getFormat() {
- if (!getProperties().containsKey(FORMAT)) {
- return false;
- } else {
- return (boolean)getProperties().get(FORMAT);
- }
- }
-
- private boolean getHaltOnError() {
- if (!getProperties().containsKey(HALT_ON_ERROR)) {
- return false;
- } else {
- return (boolean)getProperties().get(HALT_ON_ERROR);
- }
- }
-
- private boolean getSchemaUpdate() {
- if (!getProperties().containsKey(SCHEMA_UPDATE)) {
- return false;
- } else {
- return (boolean)getProperties().get(SCHEMA_UPDATE);
- }
- }
-
+ protected void doStart() {
+ String outputFileName = getProperties().getProperty(OUTPUT_FILE_NAME);
+ Metadata metadata = getMetadata();
+ final EnumSet targetTypes = EnumSet.noneOf( TargetType.class );
+ if (getExportToConsole()) targetTypes.add(TargetType.STDOUT);
+ if (getExportToDatabase()) targetTypes.add(TargetType.DATABASE);
+ if (null != outputFileName) targetTypes.add(TargetType.SCRIPT);
+ if (getSchemaUpdate()) {
+ SchemaUpdate update = new SchemaUpdate();
+ if(outputFileName == null && getDelimiter() == null && getHaltOnError() && getFormat()) {
+ update.execute(targetTypes, metadata);
+ }
+ else {
+ if (null != outputFileName) {
+ File outputFile = new File(getOutputDirectory(), outputFileName);
+ update.setOutputFile(outputFile.getPath());
+ log.debug("delimiter ='"+ getDelimiter() + "'");
+ update.setDelimiter(getDelimiter());
+ update.setFormat( getFormat() );
+ }
+
+ if (getHaltOnError()) {
+ update.setHaltOnError( getHaltOnError() );
+ }
+
+ update.execute(targetTypes, metadata);
+ if (!update.getExceptions().isEmpty()) {
+ int i = 1;
+ for (Iterator> iterator = update.getExceptions().iterator(); iterator
+ .hasNext(); i++) {
+ Throwable element = (Throwable) iterator.next();
+ log.warn("Error #" + i + ": ", element);
+
+ }
+ log.error(i - 1 + " errors occurred while performing Hbm2DDLExporter.");
+ if (getHaltOnError()) {
+ throw new RuntimeException(
+ "Errors while performing Hbm2DDLExporter");
+ }
+ }
+ }
+
+ }
+ else {
+ SchemaExport export = new SchemaExport();
+ if (null != outputFileName) {
+ export.setOutputFile(new File(getOutputDirectory(),
+ outputFileName).toString());
+ }
+ if (null != getDelimiter()) {
+ export.setDelimiter(getDelimiter());
+ }
+ export.setHaltOnError(getHaltOnError());
+ export.setFormat(getFormat());
+ if (getDrop() && getCreate()) {
+ export.execute(targetTypes, Action.BOTH, metadata);
+ }
+ else if (getDrop()) {
+ export.execute(targetTypes, Action.DROP, metadata);
+ }
+ else if (getCreate()) {
+ export.execute(targetTypes, Action.CREATE, metadata);
+ }
+ else {
+ export.execute(targetTypes, Action.NONE, metadata);
+ }
+ }
+
+ }
+
+ private boolean getCreate() {
+ if (!getProperties().containsKey(CREATE_DATABASE)) {
+ return true;
+ }
+ else {
+ return (boolean)getProperties().get(CREATE_DATABASE);
+ }
+ }
+
+ private String getDelimiter() {
+ if (!getProperties().containsKey(DELIMITER)) {
+ return ";";
+ }
+ return (String)getProperties().get(DELIMITER);
+ }
+
+ private boolean getDrop() {
+ if (!getProperties().containsKey(DROP_DATABASE)) {
+ return false;
+ }
+ else {
+ return (boolean)getProperties().get(DROP_DATABASE);
+ }
+ }
+
+ private boolean getExportToConsole() {
+ if (!getProperties().containsKey(EXPORT_TO_CONSOLE)) {
+ return true;
+ }
+ else {
+ return (boolean)getProperties().get(EXPORT_TO_CONSOLE);
+ }
+ }
+
+ private boolean getExportToDatabase() {
+ if (!getProperties().containsKey(EXPORT_TO_DATABASE)) {
+ return true;
+ }
+ else {
+ return (boolean)getProperties().get(EXPORT_TO_DATABASE);
+ }
+ }
+
+ private boolean getFormat() {
+ if (!getProperties().containsKey(FORMAT)) {
+ return false;
+ }
+ else {
+ return (boolean)getProperties().get(FORMAT);
+ }
+ }
+
+ private boolean getHaltOnError() {
+ if (!getProperties().containsKey(HALT_ON_ERROR)) {
+ return false;
+ }
+ else {
+ return (boolean)getProperties().get(HALT_ON_ERROR);
+ }
+ }
+
+ private boolean getSchemaUpdate() {
+ if (!getProperties().containsKey(SCHEMA_UPDATE)) {
+ return false;
+ }
+ else {
+ return (boolean)getProperties().get(SCHEMA_UPDATE);
+ }
+ }
+
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocExporter.java b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocExporter.java
index d50b206f76..a40bead8ed 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocExporter.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocExporter.java
@@ -23,7 +23,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -67,42 +66,42 @@ public class DocExporter extends AbstractExporter {
* Main index page.
*/
private static final String FILE_INDEX = "doc/index.html";
-
+
/**
* Template used for the index of the table documentation.
*/
private static final String FTL_TABLES_INDEX = "doc/tables/index.ftl";
-
+
/**
* Template used for index of the entity documentation
*/
private static final String FTL_ENTITIES_INDEX = "doc/entities/index.ftl";
-
+
/**
* Template used for the Classes Summary
*/
private static final String FTL_ENTITIES_SUMMARY = "doc/entities/summary.ftl";
-
+
/**
* Template used for Class details
*/
private static final String FTL_ENTITIES_ENTITY = "doc/entities/entity.ftl";
-
+
/**
* Template used to create the Package List
*/
private static final String FTL_ENTITIES_PACKAGE_LIST = "doc/entities/package-list.ftl";
-
+
/**
* Template used to create the list of all Classes
*/
private static final String FTL_ENTITIES_ENTITY_LIST = "doc/entities/allEntity-list.ftl";
-
+
/**
* Template used to create List of Classes specific to packages.
*/
private static final String FTL_ENTITIES_PERPACKAGE_ENTITY_LIST = "doc/entities/perPackageEntity-list.ftl";
-
+
/**
* Template used to show the specific package details
*/
@@ -147,10 +146,10 @@ public class DocExporter extends AbstractExporter {
* Doc File Manager.
*/
private DocFileManager docFileManager;
-
- public void doStart() {
+
+ public void doStart() {
generateCommmonAndAssets();
-
+
boolean graphsGenerated = generateDot();
generateTablesIndex();
generateTablesSummary(graphsGenerated);
@@ -159,7 +158,7 @@ public void doStart() {
generateTablesAllTablesList();
generateTablesSchemaTableList();
generateTablesSchemaDetailedInfo();
-
+
generateEntitiesIndex();
generatePackageSummary(graphsGenerated);
generateEntitiesDetails();
@@ -167,87 +166,89 @@ public void doStart() {
generateEntitiesAllEntitiesList();
generateEntitiesPackageEntityList();
generateEntitiesPackageDetailedInfo();
-
-
+
+
}
- private boolean generateDot() {
- String cmd = getProperties().getProperty( "dot.executable" );
- boolean ignoreError = Boolean.parseBoolean(getProperties().getProperty("dot.ignoreerror", "false"));
-
- if(StringHelper.isNotEmpty( cmd )) {
- try {
- Exporter exporter = ExporterFactory.createExporter(ExporterType.GENERIC);
- exporter.getProperties().putAll( getProperties() );
- exporter.getProperties().put(ARTIFACT_COLLECTOR, getArtifactCollector());
- exporter.getProperties().put(METADATA_DESCRIPTOR, getMetadataDescriptor());
- exporter.getProperties().put(DESTINATION_FOLDER, getOutputDirectory());
- String[] tp = (String[])exporter.getProperties().get(TEMPLATE_PATH);
- if (tp != null) {
- exporter.getProperties().put(TEMPLATE_PATH, tp);
- }
-
- exporter.getProperties().put(TEMPLATE_NAME, "dot/entitygraph.dot.ftl");
- exporter.getProperties().put(FILE_PATTERN, "entities/entitygraph.dot");
- exporter.start();
-
- exporter.getProperties().put(TEMPLATE_NAME, "dot/tablegraph.dot.ftl");
- exporter.getProperties().put(FILE_PATTERN, "tables/tablegraph.dot");
- exporter.start();
-
-
- File entityGraphDot = new File(getOutputDirectory(), "entities/entitygraph.dot");
- dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.png").toString());
- dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.svg").toString());
- dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.cmapx").toString());
-
- File tableGraphDot = new File(getOutputDirectory(), "tables/tablegraph.dot");
- dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.png").toString());
- dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.svg").toString());
- dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.cmapx").toString());
-
- return true;
-
- }
- catch (IOException e) {
- if(ignoreError) {
- log.warn( "Skipping entitygraph creation since dot.executable was not found and dot.ignoreerror=false." );
- return false;
- } else {
- throw new HibernateException("Problem while generating DOT graph for Configuration (set dot.ignoreerror=false to ignore)", e);
- }
- }
- } else {
- log.info( "Skipping entitygraph creation since dot.executable is empty or not-specified." );
- return false;
- }
- }
-
- public static final String OS_NAME = System.getProperty("os.name");
- public static final boolean IS_LINUX = OS_NAME.startsWith("Linux");
-
- private String escape(String fileName){
-
- // Linux does not need " " around file names
- if (IS_LINUX){
- return fileName;
- }
-
- // Windows needs " " around file names; actually we do not
- // need it always, only when spaces are present;
- // but it does not hurt to usem them always
- return "\"" + fileName + "\"";
-
- }
-
- private void dotToFile(String dotExeFileName, String dotFileName, String outFileName) throws IOException {
-
- //
- // dot.exe works by taking *.dot file and piping
- // results into another file, for example:
- // d:\graphviz-1.12\bin\dot.exe -Tgif c:\temp\ManualDraw.dot > c:\temp\ManualDraw.gif
- // so we follow that model here and read stdout until EOF
- //
+ private boolean generateDot() {
+ String cmd = getProperties().getProperty( "dot.executable" );
+ boolean ignoreError = Boolean.parseBoolean(getProperties().getProperty("dot.ignoreerror", "false"));
+
+ if(StringHelper.isNotEmpty( cmd )) {
+ try {
+ Exporter exporter = ExporterFactory.createExporter(ExporterType.GENERIC);
+ exporter.getProperties().putAll( getProperties() );
+ exporter.getProperties().put(ARTIFACT_COLLECTOR, getArtifactCollector());
+ exporter.getProperties().put(METADATA_DESCRIPTOR, getMetadataDescriptor());
+ exporter.getProperties().put(DESTINATION_FOLDER, getOutputDirectory());
+ String[] tp = (String[])exporter.getProperties().get(TEMPLATE_PATH);
+ if (tp != null) {
+ exporter.getProperties().put(TEMPLATE_PATH, tp);
+ }
+
+ exporter.getProperties().put(TEMPLATE_NAME, "dot/entitygraph.dot.ftl");
+ exporter.getProperties().put(FILE_PATTERN, "entities/entitygraph.dot");
+ exporter.start();
+
+ exporter.getProperties().put(TEMPLATE_NAME, "dot/tablegraph.dot.ftl");
+ exporter.getProperties().put(FILE_PATTERN, "tables/tablegraph.dot");
+ exporter.start();
+
+
+ File entityGraphDot = new File(getOutputDirectory(), "entities/entitygraph.dot");
+ dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.png").toString());
+ dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.svg").toString());
+ dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.cmapx").toString());
+
+ File tableGraphDot = new File(getOutputDirectory(), "tables/tablegraph.dot");
+ dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.png").toString());
+ dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.svg").toString());
+ dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.cmapx").toString());
+
+ return true;
+
+ }
+ catch (IOException e) {
+ if(ignoreError) {
+ log.warn( "Skipping entitygraph creation since dot.executable was not found and dot.ignoreerror=false." );
+ return false;
+ }
+ else {
+ throw new HibernateException("Problem while generating DOT graph for Configuration (set dot.ignoreerror=false to ignore)", e);
+ }
+ }
+ }
+ else {
+ log.info( "Skipping entitygraph creation since dot.executable is empty or not-specified." );
+ return false;
+ }
+ }
+
+ public static final String OS_NAME = System.getProperty("os.name");
+ public static final boolean IS_LINUX = OS_NAME.startsWith("Linux");
+
+ private String escape(String fileName){
+
+ // Linux does not need " " around file names
+ if (IS_LINUX){
+ return fileName;
+ }
+
+ // Windows needs " " around file names; actually we do not
+ // need it always, only when spaces are present;
+ // but it does not hurt to usem them always
+ return "\"" + fileName + "\"";
+
+ }
+
+ private void dotToFile(String dotExeFileName, String dotFileName, String outFileName) throws IOException {
+
+ //
+ // dot.exe works by taking *.dot file and piping
+ // results into another file, for example:
+ // d:\graphviz-1.12\bin\dot.exe -Tgif c:\temp\ManualDraw.dot > c:\temp\ManualDraw.gif
+ // so we follow that model here and read stdout until EOF
+ //
final String[] cmdAsArray = new String[] {
escape( dotExeFileName ),
@@ -266,47 +267,50 @@ private void dotToFile(String dotExeFileName, String dotFileName, String outFile
final String cmdAsString = sb.toString();
Process p = Runtime.getRuntime().exec(cmdAsArray);
-
- try {
- log.debug( "Executing: " + cmdAsString );
+ //p.getErrorStream().
+ try {
+ log.debug( "Executing: " + cmdAsString );
// Get the input stream and read from it
- InputStream in = p.getErrorStream();
- int c;
- while ((c = in.read()) != -1) {
- System.out.print((char)c);
- }
- in.close();
- int i = p.waitFor( );
- if(i!=0) {
- //TODO: dump system.err
- log.error("Error " + i + " while executing: " + cmdAsString);
- }
- } catch(Exception ie){
- log.error( "Error while executing: " + cmdAsString, ie );
- }
- }
-
- private String getFormatForFile(String outFileName){
- int idx = outFileName.lastIndexOf(".");
- if (idx == -1 || idx == outFileName.length() - 1){
- throw new IllegalArgumentException("Can't determine file name extention for file name " + outFileName);
- }
- return outFileName.substring(idx + 1);
- }
-
-
- protected void setupContext() {
- if(!getProperties().contains( "jdk5" )) {
- getProperties().setProperty( "jdk5", "true" );
- }
- super.setupContext();
- Metadata metadata = getMetadata();
- docHelper = new DocHelper( metadata, getProperties(), getCfg2JavaTool() );
+ InputStream in = p.getErrorStream();
+ int c;
+ sb = new StringBuilder();
+ while ((c = in.read()) != -1) {
+ sb.append( (char)c );
+ }
+ log.error( sb.toString() );
+ in.close();
+ int i = p.waitFor( );
+ if(i!=0) {
+ //TODO: dump system.err
+ log.error("Error " + i + " while executing: " + cmdAsString);
+ }
+ }
+ catch(Exception ie){
+ log.error( "Error while executing: " + cmdAsString, ie );
+ }
+ }
+
+ private String getFormatForFile(String outFileName){
+ int idx = outFileName.lastIndexOf(".");
+ if (idx == -1 || idx == outFileName.length() - 1){
+ throw new IllegalArgumentException("Can't determine file name extention for file name " + outFileName);
+ }
+ return outFileName.substring(idx + 1);
+ }
+
+
+ protected void setupContext() {
+ if(!getProperties().contains( "jdk5" )) {
+ getProperties().setProperty( "jdk5", "true" );
+ }
+ super.setupContext();
+ Metadata metadata = getMetadata();
+ docHelper = new DocHelper( metadata, getProperties(), getCfg2JavaTool() );
docFileManager = new DocFileManager(docHelper, getOutputDirectory() );
getTemplateHelper().putInContext("dochelper", docHelper);
getTemplateHelper().putInContext("docFileManager", docFileManager);
- }
+ }
/**
* Generate common files and copy assets.
@@ -315,7 +319,7 @@ public void generateCommmonAndAssets() {
try {
DocFile cssStylesDocFile = docFileManager.getCssStylesDocFile();
- processTemplate(new HashMap(0), FILE_CSS_DEFINITION, cssStylesDocFile.getFile());
+ processTemplate( new HashMap<>( 0 ), FILE_CSS_DEFINITION, cssStylesDocFile.getFile());
DocFile hibernateLogoDocFile = docFileManager.getHibernateImageDocFile();
@@ -323,13 +327,13 @@ public void generateCommmonAndAssets() {
hibernateLogoDocFile.getFile() );
DocFile extendsImageDocFile = docFileManager.getExtendsImageDocFile();
-
+
DocFileManager.copy(this.getClass().getClassLoader(), FILE_EXTENDS_IMAGE, extendsImageDocFile.getFile());
-
+
DocFile mainIndexDocFile = docFileManager.getMainIndexDocFile();
- processTemplate(new HashMap(0), FILE_INDEX, mainIndexDocFile.getFile() );
- }
+ processTemplate( new HashMap<>( 0 ), FILE_INDEX, mainIndexDocFile.getFile() );
+ }
catch (IOException ioe) {
throw new RuntimeException("Error while copying files.", ioe);
}
@@ -343,130 +347,123 @@ public void generateTablesIndex() {
File file = docFile.getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
processTemplate(parameters, FTL_TABLES_INDEX, file);
}
-
+
/**
* Generate the index file of the class documentation
*/
public void generateEntitiesIndex(){
- DocFile docFile = docFileManager.getClassIndexDocFile();
- File file = docFile.getFile();
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
- processTemplate(parameters, FTL_ENTITIES_INDEX, file );
+ DocFile docFile = docFileManager.getClassIndexDocFile();
+ File file = docFile.getFile();
+ Map parameters = new HashMap<>();
+ parameters.put("docFile", docFile);
+ processTemplate(parameters, FTL_ENTITIES_INDEX, file );
}
/**
* Generate a file with an summary of all the tables.
- * @param graphsGenerated
*/
public void generateTablesSummary(boolean graphsGenerated) {
DocFile docFile = docFileManager.getTableSummaryDocFile();
File file = docFileManager.getTableSummaryDocFile().getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
- parameters.put( "graphsGenerated", Boolean.valueOf( graphsGenerated ) );
+ parameters.put( "graphsGenerated", graphsGenerated );
if(graphsGenerated) {
- StringBuffer sb = new StringBuffer();
- String fileName = "tables/tablegraph.cmapx";
- appendFile( sb, fileName );
+ StringBuffer sb = new StringBuffer();
+ String fileName = "tables/tablegraph.cmapx";
+ appendFile( sb, fileName );
parameters.put( "tablegrapharea", sb );
}
-
+
processTemplate(parameters, FTL_TABLES_SUMMARY, file);
}
- private void appendFile(StringBuffer sb, String fileName) {
- try {
- BufferedReader in = new BufferedReader(new FileReader(new File(getOutputDirectory(), fileName)));
- String str;
-
- while ((str = in.readLine()) != null) {
- sb.append(str);
- sb.append(System.getProperty("line.separator"));
- }
-
- in.close();
- } catch (IOException e) {
- }
- }
-
- /**
- * Generate summary (summaty.html) to show all the packages
+ private void appendFile(StringBuffer sb, String fileName) {
+ try {
+ BufferedReader in = new BufferedReader(new FileReader(new File(getOutputDirectory(), fileName)));
+ String str;
+
+ while ((str = in.readLine()) != null) {
+ sb.append(str);
+ sb.append( System.lineSeparator() );
+ }
+
+ in.close();
+ }
+ catch (IOException ignored) {}
+ }
+
+ /**
+ * Generate summary (summaty.html) to show all the packages
*
*/
public void generatePackageSummary(boolean graphsGenerated){
- DocFile docFile = docFileManager.getClassSummaryFile();
- File file = docFile.getFile();
-
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
-
+ DocFile docFile = docFileManager.getClassSummaryFile();
+ File file = docFile.getFile();
+
+ Map parameters = new HashMap<>();
+ parameters.put("docFile", docFile);
+
List list = docHelper.getPackages();
- if (list.size() > 0){
- //Remove All Classes
- list.remove(0);
- }
+ if ( !list.isEmpty() ){
+ //Remove All Classes
+ list.remove(0);
+ }
parameters.put("packageList", list );
- parameters.put( "graphsGenerated", Boolean.valueOf( graphsGenerated ) );
+ parameters.put( "graphsGenerated", graphsGenerated );
if(graphsGenerated) {
- StringBuffer sb = new StringBuffer();
- String fileName = "entities/entitygraph.cmapx";
- appendFile( sb, fileName );
+ StringBuffer sb = new StringBuffer();
+ String fileName = "entities/entitygraph.cmapx";
+ appendFile( sb, fileName );
parameters.put( "entitygrapharea", sb );
}
- processTemplate(parameters, FTL_ENTITIES_SUMMARY, file);
+ processTemplate(parameters, FTL_ENTITIES_SUMMARY, file);
}
/**
* Generate one file per table with detail information.
*/
public void generateTablesDetails() {
- Metadata metadata = getMetadata();
- Iterator
tables = metadata.collectTableMappings().iterator();
- while (tables.hasNext() ) {
- Table table = tables.next();
-
- DocFile docFile = docFileManager.getTableDocFile(table);
- if(docFile!=null) {
- File file = docFile.getFile();
+ Metadata metadata = getMetadata();
+ for ( Table table : metadata.collectTableMappings() ) {
+ DocFile docFile = docFileManager.getTableDocFile( table );
+ if ( docFile != null ) {
+ File file = docFile.getFile();
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
- parameters.put("table", table);
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", docFile );
+ parameters.put( "table", table );
- processTemplate(parameters, FTL_TABLES_TABLE, file);
+ processTemplate( parameters, FTL_TABLES_TABLE, file );
}
}
}
-
+
/**
* generates one html file for each class containing detail information of class
*
*/
public void generateEntitiesDetails(){
- Iterator classes = docHelper.getClasses().iterator();
- while(classes.hasNext()){
- POJOClass pcObj = classes.next();
-
- pcObj.getPropertiesForMinimalConstructor();
- DocFile docFile = docFileManager.getEntityDocFile(pcObj);
- File file = docFile.getFile();
-
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
- parameters.put("class", pcObj);
- processTemplate(parameters, FTL_ENTITIES_ENTITY, file);
- }
+ for ( POJOClass pcObj : docHelper.getClasses() ) {
+ pcObj.getPropertiesForMinimalConstructor();
+ DocFile docFile = docFileManager.getEntityDocFile( pcObj );
+ File file = docFile.getFile();
+
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", docFile );
+ parameters.put( "class", pcObj );
+ processTemplate( parameters, FTL_ENTITIES_ENTITY, file );
+ }
}
-
+
/**
* Generates the html file containig list of packages (allpackages.html)
*
@@ -476,18 +473,18 @@ public void generateEntitiesAllPackagesList() {
File file = docFile.getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
List list = docHelper.getPackages();
- if (list.size() > 0){
- //Remove All Classes
+ if ( !list.isEmpty() ){
+ //Remove All Classes
list.remove(0);
}
parameters.put("packageList", list );
processTemplate(parameters, FTL_ENTITIES_PACKAGE_LIST, file);
- }
-
+ }
+
/**
* Generates the html file containing list of classes (allclases.html)
*
@@ -495,65 +492,59 @@ public void generateEntitiesAllPackagesList() {
public void generateEntitiesAllEntitiesList() {
DocFile docFile = docFileManager.getAllEntitiesDocFile();
- File file = docFile.getFile();
+ File file = docFile.getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
- parameters.put("classList", docHelper.getClasses());
+ parameters.put("classList", docHelper.getClasses());
processTemplate(parameters, FTL_ENTITIES_ENTITY_LIST, file);
}
-
+
/**
* generates the list of classes sepcific to package
*
*/
public void generateEntitiesPackageEntityList() {
- Iterator packages = docHelper.getPackages().iterator();
- while (packages.hasNext() ) {
- String packageName = packages.next();
-
- if(!packageName.equals(DocHelper.DEFAULT_NO_PACKAGE)){
- DocFile docFile = docFileManager.getPackageEntityListDocFile(packageName);
+ for ( String packageName : docHelper.getPackages() ) {
+ if ( !packageName.equals( DocHelper.DEFAULT_NO_PACKAGE ) ) {
+ DocFile docFile = docFileManager.getPackageEntityListDocFile( packageName );
File file = docFile.getFile();
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
- parameters.put("title", packageName);
- parameters.put("classList", docHelper.getClasses(packageName));
- processTemplate(parameters, FTL_ENTITIES_PERPACKAGE_ENTITY_LIST, file);
-
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", docFile );
+ parameters.put( "title", packageName );
+ parameters.put( "classList", docHelper.getClasses( packageName ) );
+ processTemplate( parameters, FTL_ENTITIES_PERPACKAGE_ENTITY_LIST, file );
+
}
}
}
-
+
/**
* Generates the html file containing list of classes and interfaces for given package
*
*/
public void generateEntitiesPackageDetailedInfo() {
- List packageList = docHelper.getPackages();
- if (packageList.size() > 0){
- //Remove All Classes
- packageList.remove(0);
- }
- Iterator packages = packageList.iterator();
-
- while (packages.hasNext() ) {
- String packageName = packages.next();
-
- DocFile summaryDocFile = docFileManager.getPackageSummaryDocFile(packageName);
- Map parameters = new HashMap();
- parameters.put("docFile", summaryDocFile);
- parameters.put("package", packageName);
- parameters.put("classList", docHelper.getClasses(packageName));
-
- processTemplate(parameters, FTL_ENTITIES_PACKAGE_SUMMARY,
+ List packageList = docHelper.getPackages();
+ if ( !packageList.isEmpty() ){
+ //Remove All Classes
+ packageList.remove(0);
+ }
+
+ for ( String packageName : packageList ) {
+ DocFile summaryDocFile = docFileManager.getPackageSummaryDocFile( packageName );
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", summaryDocFile );
+ parameters.put( "package", packageName );
+ parameters.put( "classList", docHelper.getClasses( packageName ) );
+
+ processTemplate( parameters, FTL_ENTITIES_PACKAGE_SUMMARY,
summaryDocFile.getFile() );
}
- }
+ }
/**
* Generate a file with a list of all the schemas in the configuration.
@@ -563,7 +554,7 @@ public void generateTablesAllSchemasList() {
File file = docFile.getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
parameters.put("schemaList", docHelper.getSchemas() );
@@ -578,7 +569,7 @@ public void generateTablesAllTablesList() {
File file = docFile.getFile();
- Map parameters = new HashMap();
+ Map parameters = new HashMap<>();
parameters.put("docFile", docFile);
parameters.put("tableList", docHelper.getTables() );
@@ -586,21 +577,18 @@ public void generateTablesAllTablesList() {
}
public void generateTablesSchemaTableList() {
- Iterator schemas = docHelper.getSchemas().iterator();
-
- while (schemas.hasNext() ) {
- String schemaName = schemas.next();
- DocFile docFile = docFileManager.getSchemaTableListDocFile(schemaName);
+ for ( String schemaName : docHelper.getSchemas() ) {
+ DocFile docFile = docFileManager.getSchemaTableListDocFile( schemaName );
File file = docFile.getFile();
- Map parameters = new HashMap();
- parameters.put("docFile", docFile);
- parameters.put("title", schemaName);
- parameters.put("tableList", docHelper.getTables(schemaName) );
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", docFile );
+ parameters.put( "title", schemaName );
+ parameters.put( "tableList", docHelper.getTables( schemaName ) );
- processTemplate(parameters, FTL_TABLES_PERSCHEMA_TABLE_LIST, file);
+ processTemplate( parameters, FTL_TABLES_PERSCHEMA_TABLE_LIST, file );
}
}
@@ -609,48 +597,45 @@ public void generateTablesSchemaTableList() {
* schema and another one with a list of tables.
*/
public void generateTablesSchemaDetailedInfo() {
- Iterator schemas = docHelper.getSchemas().iterator();
- while (schemas.hasNext() ) {
- String schemaName = schemas.next();
-
- DocFile summaryDocFile = docFileManager.getSchemaSummaryDocFile(schemaName);
+ for ( String schemaName : docHelper.getSchemas() ) {
+ DocFile summaryDocFile = docFileManager.getSchemaSummaryDocFile( schemaName );
- Map parameters = new HashMap();
- parameters.put("docFile", summaryDocFile);
- parameters.put("schema", schemaName);
+ Map parameters = new HashMap<>();
+ parameters.put( "docFile", summaryDocFile );
+ parameters.put( "schema", schemaName );
- processTemplate(parameters, FTL_TABLES_SCHEMA_SUMMARY,
+ processTemplate( parameters, FTL_TABLES_SCHEMA_SUMMARY,
summaryDocFile.getFile() );
- DocFile tableListDocFile = docFileManager.getSchemaSummaryDocFile(schemaName);
+ DocFile tableListDocFile = docFileManager.getSchemaSummaryDocFile( schemaName );
- parameters = new HashMap();
- parameters.put("docFile", tableListDocFile);
- parameters.put("schema", schemaName);
+ parameters = new HashMap<>();
+ parameters.put( "docFile", tableListDocFile );
+ parameters.put( "schema", schemaName );
- processTemplate(parameters, FTL_TABLES_SCHEMA_SUMMARY,
+ processTemplate( parameters, FTL_TABLES_SCHEMA_SUMMARY,
tableListDocFile.getFile() );
-
+
//processTemplate( new HashMap(), templateName, outputFile );
}
}
/**
* Run templates.
- *
+ *
* @param parameters the parameters to pass to the templates template.
* @param templateName the template to use.
* @param outputFile the output file.
*/
protected void processTemplate(Map parameters, String templateName,
- File outputFile) {
-
- TemplateProducer producer = new TemplateProducer(getTemplateHelper(), getArtifactCollector() );
- producer.produce(parameters, templateName, outputFile, templateName);
- }
+ File outputFile) {
+
+ TemplateProducer producer = new TemplateProducer(getTemplateHelper(), getArtifactCollector() );
+ producer.produce(parameters, templateName, outputFile, templateName);
+ }
public String getName() {
- return "hbm2doc";
+ return "hbm2doc";
}
-
-}
\ No newline at end of file
+
+}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java
index bf61e16c0d..a531fc1d71 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java
@@ -52,95 +52,87 @@
*/
public final class DocHelper {
- /** used to sort pojoclass according to their declaration name */
- static final Comparator POJOCLASS_COMPARATOR = new Comparator() {
- public int compare(POJOClass left, POJOClass right) {
- return left.getDeclarationName().compareTo(right.getDeclarationName());
- }
- };
-
- /**
- * Used to sort properties according to their name.
- */
- private static final Comparator PROPERTY_COMPARATOR = new Comparator() {
- public int compare(Property left, Property right) {
- return left.getName().compareTo(right.getName());
- }
- };
-
- /**
- * Name to use if the schema is not specified.
- */
- public static final String DEFAULT_NO_SCHEMA_NAME = "default";
-
- /**
- * Name to use if there are no packages specified for any class
- */
- public static final String DEFAULT_NO_PACKAGE = "All Entities";
-
- /**
- * Map with Tables keyed by Schema FQN. The keys are Strings and the values
- * are Lists of Tables
- */
- private final Map> tablesBySchema =
- new HashMap>();
-
- /**
- * Map with classes keyed by package name. PackageName is String key and
- * values are List of POJOClass
- */
- private final Map> classesByPackage =
- new HashMap>();
-
- /**
- * Lits of all POJOClass
- */
- private final List classes =
- new ArrayList();
-
- /**
- * Map where the keys are column names (tableFQN.column) and the values are
- * lists with the Value instances where those columns referenced.
- */
- private final Map> valuesByColumn =
- new HashMap>();
-
- /**
- * Holds intances of Property keyed by Value objects.
- */
- private final Map> propsByValue =
- new HashMap>();
-
- /**
- * List with all the tables.
- */
- private final List
tables = new ArrayList
();
-
- /**
- * Map that holds the Schema FQN for each Table. The keys are Table
- * instances and the values are Strings with the Schema FQN for that table.
- */
- private final Map
tableSchemaNames = new HashMap
();
-
- private final Metadata metadata;
-
- public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2JavaTool) {
-
- super();
-
- if (metadata == null) {
- throw new IllegalArgumentException("Hibernate Configuration cannot be null");
- }
-
- this.metadata = metadata;
-
- StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
- builder.applySettings(properties);
- String defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG);
- String defaultSchema = properties.getProperty(AvailableSettings.DEFAULT_SCHEMA);
- if (defaultSchema == null) {
- defaultSchema = DEFAULT_NO_SCHEMA_NAME;
- }
+ /** used to sort pojoclass according to their declaration name */
+ static final Comparator POJOCLASS_COMPARATOR = Comparator.comparing( POJOClass::getDeclarationName );
+
+ /**
+ * Used to sort properties according to their name.
+ */
+ private static final Comparator PROPERTY_COMPARATOR = Comparator.comparing( Property::getName );
+
+ /**
+ * Name to use if the schema is not specified.
+ */
+ public static final String DEFAULT_NO_SCHEMA_NAME = "default";
+
+ /**
+ * Name to use if there are no packages specified for any class
+ */
+ public static final String DEFAULT_NO_PACKAGE = "All Entities";
+
+ /**
+ * Map with Tables keyed by Schema FQN. The keys are Strings and the values
+ * are Lists of Tables
+ */
+ private final Map> tablesBySchema =
+ new HashMap<>();
+
+ /**
+ * Map with classes keyed by package name. PackageName is String key and
+ * values are List of POJOClass
+ */
+ private final Map> classesByPackage =
+ new HashMap<>();
+
+ /**
+ * Lits of all POJOClass
+ */
+ private final List classes =
+ new ArrayList<>();
+
+ /**
+ * Map where the keys are column names (tableFQN.column) and the values are
+ * lists with the Value instances where those columns referenced.
+ */
+ private final Map> valuesByColumn =
+ new HashMap<>();
+
+ /**
+ * Holds intances of Property keyed by Value objects.
+ */
+ private final Map> propsByValue =
+ new HashMap<>();
+
+ /**
+ * List with all the tables.
+ */
+ private final List
tables = new ArrayList<>();
+
+ /**
+ * Map that holds the Schema FQN for each Table. The keys are Table
+ * instances and the values are Strings with the Schema FQN for that table.
+ */
+ private final Map
tableSchemaNames = new HashMap<>();
+
+ private final Metadata metadata;
+
+ public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2JavaTool) {
+
+ super();
+
+ if (metadata == null) {
+ throw new IllegalArgumentException("Hibernate Configuration cannot be null");
+ }
+
+ this.metadata = metadata;
+
+ StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
+ builder.applySettings(properties);
+ String defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG);
+ String defaultSchema = properties.getProperty(AvailableSettings.DEFAULT_SCHEMA);
+ if (defaultSchema == null) {
+ defaultSchema = DEFAULT_NO_SCHEMA_NAME;
+ }
for (Table table : metadata.collectTableMappings()) {
if (!table.isPhysicalTable()) {
@@ -179,7 +171,7 @@ public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2Java
}
}
- Map components = new HashMap();
+ Map components = new HashMap<>();
for (PersistentClass clazz : metadata.getEntityBindings()) {
POJOClass pojoClazz = cfg2JavaTool.getPOJOClass(clazz);
@@ -199,310 +191,315 @@ public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2Java
new ComponentPOJOClass(component, cfg2JavaTool);
this.processClass(element);
}
- }
+ }
- /**
- * Populate classes List and classesByPackage Map
- */
- private void processClass(POJOClass pojoClazz) {
+ /**
+ * Populate classes List and classesByPackage Map
+ */
+ private void processClass(POJOClass pojoClazz) {
- classes.add(pojoClazz);
- String packageName = pojoClazz.getPackageName();
+ classes.add(pojoClazz);
+ String packageName = pojoClazz.getPackageName();
- if (packageName == null || packageName.isEmpty()) {
- packageName = DEFAULT_NO_PACKAGE;
- }
+ if (packageName == null || packageName.isEmpty()) {
+ packageName = DEFAULT_NO_PACKAGE;
+ }
- List classList = classesByPackage.computeIfAbsent(packageName, k -> new ArrayList());
+ List classList = classesByPackage.computeIfAbsent(packageName, k -> new ArrayList<>());
classList.add(pojoClazz);
- }
-
- /**
- * Return a Map with the tables keyed by Schema. The keys are the schema
- * names and the values are Lists of tables.
- *
- * @return a Map with the tables keyed by Schema Name.
- */
- public Map> getTablesBySchema() {
- return tablesBySchema;
- }
-
- /**
- * return a Map which has List of POJOClass as value keyed by package name
- * as String.
- */
- public Map> getClassesByPackage() {
- return classesByPackage;
- }
-
- /**
- * Returns a list with all the schemas.
- *
- * @return a list with all the schemas.
- */
- public List getSchemas() {
- List schemas = new ArrayList(tablesBySchema.keySet());
- Collections.sort(schemas);
- return schemas;
- }
-
- /**
- * Return a sorted List of packages
- */
- public List getPackages() {
- List packages = new ArrayList(classesByPackage.keySet());
- Collections.sort(packages);
- return packages;
- }
-
- /**
- * Return the list of tables for a particular schema.
- *
- * @param schema
- * the name of the schema.
- *
- * @return a list with all the tables.
- */
- public List
getTables(String schema) {
+ }
+
+ /**
+ * Return a Map with the tables keyed by Schema. The keys are the schema
+ * names and the values are Lists of tables.
+ *
+ * @return a Map with the tables keyed by Schema Name.
+ */
+ public Map> getTablesBySchema() {
+ return tablesBySchema;
+ }
+
+ /**
+ * return a Map which has List of POJOClass as value keyed by package name
+ * as String.
+ */
+ public Map> getClassesByPackage() {
+ return classesByPackage;
+ }
+
+ /**
+ * Returns a list with all the schemas.
+ *
+ * @return a list with all the schemas.
+ */
+ public List getSchemas() {
+ List schemas = new ArrayList<>( tablesBySchema.keySet() );
+ Collections.sort(schemas);
+ return schemas;
+ }
+
+ /**
+ * Return a sorted List of packages
+ */
+ public List getPackages() {
+ List packages = new ArrayList<>( classesByPackage.keySet() );
+ Collections.sort(packages);
+ return packages;
+ }
+
+ /**
+ * Return the list of tables for a particular schema.
+ *
+ * @param schema
+ * the name of the schema.
+ *
+ * @return a list with all the tables.
+ */
+ public List
getTables(String schema) {
return tablesBySchema.get(schema);
- }
-
- /**
- * return a sorted List of POJOClass corresponding to packageName passed
- *
- * @param packageName
- * packageName other than DEFAULT_NO_PACKAGE
- * @return a sorted List of POJOClass
- */
- public List getClasses(String packageName) {
- List clazzes = classesByPackage.get(packageName);
- List orderedClasses = new ArrayList(clazzes);
- orderedClasses.sort(POJOCLASS_COMPARATOR);
- return orderedClasses;
- }
-
- /**
- * Return all the tables.
- *
- * @return all the tables.
- */
- public List
getTables() {
- return tables;
- }
-
- /**
- * Return a sorted List of all POJOClass
- */
- public List getClasses() {
- List orderedClasses = new ArrayList(classes);
- orderedClasses.sort(POJOCLASS_COMPARATOR);
- return orderedClasses;
- }
-
- /**
- * Returns the qualified schema name for a table. The qualified schema name
- * will include the catalog name if one is specified.
- *
- * @param table
- * the table.
- *
- * @return the qualified schema name for the table.
- */
- public String getQualifiedSchemaName(Table table) {
-
- return (String) tableSchemaNames.get(table);
- }
-
- /**
- * Returns the qualified name of a table.
- *
- * @param table
- * the table.
- *
- * @return the qualified name of the table.
- */
- public String getQualifiedTableName(Table table) {
-
- String qualifiedSchemaName = getQualifiedSchemaName(table);
-
- return qualifiedSchemaName + '.' + table.getName();
- }
-
- public String getPropertyType(Property p) {
- Value v = p.getValue();
- Type t;
- String propertyString = "N/D";
- try {
- t = v.getType();
- propertyString = t.getReturnedClass().getName();
-
- } catch (Exception ex) {
- // TODO we should try to get the value from value here
- // Eat Exception??
- }
-
- return propertyString;
- }
-
- /**
- * Returns the qualified name of a column.
- *
- * @param table
- * the table.
- * @param column
- * the column
- *
- * @return the FQN of the column.
- */
- public String getQualifiedColumnName(Table table, Column column) {
- String qualifiedTableName = getQualifiedTableName(table);
- return qualifiedTableName + '.' + column.getName();
- }
-
- /**
- * Get the SQL type name for a column.
- *
- * @param column
- * the column.
- *
- * @return a String with the SQL type name.
- */
- public String getSQLTypeName(Column column) {
-
- try {
- return column.getSqlType(metadata);
- } catch (HibernateException ex) {
-
- // TODO: Fix this when we find a way to get the type or
- // the mapping.
-
- return "N/D";
- }
- }
-
- public int getLength(Column column) {
- return column.getLength() == null ?
- TypeUtils.DEFAULT_COLUMN_LENGTH :
- column.getLength().intValue();
- }
-
- public int getPrecision(Column column) {
- return column.getPrecision() == null ?
- TypeUtils.DEFAULT_COLUMN_PRECISION :
+ }
+
+ /**
+ * return a sorted List of POJOClass corresponding to packageName passed
+ *
+ * @param packageName
+ * packageName other than DEFAULT_NO_PACKAGE
+ * @return a sorted List of POJOClass
+ */
+ public List getClasses(String packageName) {
+ List clazzes = classesByPackage.get(packageName);
+ List orderedClasses = new ArrayList<>( clazzes );
+ orderedClasses.sort(POJOCLASS_COMPARATOR);
+ return orderedClasses;
+ }
+
+ /**
+ * Return all the tables.
+ *
+ * @return all the tables.
+ */
+ public List
getTables() {
+ return tables;
+ }
+
+ /**
+ * Return a sorted List of all POJOClass
+ */
+ public List getClasses() {
+ List orderedClasses = new ArrayList<>( classes );
+ orderedClasses.sort(POJOCLASS_COMPARATOR);
+ return orderedClasses;
+ }
+
+ /**
+ * Returns the qualified schema name for a table. The qualified schema name
+ * will include the catalog name if one is specified.
+ *
+ * @param table
+ * the table.
+ *
+ * @return the qualified schema name for the table.
+ */
+ public String getQualifiedSchemaName(Table table) {
+
+ return (String) tableSchemaNames.get(table);
+ }
+
+ /**
+ * Returns the qualified name of a table.
+ *
+ * @param table
+ * the table.
+ *
+ * @return the qualified name of the table.
+ */
+ public String getQualifiedTableName(Table table) {
+
+ String qualifiedSchemaName = getQualifiedSchemaName(table);
+
+ return qualifiedSchemaName + '.' + table.getName();
+ }
+
+ public String getPropertyType(Property p) {
+ Value v = p.getValue();
+ Type t;
+ String propertyString = "N/D";
+ try {
+ t = v.getType();
+ propertyString = t.getReturnedClass().getName();
+
+ }
+ catch (Exception ex) {
+ // TODO we should try to get the value from value here
+ // Eat Exception??
+ }
+
+ return propertyString;
+ }
+
+ /**
+ * Returns the qualified name of a column.
+ *
+ * @param table
+ * the table.
+ * @param column
+ * the column
+ *
+ * @return the FQN of the column.
+ */
+ public String getQualifiedColumnName(Table table, Column column) {
+ String qualifiedTableName = getQualifiedTableName(table);
+ return qualifiedTableName + '.' + column.getName();
+ }
+
+ /**
+ * Get the SQL type name for a column.
+ *
+ * @param column
+ * the column.
+ *
+ * @return a String with the SQL type name.
+ */
+ public String getSQLTypeName(Column column) {
+
+ try {
+ return column.getSqlType(metadata);
+ }
+ catch (HibernateException ex) {
+
+ // TODO: Fix this when we find a way to get the type or
+ // the mapping.
+
+ return "N/D";
+ }
+ }
+
+ public int getLength(Column column) {
+ return column.getLength() == null ?
+ TypeUtils.DEFAULT_COLUMN_LENGTH :
+ column.getLength().intValue();
+ }
+
+ public int getPrecision(Column column) {
+ return column.getPrecision() == null ?
+ TypeUtils.DEFAULT_COLUMN_PRECISION :
column.getPrecision();
- }
+ }
- public int getScale(Column column) {
- return column.getScale() == null ?
- TypeUtils.DEFAULT_COLUMN_SCALE :
+ public int getScale(Column column) {
+ return column.getScale() == null ?
+ TypeUtils.DEFAULT_COLUMN_SCALE :
column.getScale();
- }
-
- public Iterator getPrimaryKeyColumnIterator(Table table) {
- return table.getPrimaryKey().getColumns().iterator();
- }
-
- /**
- * Returns the values that use the specified column.
- *
- * @param table
- * the table.
- * @param column
- * the column.
- *
- * @return a list with the values.
- */
- public List getValues(Table table, Column column) {
- String columnFQN = getQualifiedColumnName(table, column);
- List values = valuesByColumn.get(columnFQN);
- if (values != null) {
- return values;
- } else {
- return new ArrayList();
- }
- }
-
- /**
- * Returns the properties that map to a column.
- *
- * @param table
- * the table.
- * @param column
- * the column.
- *
- * @return a list of properties.
- */
- public List getProperties(Table table, Column column) {
-
- List result = new ArrayList();
+ }
+
+ public Iterator getPrimaryKeyColumnIterator(Table table) {
+ return table.getPrimaryKey().getColumns().iterator();
+ }
+
+ /**
+ * Returns the values that use the specified column.
+ *
+ * @param table
+ * the table.
+ * @param column
+ * the column.
+ *
+ * @return a list with the values.
+ */
+ public List getValues(Table table, Column column) {
+ String columnFQN = getQualifiedColumnName(table, column);
+ List values = valuesByColumn.get(columnFQN);
+ if (values != null) {
+ return values;
+ }
+ else {
+ return new ArrayList<>();
+ }
+ }
+
+ /**
+ * Returns the properties that map to a column.
+ *
+ * @param table
+ * the table.
+ * @param column
+ * the column.
+ *
+ * @return a list of properties.
+ */
+ public List getProperties(Table table, Column column) {
+
+ List result = new ArrayList<>();
for (Value value : getValues(table, column)) {
List props = propsByValue.get(value);
if (props != null) {
result.addAll(props);
}
}
- return result;
- }
-
- /**
- * Method used in class.vm template to get the ComponentPOJO class
- * corresponding to Property if its of Type Component.
- *
- * @param property
- * Get ComponentPOJO corresponding to this Property
- * @return POJOClass for Property
- */
- // TODO We haven't taken into account Array?
- public POJOClass getComponentPOJO(Property property) {
- if (property.getValue() instanceof Component comp) {
+ return result;
+ }
+
+ /**
+ * Method used in class.vm template to get the ComponentPOJO class
+ * corresponding to Property if its of Type Component.
+ *
+ * @param property
+ * Get ComponentPOJO corresponding to this Property
+ * @return POJOClass for Property
+ */
+ // TODO We haven't taken into account Array?
+ public POJOClass getComponentPOJO(Property property) {
+ if (property.getValue() instanceof Component comp) {
return new ComponentPOJOClass(comp, new Cfg2JavaTool());
- } else {
- return null;
- }
- }
-
- public List getInheritanceHierarchy(POJOClass pc) {
- if (pc.isSubclass()) {
- List superClasses = new ArrayList();
- POJOClass superClass = pc.getSuperClass();
- while (superClass != null) {
- superClasses.add(superClass);
- superClass = superClass.getSuperClass();
- }
- return superClasses;
- } else {
- return Collections.emptyList();
- }
- }
-
- public List getOrderedProperties(POJOClass pojoClass) {
- List orderedProperties = getAllProperties(pojoClass);
- orderedProperties.sort(PROPERTY_COMPARATOR);
-
- return orderedProperties;
- }
-
- public List getSimpleProperties(POJOClass pojoClass) {
- List properties = getAllProperties(pojoClass);
- if (pojoClass.hasIdentifierProperty())
- properties.remove(pojoClass.getIdentifierProperty());
- // TODO: do we need to also remove component id properties?
- if (pojoClass.hasVersionProperty())
- properties.remove(pojoClass.getVersionProperty());
- return properties;
- }
-
- public List getOrderedSimpleProperties(POJOClass pojoClass) {
- List orderedProperties = getSimpleProperties(pojoClass);
- orderedProperties.sort(PROPERTY_COMPARATOR);
- return orderedProperties;
- }
-
- private List getAllProperties(POJOClass pojoClass) {
- List properties = new ArrayList();
- for (Iterator iterator = pojoClass.getAllPropertiesIterator(); iterator.hasNext();)
- properties.add(iterator.next());
- return properties;
- }
-
+ }
+ else {
+ return null;
+ }
+ }
+
+ public List getInheritanceHierarchy(POJOClass pc) {
+ if (pc.isSubclass()) {
+ List superClasses = new ArrayList<>();
+ POJOClass superClass = pc.getSuperClass();
+ while (superClass != null) {
+ superClasses.add(superClass);
+ superClass = superClass.getSuperClass();
+ }
+ return superClasses;
+ }
+ else {
+ return Collections.emptyList();
+ }
+ }
+
+ public List getOrderedProperties(POJOClass pojoClass) {
+ List orderedProperties = getAllProperties(pojoClass);
+ orderedProperties.sort(PROPERTY_COMPARATOR);
+
+ return orderedProperties;
+ }
+
+ public List getSimpleProperties(POJOClass pojoClass) {
+ List properties = getAllProperties(pojoClass);
+ if (pojoClass.hasIdentifierProperty())
+ properties.remove(pojoClass.getIdentifierProperty());
+ // TODO: do we need to also remove component id properties?
+ if (pojoClass.hasVersionProperty())
+ properties.remove(pojoClass.getVersionProperty());
+ return properties;
+ }
+
+ public List getOrderedSimpleProperties(POJOClass pojoClass) {
+ List orderedProperties = getSimpleProperties(pojoClass);
+ orderedProperties.sort(PROPERTY_COMPARATOR);
+ return orderedProperties;
+ }
+
+ private List getAllProperties(POJOClass pojoClass) {
+ List properties = new ArrayList<>();
+ for (Iterator iterator = pojoClass.getAllPropertiesIterator(); iterator.hasNext();)
+ properties.add(iterator.next());
+ return properties;
+ }
+
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java b/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java
index 7f87bc222d..864a14f48b 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java
@@ -17,11 +17,7 @@
*/
package org.hibernate.tool.internal.export.hbm;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
+import java.util.*;
import java.util.function.Consumer;
import org.hibernate.FetchMode;
@@ -65,45 +61,45 @@
*/
public class Cfg2HbmTool {
- private static final class HasEntityPersisterVisitor implements PersistentClassVisitor {
- private final String name;
-
- private HasEntityPersisterVisitor(String name) {
- this.name = name;
- }
-
- public Object accept(Subclass subclass) {
- return bool(!SingleTableEntityPersister.class.getName().equals(name));
- }
-
- private Object bool(boolean b) {
- return b;
- }
-
- public Object accept(JoinedSubclass subclass) {
- return bool(!JoinedSubclassEntityPersister.class.getName().equals(name));
- }
-
- public Object accept(SingleTableSubclass subclass) {
- return bool(!SingleTableEntityPersister.class.getName().equals(name));
- }
-
- public Object accept(UnionSubclass subclass) {
- return bool(!UnionSubclassEntityPersister.class.getName().equals(name));
- }
-
- public Object accept(RootClass class1) {
- return bool(!SingleTableEntityPersister.class.getName().equals(name));
- }
- }
-
- /**
- * Remove any internal keys from the set, eg, any Keys that are prefixed by
- * 'target_' and return the filtered collection.
- */
- public static Properties getFilteredIdentifierGeneratorProperties(Properties properties, Properties environmentProperties) {
- if (properties != null){
- Properties fProp = new Properties();
+ private static final class HasEntityPersisterVisitor implements PersistentClassVisitor {
+ private final String name;
+
+ private HasEntityPersisterVisitor(String name) {
+ this.name = name;
+ }
+
+ public Object accept(Subclass subclass) {
+ return bool(!SingleTableEntityPersister.class.getName().equals(name));
+ }
+
+ private Object bool(boolean b) {
+ return b;
+ }
+
+ public Object accept(JoinedSubclass subclass) {
+ return bool(!JoinedSubclassEntityPersister.class.getName().equals(name));
+ }
+
+ public Object accept(SingleTableSubclass subclass) {
+ return bool(!SingleTableEntityPersister.class.getName().equals(name));
+ }
+
+ public Object accept(UnionSubclass subclass) {
+ return bool(!UnionSubclassEntityPersister.class.getName().equals(name));
+ }
+
+ public Object accept(RootClass class1) {
+ return bool(!SingleTableEntityPersister.class.getName().equals(name));
+ }
+ }
+
+ /**
+ * Remove any internal keys from the set, eg, any Keys that are prefixed by
+ * 'target_' and return the filtered collection.
+ */
+ public static Properties getFilteredIdentifierGeneratorProperties(Properties properties, Properties environmentProperties) {
+ if (properties != null){
+ Properties fProp = new Properties();
for (Object o : properties.keySet()) {
String key = (String) o;
if ("schema".equals(key)) {
@@ -111,101 +107,105 @@ public static Properties getFilteredIdentifierGeneratorProperties(Properties pro
if (!isDefaultSchema(schema, environmentProperties)) {
fProp.put(key, schema);
}
- } else if ("catalog".equals(key)) {
+ }
+ else if ("catalog".equals(key)) {
String catalog = properties.getProperty(key);
if (!isDefaultCatalog(catalog, environmentProperties)) {
fProp.put(key, catalog);
}
- } else if (!key.startsWith("target_")) {
+ }
+ else if (!key.startsWith("target_")) {
fProp.put(key, properties.get(key));
}
}
- return fProp;
- }
- return null;
- }
-
- static private boolean isDefaultSchema(String schema, Properties properties) {
- String defaultSchema = properties.getProperty(Environment.DEFAULT_SCHEMA);
- return defaultSchema == null ? schema == null : defaultSchema.equals(schema);
- }
-
- static private boolean isDefaultCatalog(String catalog, Properties properties) {
- String defaultCatalog = properties.getProperty(Environment.DEFAULT_CATALOG);
- return defaultCatalog == null ? catalog == null : defaultCatalog.equals(catalog);
- }
-
- public String getTag(PersistentClass pc) {
- return (String) pc.accept(HBMTagForPersistentClassVisitor.INSTANCE);
- }
-
- public String getTag(Property property) {
- PersistentClass persistentClass = property.getPersistentClass();
- if(persistentClass!=null) {
- if(persistentClass.getVersion()==property) {
- String typeName = ((SimpleValue)property.getValue()).getTypeName();
- if("timestamp".equals(typeName) || "dbtimestamp".equals(typeName)) {
- return "timestamp";
- } else {
- return "version";
- }
- }
- }
- String toolTag = (String) property.getValue().accept(HBMTagForValueVisitor.INSTANCE);
- if ("component".equals(toolTag) && "embedded".equals(property.getPropertyAccessorName())){
- toolTag = "properties";
- }
- return toolTag;
- }
-
- public String getCollectionElementTag(Property property){
- Value value = property.getValue();
- if (isOneToMany(value)) return "one-to-many";
- if (isManyToMany(value)) return "many-to-many";
- if (isManyToAny(value)) return "many-to-any";
- if (((Collection)value).getElement() instanceof Component){
- return "composite";
- }
- return "element";
- }
-
-
- public boolean isUnsavedValue(Property property) {
- SimpleValue sv = (SimpleValue) property.getValue();
- return (sv.getNullValue() != null) && !"undefined".equals(sv.getNullValue());
- }
-
- public String getUnsavedValue(Property property) {
- return ( (SimpleValue) property.getValue() ).getNullValue();
- }
-
- public boolean isIdentifierGeneratorProperties(Property property) {
- Properties val = this.getIdentifierGeneratorProperties(property);
- return val != null;
- }
-
- public Properties getIdentifierGeneratorProperties(Property property) {
- Properties result = null;
- SimpleValue simpleValue = (SimpleValue)property.getValue();
- if (simpleValue instanceof EnhancedValue) {
- Properties idGenParams = ((EnhancedValue)simpleValue).getIdentifierGeneratorProperties();
- if (idGenParams != null) {
- result = new Properties();
- result.putAll(idGenParams);
- }
- } else {
- Map properties = new ValueUtil(simpleValue).getIdentifierGeneratorParameters();
- if (properties != null) {
- result = new Properties();
- result.putAll(properties);
- }
- }
- return result;
- }
-
- public Set> getFilteredIdentifierGeneratorKeySet(Property property, Properties props) {
- return getFilteredIdentifierGeneratorProperties(this.getIdentifierGeneratorProperties(property), props).keySet();
- }
+ return fProp;
+ }
+ return null;
+ }
+
+ static private boolean isDefaultSchema(String schema, Properties properties) {
+ String defaultSchema = properties.getProperty(Environment.DEFAULT_SCHEMA);
+ return Objects.equals( defaultSchema, schema );
+ }
+
+ static private boolean isDefaultCatalog(String catalog, Properties properties) {
+ String defaultCatalog = properties.getProperty(Environment.DEFAULT_CATALOG);
+ return Objects.equals( defaultCatalog, catalog );
+ }
+
+ public String getTag(PersistentClass pc) {
+ return (String) pc.accept(HBMTagForPersistentClassVisitor.INSTANCE);
+ }
+
+ public String getTag(Property property) {
+ PersistentClass persistentClass = property.getPersistentClass();
+ if(persistentClass!=null) {
+ if(persistentClass.getVersion()==property) {
+ String typeName = ((SimpleValue)property.getValue()).getTypeName();
+ if("timestamp".equals(typeName) || "dbtimestamp".equals(typeName)) {
+ return "timestamp";
+ }
+ else {
+ return "version";
+ }
+ }
+ }
+ String toolTag = (String) property.getValue().accept(HBMTagForValueVisitor.INSTANCE);
+ if ("component".equals(toolTag) && "embedded".equals(property.getPropertyAccessorName())){
+ toolTag = "properties";
+ }
+ return toolTag;
+ }
+
+ public String getCollectionElementTag(Property property){
+ Value value = property.getValue();
+ if (isOneToMany(value)) return "one-to-many";
+ if (isManyToMany(value)) return "many-to-many";
+ if (isManyToAny(value)) return "many-to-any";
+ if (((Collection)value).getElement() instanceof Component){
+ return "composite";
+ }
+ return "element";
+ }
+
+
+ public boolean isUnsavedValue(Property property) {
+ SimpleValue sv = (SimpleValue) property.getValue();
+ return (sv.getNullValue() != null) && !"undefined".equals(sv.getNullValue());
+ }
+
+ public String getUnsavedValue(Property property) {
+ return ( (SimpleValue) property.getValue() ).getNullValue();
+ }
+
+ public boolean isIdentifierGeneratorProperties(Property property) {
+ Properties val = this.getIdentifierGeneratorProperties(property);
+ return val != null;
+ }
+
+ public Properties getIdentifierGeneratorProperties(Property property) {
+ Properties result = null;
+ SimpleValue simpleValue = (SimpleValue)property.getValue();
+ if (simpleValue instanceof EnhancedValue) {
+ Properties idGenParams = ((EnhancedValue)simpleValue).getIdentifierGeneratorProperties();
+ if (idGenParams != null) {
+ result = new Properties();
+ result.putAll(idGenParams);
+ }
+ }
+ else {
+ Map properties = new ValueUtil(simpleValue).getIdentifierGeneratorParameters();
+ if (properties != null) {
+ result = new Properties();
+ result.putAll(properties);
+ }
+ }
+ return result;
+ }
+
+ public Set> getFilteredIdentifierGeneratorKeySet(Property property, Properties props) {
+ return getFilteredIdentifierGeneratorProperties(this.getIdentifierGeneratorProperties(property), props).keySet();
+ }
public boolean isOneToMany(Property property) {
return isOneToMany(property.getValue());
@@ -215,206 +215,198 @@ public boolean isOneToMany(Value value) {
if(value instanceof Collection) {
return ( (Collection)value ).isOneToMany();
}
- else
- return value instanceof OneToMany;
+ else
+ return value instanceof OneToMany;
}
- public boolean isManyToMany(Property property) {
- return isManyToMany(property.getValue());
+ public boolean isManyToMany(Property property) {
+ return isManyToMany(property.getValue());
}
public boolean isManyToMany(Value value) {
- return (value instanceof Collection &&
- ((Collection)value).getElement() instanceof ManyToOne);
+ return (value instanceof Collection &&
+ ((Collection)value).getElement() instanceof ManyToOne);
}
- public boolean isCollection(Property property) {
+ public boolean isCollection(Property property) {
return property.getValue() instanceof Collection;
}
- public boolean isOneToManyCollection(Property property) {
- return isCollection(property) && ((Collection)property.getValue()).isOneToMany();
- }
+ public boolean isOneToManyCollection(Property property) {
+ return isCollection(property) && ((Collection)property.getValue()).isOneToMany();
+ }
- public boolean isSimpleValue(Property property) {
+ public boolean isSimpleValue(Property property) {
return (property.getValue() instanceof SimpleValue);
- }
+ }
- public boolean isManyToOne(Property property) {
+ public boolean isManyToOne(Property property) {
return isManyToOne(property.getValue());
}
- public boolean isManyToAny(Property property) {
+ public boolean isManyToAny(Property property) {
return isManyToAny(property.getValue());
}
- public boolean isManyToAny(Value value) {
+ public boolean isManyToAny(Value value) {
return (value instanceof Collection &&
- ((Collection)value).getElement() instanceof Any);
+ ((Collection)value).getElement() instanceof Any);
}
- public boolean isManyToOne(Value value) {
+ public boolean isManyToOne(Value value) {
return (value instanceof ManyToOne);
}
- public boolean isOneToOne(Property property) {
+ public boolean isOneToOne(Property property) {
return (property.getValue() instanceof OneToOne);
}
- public boolean isTemporalValue(Property property) {
- if(property.getValue() instanceof SimpleValue) {
- String typeName = ((SimpleValue)property.getValue()).getTypeName();
- if("date".equals(typeName) || "java.sql.Date".equals(typeName)) {
- return true;
- } else if ("timestamp".equals(typeName) || "java.sql.Timestamp".equals(typeName)) {
- return true;
- } else return "time".equals(typeName) || "java.sql.Time".equals(typeName);
- }
- return false;
- }
+ public boolean isTemporalValue(Property property) {
+ if(property.getValue() instanceof SimpleValue) {
+ String typeName = ((SimpleValue)property.getValue()).getTypeName();
+ if("date".equals(typeName) || "java.sql.Date".equals(typeName)) {
+ return true;
+ }
+ else if ("timestamp".equals(typeName) || "java.sql.Timestamp".equals(typeName)) {
+ return true;
+ }
+ else return "time".equals(typeName) || "java.sql.Time".equals(typeName);
+ }
+ return false;
+ }
public boolean isNamedQueries(Metadata md) {
- final ArrayList> list = new ArrayList>();
- Consumer> consumer = new Consumer>() {
- @Override
- public void accept(NamedHqlQueryDefinition> namedHqlQueryDefinition) {
- list.add(namedHqlQueryDefinition);
- }
- };
- md.visitNamedHqlQueryDefinitions(consumer);
- return !list.isEmpty();
- }
-
- public boolean isNamedSQLQueries(Metadata md) {
- final ArrayList> list = new ArrayList>();
- Consumer> consumer = new Consumer>() {
- @Override
- public void accept(NamedNativeQueryDefinition> namedHqlQueryDefinition) {
- list.add(namedHqlQueryDefinition);
- }
- };
- md.visitNamedNativeQueryDefinitions(consumer);
- return !list.isEmpty();
- }
-
-
- public String getCollectionLazy(Collection value){
- return value.isExtraLazy() ? "extra" : Boolean.toString(value.isLazy());
- }
-
- public boolean isFilterDefinitions(Metadata md) {
- Map filterdefs = md.getFilterDefinitions();
- return filterdefs != null && !filterdefs.isEmpty();
- }
-
- public boolean isClassLevelOptimisticLockMode(PersistentClass pc) {
- return pc.getOptimisticLockStyle() != OptimisticLockStyle.VERSION;
- }
-
- public String getClassLevelOptimisticLockMode(PersistentClass pc) {
- OptimisticLockStyle oMode = pc.getOptimisticLockStyle();
- if ( oMode == OptimisticLockStyle.DIRTY ) {
- return "dirty";
- }
- else if ( oMode == OptimisticLockStyle.ALL ) {
- return "all";
- }
- else if ( oMode == OptimisticLockStyle.NONE ) {
- return "none";
- }
- else {
- return "version";
- }
- }
-
- public boolean hasFetchMode(Property property) {
- String fetch = getFetchMode(property);
+ final ArrayList> list = new ArrayList<>();
+ Consumer> consumer = list::add;
+ md.visitNamedHqlQueryDefinitions(consumer);
+ return !list.isEmpty();
+ }
+
+ public boolean isNamedSQLQueries(Metadata md) {
+ final ArrayList> list = new ArrayList<>();
+ Consumer> consumer = list::add;
+ md.visitNamedNativeQueryDefinitions(consumer);
+ return !list.isEmpty();
+ }
+
+
+ public String getCollectionLazy(Collection value){
+ return value.isExtraLazy() ? "extra" : Boolean.toString(value.isLazy());
+ }
+
+ public boolean isFilterDefinitions(Metadata md) {
+ Map filterdefs = md.getFilterDefinitions();
+ return filterdefs != null && !filterdefs.isEmpty();
+ }
+
+ public boolean isClassLevelOptimisticLockMode(PersistentClass pc) {
+ return pc.getOptimisticLockStyle() != OptimisticLockStyle.VERSION;
+ }
+
+ public String getClassLevelOptimisticLockMode(PersistentClass pc) {
+ OptimisticLockStyle oMode = pc.getOptimisticLockStyle();
+ if ( oMode == OptimisticLockStyle.DIRTY ) {
+ return "dirty";
+ }
+ else if ( oMode == OptimisticLockStyle.ALL ) {
+ return "all";
+ }
+ else if ( oMode == OptimisticLockStyle.NONE ) {
+ return "none";
+ }
+ else {
+ return "version";
+ }
+ }
+
+ public boolean hasFetchMode(Property property) {
+ String fetch = getFetchMode(property);
return fetch != null && !"default".equals(fetch);
- }
- public String getFetchMode(Property property) {
- FetchMode fetchMode = property.getValue().getFetchMode();
- return (fetchMode== null) ? null : fetchMode.toString().toLowerCase();
- }
-
-
- public Formula getFormulaForProperty(Property prop) {
- for (Selectable selectable : prop.getValue().getSelectables()) {
- if (selectable instanceof Formula)
- return (Formula) selectable;
- }
- return null;
- }
-
- public String columnAttributes(Column col) {
- return columnAttributes(col, false);
- }
-
- public String columnAttributes(Column column, boolean isPrimaryKeyColumn) {
- StringBuilder sb = new StringBuilder();
- if (column.getPrecision() != null) {
- sb.append("precision=\"").append(column.getPrecision() ).append("\" ");
- }
- if (column.getScale() != null) {
- sb.append("scale=\"").append(column.getScale() ).append("\" ");
- }
- else if (column.getLength() != null){
- sb.append("length=\"").append(column.getLength() ).append("\" ");
- }
- if (!isPrimaryKeyColumn) {
- if (!column.isNullable() ) {
- sb.append("not-null=\"true\" ");
- }
- if (column.isUnique() ) {
- sb.append("unique=\"true\" ");
- }
- }
- if (column.getSqlType() != null) {
- sb.append("sql-type=\""); sb.append(column.getSqlType() ); sb.append("\" ");
- }
- return sb.toString();
- }
-
- public String getClassName(PersistentClass pc) {
- if (pc.hasPojoRepresentation() ) {
- return pc.getClassName();
- }
- else {
- // todo: return null?
- throw new RuntimeException(pc + " does not have a pojo rep.");
- }
- }
-
- public String getClassName(OneToMany om) {
- return om.getAssociatedClass().getClassName();
- }
-
- public String getProxyInterfaceName(PersistentClass pc) {
- if (pc.hasPojoRepresentation() ) {
- return pc.getProxyInterfaceName();
- }
- else {
- throw new RuntimeException(pc + " does not have a pojo rep.");
- }
- }
-
- public boolean isImportData(Metadata md) {
- return !(md.getImports().isEmpty());
- }
-
- public boolean needsDiscriminatorElement(PersistentClass clazz) {
- return clazz instanceof RootClass
- && (clazz.getDiscriminator() != null);
- }
-
- public boolean needsDiscriminator(PersistentClass clazz) {
-
- return clazz instanceof Subclass
- && !(clazz instanceof UnionSubclass) && !(clazz instanceof JoinedSubclass);
- }
-
-
- public boolean needsTable(PersistentClass clazz) {
+ }
+ public String getFetchMode(Property property) {
+ FetchMode fetchMode = property.getValue().getFetchMode();
+ return (fetchMode== null) ? null : fetchMode.toString().toLowerCase();
+ }
+
+
+ public Formula getFormulaForProperty(Property prop) {
+ for (Selectable selectable : prop.getValue().getSelectables()) {
+ if (selectable instanceof Formula)
+ return (Formula) selectable;
+ }
+ return null;
+ }
+
+ public String columnAttributes(Column col) {
+ return columnAttributes(col, false);
+ }
+
+ public String columnAttributes(Column column, boolean isPrimaryKeyColumn) {
+ StringBuilder sb = new StringBuilder();
+ if (column.getPrecision() != null) {
+ sb.append("precision=\"").append(column.getPrecision() ).append("\" ");
+ }
+ if (column.getScale() != null) {
+ sb.append("scale=\"").append(column.getScale() ).append("\" ");
+ }
+ else if (column.getLength() != null){
+ sb.append("length=\"").append(column.getLength() ).append("\" ");
+ }
+ if (!isPrimaryKeyColumn) {
+ if (!column.isNullable() ) {
+ sb.append("not-null=\"true\" ");
+ }
+ if (column.isUnique() ) {
+ sb.append("unique=\"true\" ");
+ }
+ }
+ if (column.getSqlType() != null) {
+ sb.append("sql-type=\""); sb.append(column.getSqlType() ); sb.append("\" ");
+ }
+ return sb.toString();
+ }
+
+ public String getClassName(PersistentClass pc) {
+ if (pc.hasPojoRepresentation() ) {
+ return pc.getClassName();
+ }
+ else {
+ // todo: return null?
+ throw new RuntimeException(pc + " does not have a pojo rep.");
+ }
+ }
+
+ public String getClassName(OneToMany om) {
+ return om.getAssociatedClass().getClassName();
+ }
+
+ public String getProxyInterfaceName(PersistentClass pc) {
+ if (pc.hasPojoRepresentation() ) {
+ return pc.getProxyInterfaceName();
+ }
+ else {
+ throw new RuntimeException(pc + " does not have a pojo rep.");
+ }
+ }
+
+ public boolean isImportData(Metadata md) {
+ return !(md.getImports().isEmpty());
+ }
+
+ public boolean needsDiscriminatorElement(PersistentClass clazz) {
+ return clazz instanceof RootClass
+ && (clazz.getDiscriminator() != null);
+ }
+
+ public boolean needsDiscriminator(PersistentClass clazz) {
+
+ return clazz instanceof Subclass
+ && !(clazz instanceof UnionSubclass) && !(clazz instanceof JoinedSubclass);
+ }
+
+
+ public boolean needsTable(PersistentClass clazz) {
return (Boolean) clazz.accept(new PersistentClassVisitor(){
@@ -438,40 +430,40 @@ public Object accept(RootClass class1) {
return Boolean.TRUE;
}
});
- }
-
- public boolean isSubclass(PersistentClass clazz) {
- return clazz instanceof org.hibernate.mapping.Subclass;
- }
-
- public boolean isJoinedSubclass(PersistentClass clazz) {
- return clazz instanceof JoinedSubclass;
- }
-
- public boolean hasCustomEntityPersister(PersistentClass clazz) {
- ServiceRegistry sr = clazz.getServiceRegistry();
- PersisterClassResolver pcr = sr.getService(PersisterClassResolver.class);
- if (pcr == null) return false;
- Class> entityPersisterClass = pcr.getEntityPersisterClass(clazz);
- if(entityPersisterClass==null) return false;
- final String name = entityPersisterClass.getName();
+ }
+
+ public boolean isSubclass(PersistentClass clazz) {
+ return clazz instanceof org.hibernate.mapping.Subclass;
+ }
+
+ public boolean isJoinedSubclass(PersistentClass clazz) {
+ return clazz instanceof JoinedSubclass;
+ }
+
+ public boolean hasCustomEntityPersister(PersistentClass clazz) {
+ ServiceRegistry sr = clazz.getServiceRegistry();
+ PersisterClassResolver pcr = sr.getService(PersisterClassResolver.class);
+ if (pcr == null) return false;
+ Class> entityPersisterClass = pcr.getEntityPersisterClass(clazz);
+ if(entityPersisterClass==null) return false;
+ final String name = entityPersisterClass.getName();
return (Boolean) clazz.accept(new HasEntityPersisterVisitor(name));
- }
+ }
- public String getHibernateTypeName(Property p) {
- return (String) p.getValue().accept(new EntityNameFromValueVisitor());
- }
+ public String getHibernateTypeName(Property p) {
+ return (String) p.getValue().accept(new EntityNameFromValueVisitor());
+ }
- public String getSafeHibernateTypeName(Property p) {
- return (String) p.getValue().accept(new EntityNameFromValueVisitor(false));
- }
+ public String getSafeHibernateTypeName(Property p) {
+ return (String) p.getValue().accept(new EntityNameFromValueVisitor(false));
+ }
- public Iterator> getProperties(Component v) {
- return new SkipBackRefPropertyIterator(v.getProperties().iterator());
- }
+ public Iterator> getProperties(Component v) {
+ return new SkipBackRefPropertyIterator(v.getProperties().iterator());
+ }
- public Iterator> getProperties(PersistentClass pc) {
- return new SkipBackRefPropertyIterator(pc.getProperties().iterator());
- }
+ public Iterator> getProperties(PersistentClass pc) {
+ return new SkipBackRefPropertyIterator(pc.getProperties().iterator());
+ }
}
diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java
index 3a44651cb0..fcc486ac48 100644
--- a/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java
+++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java
@@ -49,924 +49,941 @@
*/
abstract public class BasicPOJOClass implements POJOClass {
- protected ImportContext importContext;
- protected MetaAttributable meta;
- protected final Cfg2JavaTool c2j;
-
- public BasicPOJOClass(MetaAttributable ma, Cfg2JavaTool c2j) {
- this.meta = ma;
- this.c2j = c2j;
-
- if(this.meta==null) {
- throw new IllegalArgumentException("class Argument must be not null");
- }
- if(this.c2j==null) throw new IllegalArgumentException("c2j must be not null");
- }
-
- // called by subclasses
- protected void init() {
- importContext = new ImportContextImpl(getPackageName());
-
- MetaAttribute metaAttribute = meta.getMetaAttribute("extra-import");
- if(metaAttribute!=null) {
+ protected ImportContext importContext;
+ protected MetaAttributable meta;
+ protected final Cfg2JavaTool c2j;
+
+ public BasicPOJOClass(MetaAttributable ma, Cfg2JavaTool c2j) {
+ this.meta = ma;
+ this.c2j = c2j;
+
+ if(this.meta==null) {
+ throw new IllegalArgumentException("class Argument must be not null");
+ }
+ if(this.c2j==null) throw new IllegalArgumentException("c2j must be not null");
+ }
+
+ // called by subclasses
+ protected void init() {
+ importContext = new ImportContextImpl(getPackageName());
+
+ MetaAttribute metaAttribute = meta.getMetaAttribute("extra-import");
+ if(metaAttribute!=null) {
for (String element : metaAttribute.getValues()) {
importContext.importType(element);
}
- }
- }
-
- protected String getPackageDeclaration(String pkgName) {
- if (pkgName!=null && !pkgName.trim().isEmpty()) {
- return "package " + pkgName + ";";
- }
- else {
- return "// default package";
- }
- }
-
- public String getPackageDeclaration() {
- String pkgName = getPackageName();
- return getPackageDeclaration(pkgName);
- }
-
- /** Return package name. Note: Does not handle inner classes */
- public String getPackageName() {
- String generatedClass = getGeneratedClassName();
- return StringHelper.qualifier(generatedClass.trim());
- }
-
- public String getShortName() {
- return qualifyInnerClass(StringHelper.unqualify(getMappedClassName()));
- }
-
- public String getQualifiedDeclarationName() {
- String generatedName = qualifyInnerClass(getGeneratedClassName());
- String qualifier = StringHelper.qualifier( getMappedClassName() );
- if (!qualifier.isEmpty()) {
- return qualifier + "." + generatedName;
- }
- else {
- return generatedName;
- }
- }
-
- /**
- * @return unqualified classname for this class (can be changed by meta attribute "generated-class")
- */
- public String getDeclarationName() {
- return qualifyInnerClass(StringHelper.unqualify( getGeneratedClassName() ));
- }
-
- protected String getGeneratedClassName()
- {
- String generatedClass = getMetaAsString(MetaAttributeConstants.GENERATED_CLASS).trim();
- if(StringHelper.isEmpty(generatedClass) ) {
- generatedClass = getMappedClassName();
- }
+ }
+ }
+
+ protected String getPackageDeclaration(String pkgName) {
+ if (pkgName!=null && !pkgName.trim().isEmpty()) {
+ return "package " + pkgName + ";";
+ }
+ else {
+ return "// default package";
+ }
+ }
+
+ public String getPackageDeclaration() {
+ String pkgName = getPackageName();
+ return getPackageDeclaration(pkgName);
+ }
+
+ /** Return package name. Note: Does not handle inner classes */
+ public String getPackageName() {
+ String generatedClass = getGeneratedClassName();
+ return StringHelper.qualifier(generatedClass.trim());
+ }
+
+ public String getShortName() {
+ return qualifyInnerClass(StringHelper.unqualify(getMappedClassName()));
+ }
+
+ public String getQualifiedDeclarationName() {
+ String generatedName = qualifyInnerClass(getGeneratedClassName());
+ String qualifier = StringHelper.qualifier( getMappedClassName() );
+ if (!qualifier.isEmpty()) {
+ return qualifier + "." + generatedName;
+ }
+ else {
+ return generatedName;
+ }
+ }
+
+ /**
+ * @return unqualified classname for this class (can be changed by meta attribute "generated-class")
+ */
+ public String getDeclarationName() {
+ return qualifyInnerClass(StringHelper.unqualify( getGeneratedClassName() ));
+ }
+
+ protected String getGeneratedClassName()
+ {
+ String generatedClass = getMetaAsString(MetaAttributeConstants.GENERATED_CLASS).trim();
+ if(StringHelper.isEmpty(generatedClass) ) {
+ generatedClass = getMappedClassName();
+ }
// will occur for
return Objects.requireNonNullElse(generatedClass, "");
}
-
- protected String qualifyInnerClass(String className)
- {
- return className.replace('$', '.');
- }
-
- protected abstract String getMappedClassName();
-
- public String getMetaAsString(String attribute) {
- MetaAttribute c = meta.getMetaAttribute( attribute );
- return MetaAttributeHelper.getMetaAsString( c );
- }
-
- public boolean hasMetaAttribute(String attribute) {
- return meta.getMetaAttribute( attribute ) != null;
- }
-
- public String getMetaAsString(String attribute, String seperator) {
- return MetaAttributeHelper.getMetaAsString( meta.getMetaAttribute( attribute ), seperator );
- }
-
- public boolean getMetaAsBool(String attribute) {
- return getMetaAsBool( attribute, false );
- }
-
- public boolean getMetaAsBool(String attribute, boolean defaultValue) {
- return MetaAttributeHelper.getMetaAsBool( meta.getMetaAttribute( attribute ), defaultValue );
- }
-
- public String getClassJavaDoc(String fallback, int indent) {
- MetaAttribute c = meta.getMetaAttribute( CLASS_DESCRIPTION );
- if ( c == null ) {
- return c2j.toJavaDoc( fallback, indent );
- }
- else {
- return c2j.toJavaDoc( getMetaAsString( CLASS_DESCRIPTION ), indent );
- }
- }
-
- public String getClassModifiers() {
- String classModifiers = null;
-
- // Get scope (backwards compatibility)
- if ( meta.getMetaAttribute( SCOPE_CLASS ) != null ) {
- classModifiers = getMetaAsString( SCOPE_CLASS ).trim();
- }
-
- // Get modifiers
- if ( meta.getMetaAttribute( CLASS_MODIFIER ) != null ) {
- classModifiers = getMetaAsString( CLASS_MODIFIER ).trim();
- }
- return classModifiers == null ? "public" : classModifiers;
- }
-
- public String getDeclarationType() {
- boolean isInterface = isInterface();
- if ( isInterface ) {
- return INTERFACE;
- }
- else {
- return "class";
- }
- }
-
- public boolean isInterface() {
- return getMetaAsBool( INTERFACE );
- }
-
- public String getExtendsDeclaration() {
- String extendz = getExtends();
- if ( extendz == null || extendz.trim().isEmpty()) {
- return "";
- }
- else {
- return "extends " + extendz;
- }
- }
-
- public String getImplementsDeclaration() {
- String implementz = getImplements();
- if ( implementz == null || implementz.trim().isEmpty()) {
- return "";
- }
- else {
- return "implements " + implementz;
- }
- }
-
- public String generateEquals(String thisName, String otherName, boolean useGenerics) {
- Iterator allPropertiesIterator = getEqualsHashCodePropertiesIterator();
- return generateEquals( thisName, otherName, allPropertiesIterator, useGenerics );
- }
-
- /** returns the properties that would be visible on this entity as a pojo. This does not return *all* properties since hibernate has certain properties that are only relevant in context of persistence. */
- public abstract Iterator getAllPropertiesIterator();
-
- protected String generateEquals(String thisName, String otherName, Iterator allPropertiesIterator, boolean useGenerics) {
- StringBuilder buf = new StringBuilder();
- while ( allPropertiesIterator.hasNext() ) {
- Property property = (Property) allPropertiesIterator.next();
- if (!buf.isEmpty()) buf.append( "\n && " );
- String javaTypeName = c2j.getJavaTypeName( property, useGenerics, this );
- buf.append(
- internalgenerateEquals(
- javaTypeName, thisName + "." + getGetterSignature( property ) + "()",
- otherName + "." + getGetterSignature( property ) + "()")
- );
- }
-
- if (buf.isEmpty()) {
- return "false";
- }
- else {
- return buf.toString();
- }
- }
-
- private boolean usePropertyInEquals(Property property) {
- boolean hasEqualsMetaAttribute = c2j.hasMetaAttribute(property, "use-in-equals");
- boolean useInEquals = c2j.getMetaAsBool( property, "use-in-equals" );
-
- if(property.isNaturalIdentifier()) {
+
+ protected String qualifyInnerClass(String className)
+ {
+ return className.replace('$', '.');
+ }
+
+ protected abstract String getMappedClassName();
+
+ public String getMetaAsString(String attribute) {
+ MetaAttribute c = meta.getMetaAttribute( attribute );
+ return MetaAttributeHelper.getMetaAsString( c );
+ }
+
+ public boolean hasMetaAttribute(String attribute) {
+ return meta.getMetaAttribute( attribute ) != null;
+ }
+
+ public String getMetaAsString(String attribute, String seperator) {
+ return MetaAttributeHelper.getMetaAsString( meta.getMetaAttribute( attribute ), seperator );
+ }
+
+ public boolean getMetaAsBool(String attribute) {
+ return getMetaAsBool( attribute, false );
+ }
+
+ public boolean getMetaAsBool(String attribute, boolean defaultValue) {
+ return MetaAttributeHelper.getMetaAsBool( meta.getMetaAttribute( attribute ), defaultValue );
+ }
+
+ public String getClassJavaDoc(String fallback, int indent) {
+ MetaAttribute c = meta.getMetaAttribute( CLASS_DESCRIPTION );
+ if ( c == null ) {
+ return c2j.toJavaDoc( fallback, indent );
+ }
+ else {
+ return c2j.toJavaDoc( getMetaAsString( CLASS_DESCRIPTION ), indent );
+ }
+ }
+
+ public String getClassModifiers() {
+ String classModifiers = null;
+
+ // Get scope (backwards compatibility)
+ if ( meta.getMetaAttribute( SCOPE_CLASS ) != null ) {
+ classModifiers = getMetaAsString( SCOPE_CLASS ).trim();
+ }
+
+ // Get modifiers
+ if ( meta.getMetaAttribute( CLASS_MODIFIER ) != null ) {
+ classModifiers = getMetaAsString( CLASS_MODIFIER ).trim();
+ }
+ return classModifiers == null ? "public" : classModifiers;
+ }
+
+ public String getDeclarationType() {
+ boolean isInterface = isInterface();
+ if ( isInterface ) {
+ return INTERFACE;
+ }
+ else {
+ return "class";
+ }
+ }
+
+ public boolean isInterface() {
+ return getMetaAsBool( INTERFACE );
+ }
+
+ public String getExtendsDeclaration() {
+ String extendz = getExtends();
+ if ( extendz == null || extendz.trim().isEmpty()) {
+ return "";
+ }
+ else {
+ return "extends " + extendz;
+ }
+ }
+
+ public String getImplementsDeclaration() {
+ String implementz = getImplements();
+ if ( implementz == null || implementz.trim().isEmpty()) {
+ return "";
+ }
+ else {
+ return "implements " + implementz;
+ }
+ }
+
+ public String generateEquals(String thisName, String otherName, boolean useGenerics) {
+ Iterator allPropertiesIterator = getEqualsHashCodePropertiesIterator();
+ return generateEquals( thisName, otherName, allPropertiesIterator, useGenerics );
+ }
+
+ /** returns the properties that would be visible on this entity as a pojo. This does not return *all* properties since hibernate has certain properties that are only relevant in context of persistence. */
+ public abstract Iterator getAllPropertiesIterator();
+
+ protected String generateEquals(String thisName, String otherName, Iterator allPropertiesIterator, boolean useGenerics) {
+ StringBuilder buf = new StringBuilder();
+ while ( allPropertiesIterator.hasNext() ) {
+ Property property = allPropertiesIterator.next();
+ if (!buf.isEmpty()) buf.append( "\n && " );
+ String javaTypeName = c2j.getJavaTypeName( property, useGenerics, this );
+ buf.append(
+ internalgenerateEquals(
+ javaTypeName, thisName + "." + getGetterSignature( property ) + "()",
+ otherName + "." + getGetterSignature( property ) + "()")
+ );
+ }
+
+ if (buf.isEmpty()) {
+ return "false";
+ }
+ else {
+ return buf.toString();
+ }
+ }
+
+ private boolean usePropertyInEquals(Property property) {
+ boolean hasEqualsMetaAttribute = c2j.hasMetaAttribute(property, "use-in-equals");
+ boolean useInEquals = c2j.getMetaAsBool( property, "use-in-equals" );
+
+ if(property.isNaturalIdentifier()) {
return !hasEqualsMetaAttribute || useInEquals;
- }
-
- return useInEquals;
- }
+ }
+
+ return useInEquals;
+ }
- private boolean useCompareTo(String javaTypeName) {
- // Fix for HBX-400
+ private boolean useCompareTo(String javaTypeName) {
+ // Fix for HBX-400
return "java.math.BigDecimal".equals(javaTypeName);
- }
-
-
- private String internalgenerateEquals(String typeName, String lh, String rh) {
- if ( c2j.isPrimitive( typeName ) ) {
- return "(" + lh + "==" + rh + ")";
- }
- else {
- if(useCompareTo( typeName )) {
- return "( (" + lh + "==" + rh + ") || ( " + lh + "!=null && " + rh + "!=null && " + lh + ".compareTo(" + rh + ")==0 ) )";
- } else {
- if(typeName.endsWith("[]")) {
- return "( (" + lh + "==" + rh + ") || ( " + lh + "!=null && " + rh + "!=null && " + importType("java.util.Arrays") + ".equals(" + lh + ", " + rh + ") ) )";
- } else {
- return "( (" + lh + "==" + rh + ") || ( " + lh + "!=null && " + rh + "!=null && " + lh + ".equals(" + rh + ") ) )";
- }
- }
-
- }
- }
-
- public String getExtraClassCode() {
- return getMetaAsString( "class-code", "\n" );
- }
-
- private boolean needsEqualsHashCode(Iterator> iter) {
- while ( iter.hasNext() ) {
- Property element = (Property) iter.next();
- if ( usePropertyInEquals( element ) ) {
- return true;
- }
- }
- return false;
- }
-
- public boolean needsEqualsHashCode() {
- Iterator