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 props = new TreeMap<>(); + if (getProperties() != null) { + props.putAll(getProperties()); + } + if(customProperties!=null) { + props.putAll(customProperties); + } + + 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(); + for ( Entry element : set ) { + 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() ) + "" ); + } + } + + if(getMetadata()!=null) { + for ( PersistentClass element : getMetadata().getEntityBindings() ) { + 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(); + } } - - - 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 iter = getAllPropertiesIterator(); - return needsEqualsHashCode( iter ); - } - - public abstract String getExtends(); - - public abstract String getImplements(); - - - public String importType(String fqcn) { - return importContext.importType(fqcn); - } - - public String generateImports() { - return importContext.generateImports(); - } - - public String staticImport(String fqcn, String member) { - return importContext.staticImport(fqcn, member); - } - - public String generateBasicAnnotation(Property property) { - StringBuffer annotations = new StringBuffer( " " ); - if(property.getValue() instanceof SimpleValue) { - if (hasVersionProperty()) - if (property.equals(getVersionProperty())) - buildVersionAnnotation(annotations); - String typeName = ((SimpleValue)property.getValue()).getTypeName(); - if("date".equals(typeName) || "java.sql.Date".equals(typeName)) { - buildTemporalAnnotation( annotations, "DATE" ); - } else if ("timestamp".equals(typeName) || "java.sql.Timestamp".equals(typeName)) { - buildTemporalAnnotation( annotations, "TIMESTAMP" ); - } else if ("time".equals(typeName) || "java.sql.Time".equals(typeName)) { - buildTemporalAnnotation(annotations, "TIME"); - } //TODO: calendar etc. ? - - - } - - return annotations.toString(); - } - - private void buildTemporalAnnotation(StringBuffer annotations, String temporalTypeValue) { - annotations - .append("@") - .append(importType("jakarta.persistence.Temporal")) - .append("(") - .append(importType("jakarta.persistence.TemporalType")) - .append(".") - .append(temporalTypeValue) - .append(")"); - } - - private void buildVersionAnnotation(StringBuffer annotations) { - annotations - .append("@") - .append(importType("jakarta.persistence.Version")); - } - - public String generateAnnColumnAnnotation(Property property) { - StringBuffer annotations = new StringBuffer( " " ); - boolean insertable = property.isInsertable(); - boolean updatable = property.isUpdatable(); - if ( property.isComposite() ) { - annotations.append("@").append(importType("jakarta.persistence.AttributeOverrides")).append("( {"); - Component component = (Component) property.getValue(); - Iterator subElements = component.getProperties().iterator(); - buildRecursiveAttributeOverride( subElements, null, annotations ); - annotations.setLength( annotations.length() - 2 ); - annotations.append( " } )" ); - } - else { - if ( property.getColumnSpan() == 1 ) { - Selectable selectable = property.getColumns().get(0); - buildColumnAnnotation( selectable, annotations, insertable, updatable ); - } - else { - annotations.append("@").append( importType("org.hibernate.annotations.Columns") ).append("( { " ); - for (Selectable selectable : property.getColumns()) { - //TODO formula in multicolumns not supported by annotations - if ( !selectable.isFormula() ) { - annotations.append( "\n " ); - buildColumnAnnotation( selectable, annotations, insertable, updatable ); - annotations.append( ", " ); - } - } - annotations.setLength( annotations.length() - 2 ); - annotations.append( " } )" ); - } - } - return annotations.toString(); - } - - private void buildRecursiveAttributeOverride(Iterator subElements, String path, StringBuffer annotations) { - while ( subElements.hasNext() ) { - Property subProperty = (Property) subElements.next(); - if ( subProperty.isComposite() ) { - if ( path != null ) { - path = path + "."; - } - else { - path = ""; - } - path = path + subProperty.getName(); - Component component = (Component) subProperty.getValue(); - buildRecursiveAttributeOverride( component.getProperties().iterator(), path, annotations ); - } - else { - Selectable selectable = subProperty.getColumns().get(0); - //TODO formula in multicolumns not supported by annotations - if ( !selectable.isFormula() ) { - annotations.append( "\n " ).append("@") - .append( importType("jakarta.persistence.AttributeOverride") ).append("(name=\"" ); - if ( path != null ) { - annotations.append( path ).append( "." ); - } - annotations.append( subProperty.getName() ).append( "\"" ) - .append( ", column=" ); - buildColumnAnnotation( - selectable, annotations, subProperty.isInsertable(), subProperty.isUpdatable() - ); - annotations.append( " ), " ); - } - } - } - } - - private void buildColumnAnnotation(Selectable selectable, StringBuffer annotations, boolean insertable, boolean updatable) { - if ( selectable.isFormula() ) { - annotations - .append("@") - .append( importType("org.hibernate.annotations.Formula") ) - .append("(value=\"" ) - .append( selectable.getText() ) - .append( "\")" ); - } - else { - Column column = (Column) selectable; - annotations - .append("@") - .append(importType("jakarta.persistence.Column")) - .append("(name=\"") - .append( column.getName() ) - .append( "\"" ); - appendCommonColumnInfo( annotations, column, insertable, updatable ); - - if (column.getPrecision() != null) { - annotations.append( ", precision=" ).append( column.getPrecision() ); - } - if (column.getScale() != null) { - annotations.append( ", scale=" ).append( column.getScale() ); - } - else if (column.getLength() != null){ - annotations.append( ", length=" ).append( column.getLength() ); - } - - - - - //TODO support secondary table - annotations.append( ")" ); - } - } - - protected void appendCommonColumnInfo(StringBuffer annotations, Column column, boolean insertable, boolean updatable) { - if(column.isUnique()) { - annotations.append( ", unique=" ).append( column.isUnique() ); - } - if(!column.isNullable()) { - annotations.append( ", nullable=" ).append( column.isNullable() ); - } - - if(!insertable) { - annotations.append( ", insertable=" ).append( insertable ); - } - - if(!updatable) { - annotations.append( ", updatable=" ).append( updatable ); - } - - String sqlType = column.getSqlType(); - if ( StringHelper.isNotEmpty( sqlType ) ) { - annotations.append( ", columnDefinition=\"" ).append( sqlType ).append( "\"" ); - } - - } - - - public Iterator getToStringPropertiesIterator() { - Iterator iter = getAllPropertiesIterator(); - return getToStringPropertiesIterator( iter ); - } - - private Iterator getToStringPropertiesIterator(Iterator iter) { - List properties = new ArrayList(); - - while ( iter.hasNext() ) { - Property element = (Property) iter.next(); - if ( c2j.getMetaAsBool( element, "use-in-tostring" ) ) { - properties.add( element ); - } - } - - return properties.iterator(); - } - - public Iterator getEqualsHashCodePropertiesIterator() { - Iterator iter = getAllPropertiesIterator(); - return getEqualsHashCodePropertiesIterator(iter); - } - - private Iterator getEqualsHashCodePropertiesIterator(Iterator iter) { - List properties = new ArrayList(); - - while ( iter.hasNext() ) { - Property element = (Property) iter.next(); - if ( usePropertyInEquals(element) ) { - properties.add( element ); - } - } - - return properties.iterator(); - } - - public boolean needsToString() { - Iterator iter = getAllPropertiesIterator(); - return needsToString( iter ); - } - - private boolean needsToString(Iterator iter) { - while ( iter.hasNext() ) { - Property element = (Property) iter.next(); - if ( c2j.getMetaAsBool( element, "use-in-tostring" ) ) { - return true; - } - } - return false; - } - - public boolean hasMetaAttribute(MetaAttributable pc, String attribute) { - return pc.getMetaAttribute( attribute ) != null; - } - - public boolean getMetaAttribAsBool(MetaAttributable pc, String attribute, boolean defaultValue) { - return MetaAttributeHelper.getMetaAsBool( pc.getMetaAttribute( attribute ), defaultValue ); - } - - public boolean hasFieldJavaDoc(Property property) { - return property.getMetaAttribute("field-description")!=null; - } - - public String getFieldJavaDoc(Property property, int indent) { - MetaAttribute c = property.getMetaAttribute( "field-description" ); - if ( c == null ) { - return c2j.toJavaDoc( "", indent ); - } - else { - return c2j.toJavaDoc( c2j.getMetaAsString( property, "field-description" ), indent ); - } - } - - public String getFieldDescription(Property property){ - MetaAttribute c = property.getMetaAttribute( "field-description" ); - if ( c == null ) { - return ""; - } - else { - return c2j.getMetaAsString( property, "field-description" ); - } - } - - /** - * Method getGetterSignature. - * - * @return String - */ - public String getGetterSignature(Property p) { - String prefix = c2j.getJavaTypeName( p, false).equals( "boolean" ) ? "is" : "get"; - return prefix + beanCapitalize( p.getName() ); - } - - /** - * @return foo -> Foo, FOo -> FOo - */ - public String getPropertyName(Property p) { - return beanCapitalize( p.getName() ); - } - - - // get the "opposite" collectionnae for a property. Currently a "hack" that just uses the same naming algorithm as in reveng, will fail on more general models! - public String getCollectionNameFor(Property property) { - String str = getPropertyName(property); - return NameConverter.simplePluralize(str); - } - - - /** - * foo -> Foo - * FOo -> FOo - */ - static public String beanCapitalize(String fieldname) { - if ( fieldname == null || fieldname.isEmpty()) { - return fieldname; - } - - if ( fieldname.length() > 1 && Character.isUpperCase( fieldname.charAt( 1 ) ) ) { - return fieldname; - } - char[] chars = fieldname.toCharArray(); - chars[0] = Character.toUpperCase( chars[0] ); - return new String( chars ); - } - - - public boolean isComponent(Property property) { + } + + + 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 iter = getAllPropertiesIterator(); + return needsEqualsHashCode( iter ); + } + + public abstract String getExtends(); + + public abstract String getImplements(); + + + public String importType(String fqcn) { + return importContext.importType(fqcn); + } + + public String generateImports() { + return importContext.generateImports(); + } + + public String staticImport(String fqcn, String member) { + return importContext.staticImport(fqcn, member); + } + + public String generateBasicAnnotation(Property property) { + StringBuffer annotations = new StringBuffer( " " ); + if(property.getValue() instanceof SimpleValue) { + if (hasVersionProperty()) + if (property.equals(getVersionProperty())) + buildVersionAnnotation(annotations); + String typeName = ((SimpleValue)property.getValue()).getTypeName(); + if("date".equals(typeName) || "java.sql.Date".equals(typeName)) { + buildTemporalAnnotation( annotations, "DATE" ); + } + else if ("timestamp".equals(typeName) || "java.sql.Timestamp".equals(typeName)) { + buildTemporalAnnotation( annotations, "TIMESTAMP" ); + } + else if ("time".equals(typeName) || "java.sql.Time".equals(typeName)) { + buildTemporalAnnotation(annotations, "TIME"); + } //TODO: calendar etc. ? + + + } + + return annotations.toString(); + } + + private void buildTemporalAnnotation(StringBuffer annotations, String temporalTypeValue) { + annotations + .append("@") + .append(importType("jakarta.persistence.Temporal")) + .append("(") + .append(importType("jakarta.persistence.TemporalType")) + .append(".") + .append(temporalTypeValue) + .append(")"); + } + + private void buildVersionAnnotation(StringBuffer annotations) { + annotations + .append("@") + .append(importType("jakarta.persistence.Version")); + } + + public String generateAnnColumnAnnotation(Property property) { + StringBuffer annotations = new StringBuffer( " " ); + boolean insertable = property.isInsertable(); + boolean updatable = property.isUpdatable(); + if ( property.isComposite() ) { + annotations.append("@").append(importType("jakarta.persistence.AttributeOverrides")).append("( {"); + Component component = (Component) property.getValue(); + Iterator subElements = component.getProperties().iterator(); + buildRecursiveAttributeOverride( subElements, null, annotations ); + annotations.setLength( annotations.length() - 2 ); + annotations.append( " } )" ); + } + else { + if ( property.getColumnSpan() == 1 ) { + Selectable selectable = property.getColumns().get(0); + buildColumnAnnotation( selectable, annotations, insertable, updatable ); + } + else { + annotations.append("@").append( importType("org.hibernate.annotations.Columns") ).append("( { " ); + for (Selectable selectable : property.getColumns()) { + //TODO formula in multicolumns not supported by annotations + if ( !selectable.isFormula() ) { + annotations.append( "\n " ); + buildColumnAnnotation( selectable, annotations, insertable, updatable ); + annotations.append( ", " ); + } + } + annotations.setLength( annotations.length() - 2 ); + annotations.append( " } )" ); + } + } + return annotations.toString(); + } + + private void buildRecursiveAttributeOverride(Iterator subElements, String path, StringBuffer annotations) { + while ( subElements.hasNext() ) { + Property subProperty = (Property) subElements.next(); + if ( subProperty.isComposite() ) { + if ( path != null ) { + path = path + "."; + } + else { + path = ""; + } + path = path + subProperty.getName(); + Component component = (Component) subProperty.getValue(); + buildRecursiveAttributeOverride( component.getProperties().iterator(), path, annotations ); + } + else { + Selectable selectable = subProperty.getColumns().get(0); + //TODO formula in multicolumns not supported by annotations + if ( !selectable.isFormula() ) { + annotations.append( "\n " ).append("@") + .append( importType("jakarta.persistence.AttributeOverride") ).append("(name=\"" ); + if ( path != null ) { + annotations.append( path ).append( "." ); + } + annotations.append( subProperty.getName() ).append( "\"" ) + .append( ", column=" ); + buildColumnAnnotation( + selectable, annotations, subProperty.isInsertable(), subProperty.isUpdatable() + ); + annotations.append( " ), " ); + } + } + } + } + + private void buildColumnAnnotation(Selectable selectable, StringBuffer annotations, boolean insertable, boolean updatable) { + if ( selectable.isFormula() ) { + annotations + .append("@") + .append( importType("org.hibernate.annotations.Formula") ) + .append("(value=\"" ) + .append( selectable.getText() ) + .append( "\")" ); + } + else { + Column column = (Column) selectable; + annotations + .append("@") + .append(importType("jakarta.persistence.Column")) + .append("(name=\"") + .append( column.getName() ) + .append( "\"" ); + appendCommonColumnInfo( annotations, column, insertable, updatable ); + + if (column.getPrecision() != null) { + annotations.append( ", precision=" ).append( column.getPrecision() ); + } + if (column.getScale() != null) { + annotations.append( ", scale=" ).append( column.getScale() ); + } + else if (column.getLength() != null){ + annotations.append( ", length=" ).append( column.getLength() ); + } + + + + + //TODO support secondary table + annotations.append( ")" ); + } + } + + protected void appendCommonColumnInfo(StringBuffer annotations, Column column, boolean insertable, boolean updatable) { + if(column.isUnique()) { + annotations.append( ", unique=" ).append( column.isUnique() ); + } + if(!column.isNullable()) { + annotations.append( ", nullable=" ).append( column.isNullable() ); + } + + if(!insertable) { + annotations.append( ", insertable=" ).append( "false" ); + } + + if(!updatable) { + annotations.append( ", updatable=" ).append( "false" ); + } + + String sqlType = column.getSqlType(); + if ( StringHelper.isNotEmpty( sqlType ) ) { + annotations.append( ", columnDefinition=\"" ).append( sqlType ).append( "\"" ); + } + + } + + + public Iterator getToStringPropertiesIterator() { + Iterator iter = getAllPropertiesIterator(); + return getToStringPropertiesIterator( iter ); + } + + private Iterator getToStringPropertiesIterator(Iterator iter) { + List properties = new ArrayList<>(); + + while ( iter.hasNext() ) { + Property element = iter.next(); + if ( c2j.getMetaAsBool( element, "use-in-tostring" ) ) { + properties.add( element ); + } + } + + return properties.iterator(); + } + + public Iterator getEqualsHashCodePropertiesIterator() { + Iterator iter = getAllPropertiesIterator(); + return getEqualsHashCodePropertiesIterator(iter); + } + + private Iterator getEqualsHashCodePropertiesIterator(Iterator iter) { + List properties = new ArrayList<>(); + + while ( iter.hasNext() ) { + Property element = iter.next(); + if ( usePropertyInEquals(element) ) { + properties.add( element ); + } + } + + return properties.iterator(); + } + + public boolean needsToString() { + Iterator iter = getAllPropertiesIterator(); + return needsToString( iter ); + } + + private boolean needsToString(Iterator iter) { + while ( iter.hasNext() ) { + Property element = iter.next(); + if ( c2j.getMetaAsBool( element, "use-in-tostring" ) ) { + return true; + } + } + return false; + } + + public boolean hasMetaAttribute(MetaAttributable pc, String attribute) { + return pc.getMetaAttribute( attribute ) != null; + } + + public boolean getMetaAttribAsBool(MetaAttributable pc, String attribute, boolean defaultValue) { + return MetaAttributeHelper.getMetaAsBool( pc.getMetaAttribute( attribute ), defaultValue ); + } + + public boolean hasFieldJavaDoc(Property property) { + return property.getMetaAttribute("field-description")!=null; + } + + public String getFieldJavaDoc(Property property, int indent) { + MetaAttribute c = property.getMetaAttribute( "field-description" ); + if ( c == null ) { + return c2j.toJavaDoc( "", indent ); + } + else { + return c2j.toJavaDoc( c2j.getMetaAsString( property, "field-description" ), indent ); + } + } + + public String getFieldDescription(Property property){ + MetaAttribute c = property.getMetaAttribute( "field-description" ); + if ( c == null ) { + return ""; + } + else { + return c2j.getMetaAsString( property, "field-description" ); + } + } + + /** + * Method getGetterSignature. + * + * @return String + */ + public String getGetterSignature(Property p) { + String prefix = c2j.getJavaTypeName( p, false).equals( "boolean" ) ? "is" : "get"; + return prefix + beanCapitalize( p.getName() ); + } + + /** + * @return foo -> Foo, FOo -> FOo + */ + public String getPropertyName(Property p) { + return beanCapitalize( p.getName() ); + } + + + // get the "opposite" collectionnae for a property. Currently a "hack" that just uses the same naming algorithm as in reveng, will fail on more general models! + public String getCollectionNameFor(Property property) { + String str = getPropertyName(property); + return NameConverter.simplePluralize(str); + } + + + /** + * foo -> Foo + * FOo -> FOo + */ + static public String beanCapitalize(String fieldname) { + if ( fieldname == null || fieldname.isEmpty()) { + return fieldname; + } + + if ( fieldname.length() > 1 && Character.isUpperCase( fieldname.charAt( 1 ) ) ) { + return fieldname; + } + char[] chars = fieldname.toCharArray(); + chars[0] = Character.toUpperCase( chars[0] ); + return new String( chars ); + } + + + public boolean isComponent(Property property) { return property.getValue() instanceof Component; - } - - public String generateHashCode(Property property, String result, String thisName, boolean jdk5) { - StringBuilder buf = new StringBuilder(); - if ( c2j.getMetaAsBool( property, "use-in-equals" ) ) { - String javaTypeName = c2j.getJavaTypeName( property, jdk5, this ); - boolean isPrimitive = c2j.isPrimitive( javaTypeName ); - if ( isPrimitive ) { - buf.append( result ) - .append( " = 37 * " ) - .append( result ) - .append( " + " ); - String thisValue = thisName + "." + getGetterSignature( property ) + "()"; - if("char".equals(javaTypeName)||"int".equals(javaTypeName)||"short".equals(javaTypeName)||"byte".equals(javaTypeName)) { - buf.append( thisValue ); - } else if("boolean".equals(javaTypeName)) { - buf.append("(").append(thisValue).append("?1:0)"); - } else { - buf.append( "(int) "); - buf.append( thisValue ); - } - buf.append(";"); - } - else { - if(javaTypeName.endsWith("[]")) { - if(jdk5) { - buf.append( result ) - .append( " = 37 * " ) - .append( result ) - .append( " + " ) - .append("( ") - .append(getGetterSignature(property)) - .append("() == null ? 0 : ") - .append(importType("java.util.Arrays")) - .append(".hashCode(") - .append( thisName ) - .append( "." ) - .append( getGetterSignature( property ) ) - .append( "())" ) - .append( " )" ) - .append(";"); - } - else { - buf.append(internalGenerateArrayHashcode(property, javaTypeName, result, thisName)); - } - } else { - buf.append( result ) - .append( " = 37 * " ) - .append( result ) - .append( " + " ); - buf.append( "( " ) - .append( getGetterSignature( property ) ) - .append( "() == null ? 0 : " ) - .append( thisName ) - .append( "." ) - .append( getGetterSignature( property ) ) - .append( "()" ) - .append( ".hashCode()" ) - .append( " )" ) - .append(";"); - } - } - } - return buf.toString(); - } - - - private String internalGenerateArrayHashcode(Property property, String javaTypeName, String result, String thisName) - { - StringBuilder buf = new StringBuilder(); - - String propertyHashVarName = property.getName() + "Hashcode"; - String propertyArrayName = property.getName() + "Property"; + } + + public String generateHashCode(Property property, String result, String thisName, boolean jdk5) { + StringBuilder buf = new StringBuilder(); + if ( c2j.getMetaAsBool( property, "use-in-equals" ) ) { + String javaTypeName = c2j.getJavaTypeName( property, jdk5, this ); + boolean isPrimitive = c2j.isPrimitive( javaTypeName ); + if ( isPrimitive ) { + buf.append( result ) + .append( " = 37 * " ) + .append( result ) + .append( " + " ); + String thisValue = thisName + "." + getGetterSignature( property ) + "()"; + if("char".equals(javaTypeName)||"int".equals(javaTypeName)||"short".equals(javaTypeName)||"byte".equals(javaTypeName)) { + buf.append( thisValue ); + } + else if("boolean".equals(javaTypeName)) { + buf.append("(").append(thisValue).append("?1:0)"); + } + else { + buf.append( "(int) "); + buf.append( thisValue ); + } + buf.append(";"); + } + else { + if(javaTypeName.endsWith("[]")) { + if(jdk5) { + buf.append( result ) + .append( " = 37 * " ) + .append( result ) + .append( " + " ) + .append("( ") + .append(getGetterSignature(property)) + .append("() == null ? 0 : ") + .append(importType("java.util.Arrays")) + .append(".hashCode(") + .append( thisName ) + .append( "." ) + .append( getGetterSignature( property ) ) + .append( "())" ) + .append( " )" ) + .append(";"); + } + else { + buf.append(internalGenerateArrayHashcode(property, javaTypeName, result, thisName)); + } + } + else { + buf.append( result ) + .append( " = 37 * " ) + .append( result ) + .append( " + " ); + buf.append( "( " ) + .append( getGetterSignature( property ) ) + .append( "() == null ? 0 : " ) + .append( thisName ) + .append( "." ) + .append( getGetterSignature( property ) ) + .append( "()" ) + .append( ".hashCode()" ) + .append( " )" ) + .append(";"); + } + } + } + return buf.toString(); + } + + + private String internalGenerateArrayHashcode(Property property, String javaTypeName, String result, String thisName) + { + StringBuilder buf = new StringBuilder(); + + String propertyHashVarName = property.getName() + "Hashcode"; + String propertyArrayName = property.getName() + "Property"; // int propertyHash = 0; - buf.append( "int ") - .append( propertyHashVarName ) - .append( " = 0;\n" ); + buf.append( "int ") + .append( propertyHashVarName ) + .append( " = 0;\n" ); // type[] proterty = getProperty(); - buf.append( " " ) - .append( javaTypeName ) - .append( " " ) - .append( propertyArrayName ) - .append( " = " ) - .append( thisName ) - .append( "." ) - .append( getGetterSignature( property ) ) - .append( "();\n"); + buf.append( " " ) + .append( javaTypeName ) + .append( " " ) + .append( propertyArrayName ) + .append( " = " ) + .append( thisName ) + .append( "." ) + .append( getGetterSignature( property ) ) + .append( "();\n"); // if(property != null) { - buf.append( " if(" ) - .append( propertyArrayName ) - .append( " != null) {\n" ); + buf.append( " if(" ) + .append( propertyArrayName ) + .append( " != null) {\n" ); // propertyHash = 1; - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 1;\n" ); + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 1;\n" ); // for (int i=0; i>> 32)); - buf.append( " int elementHash = (int)(" ) - .append( propertyArrayName ) - .append( "[i] ^ (" ) - .append( propertyArrayName ) - .append( "[i] >>> 32));\n" ); + buf.append( " int elementHash = (int)(" ) + .append( propertyArrayName ) + .append( "[i] ^ (" ) + .append( propertyArrayName ) + .append( "[i] >>> 32));\n" ); // propertyHash = 37 * propertyHash + elementHash; - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + elementHash;\n" ); - } else if(javaTypeName.startsWith("boolean")) { + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + elementHash;\n" ); + } + else if(javaTypeName.startsWith("boolean")) { // propertyHash = 37 * propertyHash + (propertyArray[i] ? 1231 : 1237); - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + (" ) - .append( propertyArrayName ) - .append( "[i] ? 1231 : 1237);\n" ); - } else if(javaTypeName.startsWith("float")) { + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + (" ) + .append( propertyArrayName ) + .append( "[i] ? 1231 : 1237);\n" ); + } + else if(javaTypeName.startsWith("float")) { // propertyHash = 37 * propertyHash + Float.floatToIntBits(propertyArray[i]); - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + Float.floatToIntBits(" ) - .append( propertyArrayName ) - .append( "[i]);\n" ); - } else if(javaTypeName.startsWith("double")) { + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + Float.floatToIntBits(" ) + .append( propertyArrayName ) + .append( "[i]);\n" ); + } + else if(javaTypeName.startsWith("double")) { // long bits = Double.doubleToLongBits(propertyArray[i]); - buf.append( " long bits = Double.doubleToLongBits(" ) - .append( propertyArrayName ) - .append( "[i]);\n" ); + buf.append( " long bits = Double.doubleToLongBits(" ) + .append( propertyArrayName ) + .append( "[i]);\n" ); // propertyHash = 37 * propertyHash + (int)(bits ^ (bits >>> 32)); - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + (int)(bits ^ (bits >>> 32));\n" ); - } else if(javaTypeName.startsWith("int") - || javaTypeName.startsWith("short") - || javaTypeName.startsWith("char") - || javaTypeName.startsWith("byte")) { + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + (int)(bits ^ (bits >>> 32));\n" ); + } + else if(javaTypeName.startsWith("int") + || javaTypeName.startsWith("short") + || javaTypeName.startsWith("char") + || javaTypeName.startsWith("byte")) { // propertyHash = 37 * propertyHash + propertyArray[i]; - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + " ) - .append( propertyArrayName ) - .append( "[i];\n" ); - } else {// Object[] + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + " ) + .append( propertyArrayName ) + .append( "[i];\n" ); + } + else {// Object[] // propertyHash = 37 * propertyHash + propertyArray[i].hashCode(); - buf.append( " " ) - .append( propertyHashVarName ) - .append( " = 37 * " ) - .append( propertyHashVarName ) - .append( " + " ) - .append( propertyArrayName ) - .append( "[i].hashCode();\n" ); - } - - buf.append( " }\n" ); - buf.append( " }\n\n" ); + buf.append( " " ) + .append( propertyHashVarName ) + .append( " = 37 * " ) + .append( propertyHashVarName ) + .append( " + " ) + .append( propertyArrayName ) + .append( "[i].hashCode();\n" ); + } + + buf.append( " }\n" ); + buf.append( " }\n\n" ); // result = 37 * result + arrayHashcode; - buf.append( " " ) - .append( result ) - .append( " = 37 * " ) - .append( result ) - .append( " + " ) - .append( propertyHashVarName ) - .append( ";\n" ); - - return buf.toString(); - } - - - public String getFieldModifiers(Property property) { - return getModifiers( property, "scope-field", "private" ); - } - - public String getPropertyGetModifiers(Property property) { - return getModifiers( property, "scope-get", "public" ); - } - - public String getPropertySetModifiers(Property property) { - return getModifiers( property, "scope-set", "public" ); - } - - //TODO defaultModifiers - private String getModifiers(Property property, String modifiername, String defaultModifiers) { - MetaAttribute override = property.getMetaAttribute( modifiername ); - if ( override != null ) { - return MetaAttributeHelper.getMetaAsString( override ); - } - else { - return defaultModifiers; - } - } - - protected boolean isRequiredInConstructor(Property field) { - if(hasMetaAttribute(field, "default-value")) { - return false; - } - if(field.getValue()!=null) { - if (!(field.isOptional() || field.getValue().isNullable()) && (field.getValueGeneratorCreator() == null )) { - return true; - } else if (field.getValue() instanceof Component c) { + buf.append( " " ) + .append( result ) + .append( " = 37 * " ) + .append( result ) + .append( " + " ) + .append( propertyHashVarName ) + .append( ";\n" ); + + return buf.toString(); + } + + + public String getFieldModifiers(Property property) { + return getModifiers( property, "scope-field", "private" ); + } + + public String getPropertyGetModifiers(Property property) { + return getModifiers( property, "scope-get", "public" ); + } + + public String getPropertySetModifiers(Property property) { + return getModifiers( property, "scope-set", "public" ); + } + + //TODO defaultModifiers + private String getModifiers(Property property, String modifiername, String defaultModifiers) { + MetaAttribute override = property.getMetaAttribute( modifiername ); + if ( override != null ) { + return MetaAttributeHelper.getMetaAsString( override ); + } + else { + return defaultModifiers; + } + } + + protected boolean isRequiredInConstructor(Property field) { + if(hasMetaAttribute(field, "default-value")) { + return false; + } + if(field.getValue()!=null) { + if (!(field.isOptional() || field.getValue().isNullable()) && (field.getValueGeneratorCreator() == null )) { + return true; + } + else if (field.getValue() instanceof Component c) { for (Property prop : c.getProperties()) { if (isRequiredInConstructor(prop)) { return true; } } - } - } - - return false; - } - - public boolean needsMinimalConstructor() { - List propClosure = getPropertyClosureForMinimalConstructor(); - if(propClosure.isEmpty()) return false; // minimal=default + } + } + + return false; + } + + public boolean needsMinimalConstructor() { + List propClosure = getPropertyClosureForMinimalConstructor(); + if(propClosure.isEmpty()) return false; // minimal=default return !propClosure.equals(getPropertyClosureForFullConstructor()); // minimal=full } - public boolean needsFullConstructor() { - return !getPropertyClosureForFullConstructor().isEmpty(); - } - - public String getJavaTypeName(Property p, boolean useGenerics) { - return c2j.getJavaTypeName(p, useGenerics, this); - } - - static private class DefaultInitializor { - - private final String type; - private final boolean initToZero; - - public DefaultInitializor(String type, boolean initToZero) { - this.type = type; - this.initToZero = initToZero; - } - - public String getDefaultValue(String comparator, String genericDeclaration, ImportContext importContext) { - StringBuilder val = new StringBuilder("new " + importContext.importType(type)); - if(genericDeclaration!=null) { - val.append(genericDeclaration); - } - - val.append("("); - if(comparator!=null) { - val.append("new "); - val.append(importContext.importType(comparator)); - val.append("()"); - if(initToZero) val.append(","); - } - if(initToZero) { - val.append("0"); - } - val.append(")"); - return val.toString(); - } - - } - - static Map defaultInitializors = new HashMap(); - static { - defaultInitializors.put("java.util.List", new DefaultInitializor("java.util.ArrayList", true)); - defaultInitializors.put("java.util.Map", new DefaultInitializor("java.util.HashMap", true)); - defaultInitializors.put("java.util.Set", new DefaultInitializor("java.util.HashSet",true)); - defaultInitializors.put("java.util.SortedSet", new DefaultInitializor("java.util.TreeSet", false)); - defaultInitializors.put("java.util.SortedMap", new DefaultInitializor("java.util.TreeMap", false)); - } - - public boolean hasFieldInitializor(Property p, boolean useGenerics) { - return getFieldInitialization(p, useGenerics)!=null; - } - - public String getFieldInitialization(Property p, boolean useGenerics) { - if(hasMetaAttribute(p, "default-value")) { - return MetaAttributeHelper.getMetaAsString( p.getMetaAttribute( "default-value" ) ); - } - if(c2j.getJavaTypeName(p, false)==null) { - throw new IllegalArgumentException(); - } else if (p.getValue() instanceof Collection col) { + public boolean needsFullConstructor() { + return !getPropertyClosureForFullConstructor().isEmpty(); + } + + public String getJavaTypeName(Property p, boolean useGenerics) { + return c2j.getJavaTypeName(p, useGenerics, this); + } + + static private class DefaultInitializor { + + private final String type; + private final boolean initToZero; + + public DefaultInitializor(String type, boolean initToZero) { + this.type = type; + this.initToZero = initToZero; + } + + public String getDefaultValue(String comparator, String genericDeclaration, ImportContext importContext) { + StringBuilder val = new StringBuilder("new " + importContext.importType(type)); + if(genericDeclaration!=null) { + val.append(genericDeclaration); + } + + val.append("("); + if(comparator!=null) { + val.append("new "); + val.append(importContext.importType(comparator)); + val.append("()"); + if(initToZero) val.append(","); + } + if(initToZero) { + val.append("0"); + } + val.append(")"); + return val.toString(); + } + + } + + static Map defaultInitializors = new HashMap<>(); + static { + defaultInitializors.put("java.util.List", new DefaultInitializor("java.util.ArrayList", true)); + defaultInitializors.put("java.util.Map", new DefaultInitializor("java.util.HashMap", true)); + defaultInitializors.put("java.util.Set", new DefaultInitializor("java.util.HashSet",true)); + defaultInitializors.put("java.util.SortedSet", new DefaultInitializor("java.util.TreeSet", false)); + defaultInitializors.put("java.util.SortedMap", new DefaultInitializor("java.util.TreeMap", false)); + } + + public boolean hasFieldInitializor(Property p, boolean useGenerics) { + return getFieldInitialization(p, useGenerics)!=null; + } + + public String getFieldInitialization(Property p, boolean useGenerics) { + if(hasMetaAttribute(p, "default-value")) { + return MetaAttributeHelper.getMetaAsString( p.getMetaAttribute( "default-value" ) ); + } + if(c2j.getJavaTypeName(p, false)==null) { + throw new IllegalArgumentException(); + } + else if (p.getValue() instanceof Collection col) { DefaultInitializor initialization = (DefaultInitializor) col.accept(new DefaultValueVisitor(true) { - - public Object accept(Bag o) { - return new DefaultInitializor("java.util.ArrayList", true); - } - - public Object accept(org.hibernate.mapping.List o) { - return new DefaultInitializor("java.util.ArrayList", true); - } - - public Object accept(org.hibernate.mapping.Map o) { - if(o.isSorted()) { - return new DefaultInitializor("java.util.TreeMap", false); - } else { - return new DefaultInitializor("java.util.HashMap", true); - } - } - - public Object accept(IdentifierBag o) { - return new DefaultInitializor("java.util.ArrayList", true); - } - - public Object accept(Set o) { - if(o.isSorted()) { - return new DefaultInitializor("java.util.TreeSet", false); - } else { - return new DefaultInitializor("java.util.HashSet", true); - } - } - - - public Object accept(PrimitiveArray o) { - return null; // TODO: default init for arrays ? - } - - public Object accept(Array o) { - return null;// TODO: default init for arrays ? - } - - }); - - if(initialization!=null) { - String comparator = null; - String decl = null; - - if(col.isSorted()) { - comparator = col.getComparatorClassName(); - } - - if(useGenerics) { - decl = c2j.getGenericCollectionDeclaration((Collection) p.getValue(), importContext); - } - return initialization.getDefaultValue(comparator, decl, this); - } else { - return null; - } - } else { - return null; - } - } - + + public Object accept(Bag o) { + return new DefaultInitializor("java.util.ArrayList", true); + } + + public Object accept(org.hibernate.mapping.List o) { + return new DefaultInitializor("java.util.ArrayList", true); + } + + public Object accept(org.hibernate.mapping.Map o) { + if(o.isSorted()) { + return new DefaultInitializor("java.util.TreeMap", false); + } + else { + return new DefaultInitializor("java.util.HashMap", true); + } + } + + public Object accept(IdentifierBag o) { + return new DefaultInitializor("java.util.ArrayList", true); + } + + public Object accept(Set o) { + if(o.isSorted()) { + return new DefaultInitializor("java.util.TreeSet", false); + } + else { + return new DefaultInitializor("java.util.HashSet", true); + } + } + + + public Object accept(PrimitiveArray o) { + return null; // TODO: default init for arrays ? + } + + public Object accept(Array o) { + return null;// TODO: default init for arrays ? + } + + }); + + if(initialization!=null) { + String comparator = null; + String decl = null; + + if(col.isSorted()) { + comparator = col.getComparatorClassName(); + } + + if(useGenerics) { + decl = c2j.getGenericCollectionDeclaration((Collection) p.getValue(), importContext); + } + return initialization.getDefaultValue(comparator, decl, this); + } + else { + return null; + } + } + else { + return null; + } + } + } - diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java index 6c46a65f01..aaf35adf2c 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java @@ -55,362 +55,367 @@ */ public class Cfg2JavaTool { - private static final Logger log = Logger.getLogger( Cfg2JavaTool.class ); - - public Cfg2JavaTool() { - - } - - public POJOClass getPOJOClass(Component comp) { - return new ComponentPOJOClass(comp, this); - } - - public POJOClass getPOJOClass(PersistentClass comp) { - return new EntityPOJOClass(comp, this); - } - - public String unqualify(String name) { - return StringHelper.unqualify( name ); - } - - /** - * Returns all meta items as one large string. - * - */ - public String getMetaAsString(MetaAttributable pc, String attribute) { - MetaAttribute c = pc.getMetaAttribute( attribute ); - - return MetaAttributeHelper.getMetaAsString( c ); - } - - public boolean hasMetaAttribute(MetaAttributable pc, String attribute) { - return pc.getMetaAttribute( attribute ) != null; - } - - public String getMetaAsString(MetaAttributable pc, String attribute, String seperator) { - return MetaAttributeHelper.getMetaAsString( pc.getMetaAttribute( attribute ), seperator ); - } - - public boolean getMetaAsBool(MetaAttributable ma, String attribute) { - return getMetaAsBool( ma, attribute, false ); - } - - public boolean getMetaAsBool(MetaAttributable pc, String attribute, boolean defaultValue) { - return MetaAttributeHelper.getMetaAsBool( pc.getMetaAttribute( attribute ), defaultValue ); - } - - - - /** - * Convert string into something that can be rendered nicely into a javadoc - * comment. - * Prefix each line with a star ('*'). - */ - public String toJavaDoc(String string, int indent) { - StringBuilder result = new StringBuilder(); - - if ( string != null ) { - String[] lines = StringUtil.split( string, "\n\r\f" ); - for ( int i = 0; i < lines.length ; i++ ) { - String docline = " * " + lines[i]; - if ( i < lines.length - 1 ) docline += "\n"; - result.append( StringUtil.leftPad( docline, docline.length() + indent ) ); - } - } - - return result.toString(); - } - - public String getClassModifiers(MetaAttributable pc) { - String classModifiers = null; - - // Get scope (backwards compatibility) - if ( pc.getMetaAttribute( "scope-class" ) != null ) { - classModifiers = getMetaAsString( pc, "scope-class" ).trim(); - } - - // Get modifiers - if ( pc.getMetaAttribute( "class-modifier" ) != null ) { - classModifiers = getMetaAsString( pc, "class-modifier" ).trim(); - } - return classModifiers == null ? "public" : classModifiers; - } - - - private String toName(Class c) { - - if ( c.isArray() ) { - Class a = c.getComponentType(); - - return a.getName() + "[]"; - } - else { - return c.getName(); - } - } - - /** - * Returns the typename for a property, using generics if this is a Set type and useGenerics is set to true. - */ - public String getJavaTypeName(Property p, boolean useGenerics) { - return getJavaTypeName(p, useGenerics, new NoopImportContext()); - } - - public String getJavaTypeName(Property p, boolean useGenerics, ImportContext importContext) { - String overrideType = getMetaAsString( p, "property-type" ); - if ( !StringHelper.isEmpty( overrideType ) ) { - String importType = importContext.importType(overrideType); - if ( useGenerics && !importType.contains("<")) { - if ( p.getValue() instanceof Collection ) { - String decl = getGenericCollectionDeclaration( (Collection) p.getValue(), importContext ); - return importType + decl; - } - } - return importType; - } - else { - String rawType = getRawTypeName( p, useGenerics, importContext ); - if(rawType==null) { - throw new IllegalStateException("getJavaTypeName *must* return a value"); - } - return importContext.importType(rawType); - } - } - - private static final Map PRIMITIVES = - new HashMap(); - - static { - PRIMITIVES.put( "char", "Character" ); - PRIMITIVES.put( "byte", "Byte" ); - PRIMITIVES.put( "short", "Short" ); - PRIMITIVES.put( "int", "Integer" ); - PRIMITIVES.put( "long", "Long" ); - PRIMITIVES.put( "boolean", "Boolean" ); - PRIMITIVES.put( "float", "Float" ); - PRIMITIVES.put( "double", "Double" ); - } - - static public boolean isNonPrimitiveTypeName(String typeName) { - return (!PRIMITIVES.containsKey( typeName )) - && new TypeConfiguration() - .getBasicTypeRegistry() - .getRegisteredType(typeName) != null; - } - - private String getRawTypeName(Property p, boolean useGenerics, ImportContext importContext) { - Value value = p.getValue(); - try { - - if (value instanceof Array a) { // array has a string rep.inside. + private static final Logger log = Logger.getLogger( Cfg2JavaTool.class ); + + public Cfg2JavaTool() { + + } + + public POJOClass getPOJOClass(Component comp) { + return new ComponentPOJOClass(comp, this); + } + + public POJOClass getPOJOClass(PersistentClass comp) { + return new EntityPOJOClass(comp, this); + } + + public String unqualify(String name) { + return StringHelper.unqualify( name ); + } + + /** + * Returns all meta items as one large string. + * + */ + public String getMetaAsString(MetaAttributable pc, String attribute) { + MetaAttribute c = pc.getMetaAttribute( attribute ); + + return MetaAttributeHelper.getMetaAsString( c ); + } + + public boolean hasMetaAttribute(MetaAttributable pc, String attribute) { + return pc.getMetaAttribute( attribute ) != null; + } + + public String getMetaAsString(MetaAttributable pc, String attribute, String seperator) { + return MetaAttributeHelper.getMetaAsString( pc.getMetaAttribute( attribute ), seperator ); + } + + public boolean getMetaAsBool(MetaAttributable ma, String attribute) { + return getMetaAsBool( ma, attribute, false ); + } + + public boolean getMetaAsBool(MetaAttributable pc, String attribute, boolean defaultValue) { + return MetaAttributeHelper.getMetaAsBool( pc.getMetaAttribute( attribute ), defaultValue ); + } + + + + /** + * Convert string into something that can be rendered nicely into a javadoc + * comment. + * Prefix each line with a star ('*'). + */ + public String toJavaDoc(String string, int indent) { + StringBuilder result = new StringBuilder(); + + if ( string != null ) { + String[] lines = StringUtil.split( string, "\n\r\f" ); + for ( int i = 0; i < lines.length ; i++ ) { + String docline = " * " + lines[i]; + if ( i < lines.length - 1 ) docline += "\n"; + result.append( StringUtil.leftPad( docline, docline.length() + indent ) ); + } + } + + return result.toString(); + } + + public String getClassModifiers(MetaAttributable pc) { + String classModifiers = null; + + // Get scope (backwards compatibility) + if ( pc.getMetaAttribute( "scope-class" ) != null ) { + classModifiers = getMetaAsString( pc, "scope-class" ).trim(); + } + + // Get modifiers + if ( pc.getMetaAttribute( "class-modifier" ) != null ) { + classModifiers = getMetaAsString( pc, "class-modifier" ).trim(); + } + return classModifiers == null ? "public" : classModifiers; + } + + + private String toName(Class c) { + + if ( c.isArray() ) { + Class a = c.getComponentType(); + + return a.getName() + "[]"; + } + else { + return c.getName(); + } + } + + /** + * Returns the typename for a property, using generics if this is a Set type and useGenerics is set to true. + */ + public String getJavaTypeName(Property p, boolean useGenerics) { + return getJavaTypeName(p, useGenerics, new NoopImportContext()); + } + + public String getJavaTypeName(Property p, boolean useGenerics, ImportContext importContext) { + String overrideType = getMetaAsString( p, "property-type" ); + if ( !StringHelper.isEmpty( overrideType ) ) { + String importType = importContext.importType(overrideType); + if ( useGenerics && !importType.contains("<")) { + if ( p.getValue() instanceof Collection ) { + String decl = getGenericCollectionDeclaration( (Collection) p.getValue(), importContext ); + return importType + decl; + } + } + return importType; + } + else { + String rawType = getRawTypeName( p, useGenerics, importContext ); + if(rawType==null) { + throw new IllegalStateException("getJavaTypeName *must* return a value"); + } + return importContext.importType(rawType); + } + } + + private static final Map PRIMITIVES = + new HashMap<>(); + + static { + PRIMITIVES.put( "char", "Character" ); + PRIMITIVES.put( "byte", "Byte" ); + PRIMITIVES.put( "short", "Short" ); + PRIMITIVES.put( "int", "Integer" ); + PRIMITIVES.put( "long", "Long" ); + PRIMITIVES.put( "boolean", "Boolean" ); + PRIMITIVES.put( "float", "Float" ); + PRIMITIVES.put( "double", "Double" ); + } + + static public boolean isNonPrimitiveTypeName(String typeName) { + return (!PRIMITIVES.containsKey( typeName )) + && new TypeConfiguration() + .getBasicTypeRegistry() + .getRegisteredType(typeName) != null; + } + + private String getRawTypeName(Property p, boolean useGenerics, ImportContext importContext) { + Value value = p.getValue(); + try { + + if (value instanceof Array a) { // array has a string rep.inside. if ( a.isPrimitiveArray() ) { - return toName( value.getType().getReturnedClass() ); - } - else if (a.getElementClassName()!=null){ - return a.getElementClassName() + "[]"; - } else { - return getJavaTypeName(a.getElement()) + "[]"; - } - } - - if (value instanceof Component component) { // same for component. + return toName( value.getType().getReturnedClass() ); + } + else if (a.getElementClassName()!=null){ + return a.getElementClassName() + "[]"; + } + else { + return getJavaTypeName(a.getElement()) + "[]"; + } + } + + if (value instanceof Component component) { // same for component. if(component.isDynamic()) return "java.util.Map"; - return component.getComponentClassName(); - } - - if ( useGenerics ) { - if ( value instanceof Collection ) { - String decl = getGenericCollectionDeclaration( (Collection) value, importContext ); - return getJavaTypeName(value) + decl; - } - } - - return getJavaTypeName( value); - } - catch (Exception e) { - //e.printStackTrace(); - String msg = "Could not resolve type without exception for " + p + " Value: " + value; - if ( value != null && value.isSimpleValue() ) { - String typename = ( (SimpleValue) value ).getTypeName(); - log.warn( msg + ". Falling back to typename: " + typename ); - return typename; - } - else { - throw new RuntimeException( msg, e ); - } - } - } - - public String getGenericCollectionDeclaration(Collection collection, ImportContext importContext) { - Value element = collection.getElement(); - String elementType = importContext.importType(getJavaTypeName(element)); - String genericDecl = elementType; - if(collection.isIndexed()) { - IndexedCollection idxCol = (IndexedCollection) collection; - if(!idxCol.isList()) { - Value idxElement = idxCol.getIndex(); - String indexType = importContext.importType(getJavaTypeName(idxElement)); - genericDecl = indexType + "," + elementType; - } - } + return component.getComponentClassName(); + } + + if ( useGenerics ) { + if ( value instanceof Collection ) { + String decl = getGenericCollectionDeclaration( (Collection) value, importContext ); + return getJavaTypeName(value) + decl; + } + } + + return getJavaTypeName( value); + } + catch (Exception e) { + //e.printStackTrace(); + String msg = "Could not resolve type without exception for " + p + " Value: " + value; + if ( value != null && value.isSimpleValue() ) { + String typename = ( (SimpleValue) value ).getTypeName(); + log.warn( msg + ". Falling back to typename: " + typename ); + return typename; + } + else { + throw new RuntimeException( msg, e ); + } + } + } + + public String getGenericCollectionDeclaration(Collection collection, ImportContext importContext) { + Value element = collection.getElement(); + String elementType = importContext.importType(getJavaTypeName(element)); + String genericDecl = elementType; + if(collection.isIndexed()) { + IndexedCollection idxCol = (IndexedCollection) collection; + if(!idxCol.isList()) { + Value idxElement = idxCol.getIndex(); + String indexType = importContext.importType(getJavaTypeName(idxElement)); + genericDecl = indexType + "," + elementType; + } + } return "<" + genericDecl + ">"; - } - - public Properties getFilteredIdentifierGeneratorProperties(SimpleValue simpleValue) { - Properties p = ((EnhancedValue)simpleValue).getIdentifierGeneratorProperties(); - return Cfg2HbmTool.getFilteredIdentifierGeneratorProperties(p, new Properties()); - } - - private String getJavaTypeName(Value value) { - return (String) value.accept( new JavaTypeFromValueVisitor() ); - } - - public String asParameterList(Iterator fields, boolean useGenerics, ImportContext ic) { - StringBuilder buf = new StringBuilder(); - while ( fields.hasNext() ) { - Property field = (Property)fields.next(); - buf.append( getJavaTypeName( field, useGenerics, ic ) ) - .append( " " ) - .append( keyWordCheck(field.getName()) ); - if ( fields.hasNext() ) { - buf.append( ", " ); - } - } - return buf.toString(); - } - - /** - * @param fields iterator on Property elements. - * @return "name, number, ..." for a property list, usable for method calls. - *

- * TODO: handle this in a template ? - */ - public String asArgumentList(Iterator fields) { - StringBuilder buf = new StringBuilder(); - while ( fields.hasNext() ) { - Property field = (Property)fields.next(); - buf.append( keyWordCheck(field.getName()) ); - if ( fields.hasNext() ) { - buf.append( ", " ); - } - } - return buf.toString(); - } - - /** - * @param clazz persistent class. - * @return "String name, int number, ..." for a property list, usable for method declarations. - *

- * TODO: handle this in a template ? - */ - public String asNaturalIdParameterList(PersistentClass clazz) { - StringBuilder buf = new StringBuilder(); - for (Property field : clazz.getRootClass().getProperties()) { - if ( field.isNaturalIdentifier() ) { - buf.append( getJavaTypeName( field, false ) ) - .append( " " ) - .append( field.getName() ) - .append( ", " ); - } - } - return buf.substring( 0, buf.length() - 2 ); - } - - public String asParameterList(List fields, boolean useGenerics, ImportContext ic) { - return asParameterList( fields.iterator(), useGenerics, ic ); - } - - public String asArgumentList(List fields) { - return asArgumentList( fields.iterator() ); - } - - public String asFinderArgumentList(Map parameterTypes, ImportContext ctx) { - StringBuilder buf = new StringBuilder(); - Iterator> iter = parameterTypes.entrySet().iterator(); - while ( iter.hasNext() ) { - Entry entry = iter.next(); - String typename = null; - Type type = null; - if(entry.getValue() instanceof String) { - try { - type = new TypeConfiguration() - .getBasicTypeRegistry() - .getRegisteredType((String) entry.getValue()); - } catch(Throwable t) { + } + + public Properties getFilteredIdentifierGeneratorProperties(SimpleValue simpleValue) { + Properties p = ((EnhancedValue)simpleValue).getIdentifierGeneratorProperties(); + return Cfg2HbmTool.getFilteredIdentifierGeneratorProperties(p, new Properties()); + } + + private String getJavaTypeName(Value value) { + return (String) value.accept( new JavaTypeFromValueVisitor() ); + } + + public String asParameterList(Iterator fields, boolean useGenerics, ImportContext ic) { + StringBuilder buf = new StringBuilder(); + while ( fields.hasNext() ) { + Property field = (Property)fields.next(); + buf.append( getJavaTypeName( field, useGenerics, ic ) ) + .append( " " ) + .append( keyWordCheck(field.getName()) ); + if ( fields.hasNext() ) { + buf.append( ", " ); + } + } + return buf.toString(); + } + + /** + * @param fields iterator on Property elements. + * @return "name, number, ..." for a property list, usable for method calls. + *

+ * TODO: handle this in a template ? + */ + public String asArgumentList(Iterator fields) { + StringBuilder buf = new StringBuilder(); + while ( fields.hasNext() ) { + Property field = (Property)fields.next(); + buf.append( keyWordCheck(field.getName()) ); + if ( fields.hasNext() ) { + buf.append( ", " ); + } + } + return buf.toString(); + } + + /** + * @param clazz persistent class. + * @return "String name, int number, ..." for a property list, usable for method declarations. + *

+ * TODO: handle this in a template ? + */ + public String asNaturalIdParameterList(PersistentClass clazz) { + StringBuilder buf = new StringBuilder(); + for (Property field : clazz.getRootClass().getProperties()) { + if ( field.isNaturalIdentifier() ) { + buf.append( getJavaTypeName( field, false ) ) + .append( " " ) + .append( field.getName() ) + .append( ", " ); + } + } + return buf.substring( 0, buf.length() - 2 ); + } + + public String asParameterList(List fields, boolean useGenerics, ImportContext ic) { + return asParameterList( fields.iterator(), useGenerics, ic ); + } + + public String asArgumentList(List fields) { + return asArgumentList( fields.iterator() ); + } + + public String asFinderArgumentList(Map parameterTypes, ImportContext ctx) { + StringBuilder buf = new StringBuilder(); + Iterator> iter = parameterTypes.entrySet().iterator(); + while ( iter.hasNext() ) { + Entry entry = iter.next(); + String typename = null; + Type type = null; + if(entry.getValue() instanceof String) { + try { + type = new TypeConfiguration() + .getBasicTypeRegistry() + .getRegisteredType((String) entry.getValue()); + } + catch(Throwable t) { typename = (String) entry.getValue(); - } - } - - if(type!=null) { - typename = type.getReturnedClass().getName(); - } - buf.append( ctx.importType( typename )) - .append( " " ) - .append( entry.getKey() ); - if ( iter.hasNext() ) buf.append( ", " ); - } - return buf.toString(); - } - - - - public boolean isPrimitive(String typeName) { - return PRIMITIVES.containsKey(typeName); - } - - public boolean isComponent(Property property) { - return isComponent(property.getValue()); - } - - public boolean isComponent(Value value) { - return ( value instanceof Component ); - } - - // TODO: should consult exporter/cfg2java tool for cached POJOEntities....or maybe not since they - // have their own state... - public Iterator getPOJOIterator( - final Iterator persistentClasses) { - return new Iterator() { - public POJOClass next() { - return getPOJOClass((PersistentClass)persistentClasses.next()); - } - public boolean hasNext() { - return persistentClasses.hasNext(); - } - public void remove() { - persistentClasses.remove(); - } - }; - } - - - public String simplePluralize(String str) { - return NameConverter.simplePluralize(str); - } - - public String keyWordCheck(String possibleKeyword) { - if(NameConverter.isReservedJavaKeyword(possibleKeyword)) { - possibleKeyword = possibleKeyword + "_"; - } - return possibleKeyword; - } - - public boolean isArray(String typeName) { - return typeName!=null && typeName.endsWith("[]"); - } - - public Map getParameterTypes(NamedHqlQueryDefinition query) { - Map result = null; - try { - Field field = NamedHqlQueryDefinitionImpl.class.getDeclaredField("parameterTypes"); - field.setAccessible(true); - result = (Map)field.get(query); - if (result == null) { - result = new HashMap<>(); - } - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); - } - return result; - } + } + } + + if(type!=null) { + typename = type.getReturnedClass().getName(); + } + buf.append( ctx.importType( typename )) + .append( " " ) + .append( entry.getKey() ); + if ( iter.hasNext() ) buf.append( ", " ); + } + return buf.toString(); + } + + + + public boolean isPrimitive(String typeName) { + return PRIMITIVES.containsKey(typeName); + } + + public boolean isComponent(Property property) { + return isComponent(property.getValue()); + } + + public boolean isComponent(Value value) { + return ( value instanceof Component ); + } + + // TODO: should consult exporter/cfg2java tool for cached POJOEntities....or maybe not since they + // have their own state... + public Iterator getPOJOIterator( + final Iterator persistentClasses) { + return new Iterator<>() { + public POJOClass next() { + return getPOJOClass( persistentClasses.next() ); + } + + public boolean hasNext() { + return persistentClasses.hasNext(); + } + + public void remove() { + persistentClasses.remove(); + } + }; + } + + + public String simplePluralize(String str) { + return NameConverter.simplePluralize(str); + } + + public String keyWordCheck(String possibleKeyword) { + if(NameConverter.isReservedJavaKeyword(possibleKeyword)) { + possibleKeyword = possibleKeyword + "_"; + } + return possibleKeyword; + } + + public boolean isArray(String typeName) { + return typeName!=null && typeName.endsWith("[]"); + } + + public Map getParameterTypes(NamedHqlQueryDefinition query) { + Map result; + try { + Field field = NamedHqlQueryDefinitionImpl.class.getDeclaredField("parameterTypes"); + field.setAccessible(true); + result = (Map)field.get(query); + if (result == null) { + result = new HashMap<>(); + } + } + catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + return result; + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java index e57a83a77c..d29e9a58e6 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java @@ -63,379 +63,382 @@ public class EntityPOJOClass extends BasicPOJOClass { - private final PersistentClass clazz; - - public EntityPOJOClass(PersistentClass clazz, Cfg2JavaTool cfg) { - super(clazz, cfg); - this.clazz = clazz; - init(); - } - - protected String getMappedClassName() { - return clazz.getClassName(); - } - - /** - * @return whatever the class (or interface) extends (null if it does not extend anything) - */ - public String getExtends() { - String extendz = ""; - - if ( isInterface() ) { - if ( clazz.getSuperclass() != null ) { - extendz = clazz.getSuperclass().getClassName(); - } - if ( clazz.getMetaAttribute( EXTENDS ) != null ) { - if ( !extendz.isEmpty() ) { - extendz += ","; - } - extendz += getMetaAsString( EXTENDS, "," ); - } - } - else if ( clazz.getSuperclass() != null ) { - if (!( c2j.getPOJOClass(clazz.getSuperclass()).isInterface() )) { - extendz = clazz.getSuperclass().getClassName(); - } - } - else if ( clazz.getMetaAttribute( EXTENDS ) != null ) { - extendz = getMetaAsString( EXTENDS, "," ); - } - - return extendz.isEmpty() ? null : extendz; - } - - - public String getImplements() { - List interfaces = new ArrayList(); - - // implement proxy, but NOT if the proxy is the class it self! - if ( clazz.getProxyInterfaceName() != null && ( !clazz.getProxyInterfaceName().equals( clazz.getClassName() ) ) ) { - interfaces.add( clazz.getProxyInterfaceName() ); - } - - if ( !isInterface() ) { - if ( clazz.getSuperclass() != null && c2j.getPOJOClass(clazz.getSuperclass()).isInterface() ) { - interfaces.add( clazz.getSuperclass().getClassName() ); - } - if ( clazz.getMetaAttribute( IMPLEMENTS ) != null ) { - interfaces.addAll( clazz.getMetaAttribute( IMPLEMENTS ).getValues() ); - } - interfaces.add( Serializable.class.getName() ); // TODO: is this "nice" ? shouldn't it be a user choice ? - } - - if (!interfaces.isEmpty()) { - StringBuilder sbuf = new StringBuilder(); - for ( Iterator iter = interfaces.iterator(); iter.hasNext() ; ) { - //sbuf.append(JavaTool.shortenType(iter.next().toString(), pc.getImports() ) ); - sbuf.append( iter.next() ); - if ( iter.hasNext() ) sbuf.append( "," ); - } - return sbuf.toString(); - } - else { - return null; - } - } - - public Iterator getAllPropertiesIterator() { - return getAllPropertiesIterator(clazz); - } - - - public Iterator getAllPropertiesIterator(PersistentClass pc) { - List properties = new ArrayList(); - List> lists = new ArrayList>(); - if ( pc.getSuperclass() == null ) { - // only include identifier for the root class. - if ( pc.hasIdentifierProperty() ) { - properties.add( pc.getIdentifierProperty() ); - } - else if ( pc.hasEmbeddedIdentifier() ) { - Component embeddedComponent = (Component) pc.getIdentifier(); - lists.add( embeddedComponent.getProperties() ); - } + private final PersistentClass clazz; + + public EntityPOJOClass(PersistentClass clazz, Cfg2JavaTool cfg) { + super(clazz, cfg); + this.clazz = clazz; + init(); + } + + protected String getMappedClassName() { + return clazz.getClassName(); + } + + /** + * @return whatever the class (or interface) extends (null if it does not extend anything) + */ + public String getExtends() { + String extendz = ""; + + if ( isInterface() ) { + if ( clazz.getSuperclass() != null ) { + extendz = clazz.getSuperclass().getClassName(); + } + if ( clazz.getMetaAttribute( EXTENDS ) != null ) { + if ( !extendz.isEmpty() ) { + extendz += ","; + } + extendz += getMetaAsString( EXTENDS, "," ); + } + } + else if ( clazz.getSuperclass() != null ) { + if (!( c2j.getPOJOClass(clazz.getSuperclass()).isInterface() )) { + extendz = clazz.getSuperclass().getClassName(); + } + } + else if ( clazz.getMetaAttribute( EXTENDS ) != null ) { + extendz = getMetaAsString( EXTENDS, "," ); + } + + return extendz.isEmpty() ? null : extendz; + } + + + public String getImplements() { + List interfaces = new ArrayList<>(); + + // implement proxy, but NOT if the proxy is the class it self! + if ( clazz.getProxyInterfaceName() != null && ( !clazz.getProxyInterfaceName().equals( clazz.getClassName() ) ) ) { + interfaces.add( clazz.getProxyInterfaceName() ); + } + + if ( !isInterface() ) { + if ( clazz.getSuperclass() != null && c2j.getPOJOClass(clazz.getSuperclass()).isInterface() ) { + interfaces.add( clazz.getSuperclass().getClassName() ); + } + if ( clazz.getMetaAttribute( IMPLEMENTS ) != null ) { + interfaces.addAll( clazz.getMetaAttribute( IMPLEMENTS ).getValues() ); + } + interfaces.add( Serializable.class.getName() ); // TODO: is this "nice" ? shouldn't it be a user choice ? + } + + if (!interfaces.isEmpty()) { + StringBuilder sbuf = new StringBuilder(); + for ( Iterator iter = interfaces.iterator(); iter.hasNext() ; ) { + //sbuf.append(JavaTool.shortenType(iter.next().toString(), pc.getImports() ) ); + sbuf.append( iter.next() ); + if ( iter.hasNext() ) sbuf.append( "," ); + } + return sbuf.toString(); + } + else { + return null; + } + } + + public Iterator getAllPropertiesIterator() { + return getAllPropertiesIterator(clazz); + } + + + public Iterator getAllPropertiesIterator(PersistentClass pc) { + List properties = new ArrayList<>(); + List> lists = new ArrayList<>(); + if ( pc.getSuperclass() == null ) { + // only include identifier for the root class. + if ( pc.hasIdentifierProperty() ) { + properties.add( pc.getIdentifierProperty() ); + } + else if ( pc.hasEmbeddedIdentifier() ) { + Component embeddedComponent = (Component) pc.getIdentifier(); + lists.add( embeddedComponent.getProperties() ); + } /*if(clazz.isVersioned() ) { // version is already in property set properties.add(clazz.getVersion() ); }*/ - } - - - // iterators.add( pc.getPropertyIterator() ); - // Need to skip element which are defined via "embedded" components - // Best if we could return an intelligent iterator, but for now we just iterate explicitly. - List pl = pc.getProperties(); - for(Property element : pl) - { - if ( element.getValue() instanceof Component component - && element.getPropertyAccessorName().equals( "embedded" )) { - properties.addAll(component.getProperties()); - } else { - properties.add(element); - } - } - - lists.add(properties); - - return new SkipBackRefPropertyIterator( new JoinedList( lists ).iterator() ); - } - - public boolean isComponent() { - return false; - } - - - public boolean hasIdentifierProperty() { - return clazz.hasIdentifierProperty() && clazz instanceof RootClass; - } - - public Property getIdentifierProperty() { - return clazz.getIdentifierProperty(); - } - - public String generateAnnTableUniqueConstraint() { - if ( ! ( clazz instanceof Subclass ) ) { - Table table = clazz.getTable(); - return generateAnnTableUniqueConstraint( table ); - } - return ""; - } - - protected String generateAnnTableUniqueConstraint(Table table) { - List cons = new ArrayList(); - for (UniqueKey key : table.getUniqueKeys().values()) { - if (table.hasPrimaryKey() && table.getPrimaryKey().getColumns().equals(key.getColumns())) { - continue; - } - AnnotationBuilder constraint = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.UniqueConstraint") ); - constraint.addQuotedAttributes( "columnNames", new IteratorTransformer(key.getColumns().iterator()) { - public String transform(Column column) { - return column.getName(); - } - }); - cons.add( constraint.getResult() ); - } - - AnnotationBuilder builder = AnnotationBuilder.createAnnotation( "dummyAnnotation" ); - builder.addAttributes( "dummyAttribute", cons.iterator() ); - String attributeAsString = builder.getAttributeAsString( "dummyAttribute" ); - return attributeAsString==null?"":attributeAsString; - } - - - public String generateAnnIdGenerator() { - KeyValue identifier = clazz.getIdentifier(); - String strategy = null; - Properties properties = null; - StringBuffer wholeString = new StringBuffer( " " ); - if ( identifier instanceof Component ) { - - wholeString.append( AnnotationBuilder.createAnnotation( importType("jakarta.persistence.EmbeddedId") ).getResult()); - } - else if (identifier instanceof EnhancedBasicValue enhancedBasicValue) { + } + + + // iterators.add( pc.getPropertyIterator() ); + // Need to skip element which are defined via "embedded" components + // Best if we could return an intelligent iterator, but for now we just iterate explicitly. + List pl = pc.getProperties(); + for(Property element : pl) + { + if ( element.getValue() instanceof Component component + && element.getPropertyAccessorName().equals( "embedded" )) { + properties.addAll(component.getProperties()); + } + else { + properties.add(element); + } + } + + lists.add(properties); + + return new SkipBackRefPropertyIterator( new JoinedList<>( lists ).iterator() ); + } + + public boolean isComponent() { + return false; + } + + + public boolean hasIdentifierProperty() { + return clazz.hasIdentifierProperty() && clazz instanceof RootClass; + } + + public Property getIdentifierProperty() { + return clazz.getIdentifierProperty(); + } + + public String generateAnnTableUniqueConstraint() { + if ( ! ( clazz instanceof Subclass ) ) { + Table table = clazz.getTable(); + return generateAnnTableUniqueConstraint( table ); + } + return ""; + } + + protected String generateAnnTableUniqueConstraint(Table table) { + List cons = new ArrayList<>(); + for (UniqueKey key : table.getUniqueKeys().values()) { + if (table.hasPrimaryKey() && table.getPrimaryKey().getColumns().equals(key.getColumns())) { + continue; + } + AnnotationBuilder constraint = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.UniqueConstraint") ); + constraint.addQuotedAttributes( "columnNames", new IteratorTransformer<>( key.getColumns().iterator() ) { + public String transform(Column column) { + return column.getName(); + } + }); + cons.add( constraint.getResult() ); + } + + AnnotationBuilder builder = AnnotationBuilder.createAnnotation( "dummyAnnotation" ); + builder.addAttributes( "dummyAttribute", cons.iterator() ); + String attributeAsString = builder.getAttributeAsString( "dummyAttribute" ); + return attributeAsString==null?"":attributeAsString; + } + + + public String generateAnnIdGenerator() { + KeyValue identifier = clazz.getIdentifier(); + String strategy; + Properties properties; + StringBuffer wholeString = new StringBuffer( " " ); + if ( identifier instanceof Component ) { + + wholeString.append( AnnotationBuilder.createAnnotation( importType("jakarta.persistence.EmbeddedId") ).getResult()); + } + else if (identifier instanceof EnhancedBasicValue enhancedBasicValue) { strategy = enhancedBasicValue.getIdentifierGeneratorStrategy(); - properties = c2j.getFilteredIdentifierGeneratorProperties(enhancedBasicValue); - StringBuilder idResult = new StringBuilder(); - AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.Id") ); - idResult.append(builder.getResult()); - idResult.append(" "); - - boolean isGenericGenerator = false; //TODO: how to handle generic now?? - if ( !"assigned".equals( strategy ) ) { - - if ( !"native".equals( strategy ) ) { - if ( "identity".equals( strategy ) ) { - builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); - builder.addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "IDENTITY" ) ); - idResult.append(builder.getResult()); - } - else if ( "sequence".equals( strategy ) ) { - String sequenceGeneratorName = null; - if (properties != null) { - sequenceGeneratorName = properties.getProperty( - org.hibernate.id.enhanced.SequenceStyleGenerator.SEQUENCE_PARAM, null ); - } - builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ) - .addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "SEQUENCE" ) ) - .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); - idResult.append(builder.getResult()); - - builder.resetAnnotation( importType("jakarta.persistence.SequenceGenerator") ) - .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) - .addQuotedAttribute( "sequenceName", sequenceGeneratorName ); - // TODO HA does not support initialValue and allocationSize - wholeString.append( builder.getResult() ); - } - else if ( TableGenerator.class.getName().equals( strategy ) ) { - builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ) - .addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "TABLE" ) ) - .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); - idResult.append(builder.getResult()); - buildAnnTableGenerator( wholeString, properties ); - } - else { - isGenericGenerator = true; - builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); - builder.addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); - idResult.append(builder.getResult()); - } - } else { - builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); - idResult.append(builder.getResult()); - } - } - if ( isGenericGenerator ) { - builder.resetAnnotation( importType("org.hibernate.annotations.GenericGenerator") ) - .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) - .addQuotedAttribute( "strategy", strategy); - - List params = new ArrayList(); - //wholeString.append( "parameters = { " ); - if ( properties != null ) { - Enumeration propNames = properties.propertyNames(); - while ( propNames.hasMoreElements() ) { - - String propertyName = (String) propNames.nextElement(); - AnnotationBuilder parameter = AnnotationBuilder.createAnnotation( importType("org.hibernate.annotations.Parameter") ) - .addQuotedAttribute( "name", propertyName ) - .addQuotedAttribute( "value", properties.getProperty( propertyName ) ); - params.add( parameter ); - } - } - builder.addAttributes( "parameters", params.iterator() ); - wholeString.append(builder.getResult()); - } - wholeString.append( idResult ); - } - return wholeString.toString(); - } - - private void buildAnnTableGenerator(StringBuffer wholeString, Properties properties) { - - AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.TableGenerator") ); - builder.addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ); - builder.addQuotedAttribute( "table", properties.getProperty( "generatorTableName", "hibernate_sequences" ) ); - if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.CATALOG, properties ) ) { - builder.addQuotedAttribute( "catalog", properties.getProperty( PersistentIdentifierGenerator.CATALOG, "") ); - } - if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.SCHEMA, properties ) ) { - builder.addQuotedAttribute( "schema", properties.getProperty( PersistentIdentifierGenerator.SCHEMA, "") ); - } - if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_VALUE_PARAM, properties ) ) { - builder.addQuotedAttribute( "pkColumnValue", properties.getProperty( TableGenerator.SEGMENT_VALUE_PARAM, "") ); - } - if (propertyDoesNotHaveDefaultValue( TableGenerator.INCREMENT_PARAM, properties, "50" ) ) { - builder.addAttribute( "allocationSize", properties.getProperty( TableGenerator.INCREMENT_PARAM, "50" ) ); - } - if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_COLUMN_PARAM, properties ) ) { - builder.addQuotedAttribute( "pkColumnName", properties.getProperty( TableGenerator.SEGMENT_COLUMN_PARAM, "") ); - } - if (propertyDoesNotHaveDefaultValue( TableGenerator.VALUE_COLUMN_PARAM, properties) ) { - builder.addQuotedAttribute( "valueColumnName", properties.getProperty( TableGenerator.VALUE_COLUMN_PARAM, "") ); - } - wholeString.append(builder.getResult()).append("\n "); - } - - private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties) { - return propertyDoesNotHaveDefaultValue(property, properties, null); - } - - private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties, String defaultValue) { - String propertyValue = properties.getProperty(property); - if (defaultValue == null) { - return StringHelper.isNotEmpty(propertyValue); - } else { - return !defaultValue.equals(propertyValue); - } - } - - public String generateJoinColumnsAnnotation(Property property, Metadata md) { - boolean insertable = property.isInsertable(); - boolean updatable = property.isUpdatable(); - Value value = property.getValue(); - int span; - Iterator selectablesIterator; - Iterator referencedSelectablesIterator = null; - if (value instanceof Collection collection) { + properties = c2j.getFilteredIdentifierGeneratorProperties(enhancedBasicValue); + StringBuilder idResult = new StringBuilder(); + AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.Id") ); + idResult.append(builder.getResult()); + idResult.append(" "); + + boolean isGenericGenerator = false; //TODO: how to handle generic now?? + if ( !"assigned".equals( strategy ) ) { + + if ( !"native".equals( strategy ) ) { + if ( "identity".equals( strategy ) ) { + builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); + builder.addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "IDENTITY" ) ); + idResult.append(builder.getResult()); + } + else if ( "sequence".equals( strategy ) ) { + String sequenceGeneratorName = null; + if (properties != null) { + sequenceGeneratorName = properties.getProperty( + org.hibernate.id.enhanced.SequenceStyleGenerator.SEQUENCE_PARAM, null ); + } + builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ) + .addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "SEQUENCE" ) ) + .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); + idResult.append(builder.getResult()); + + builder.resetAnnotation( importType("jakarta.persistence.SequenceGenerator") ) + .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) + .addQuotedAttribute( "sequenceName", sequenceGeneratorName ); + // TODO HA does not support initialValue and allocationSize + wholeString.append( builder.getResult() ); + } + else if ( TableGenerator.class.getName().equals( strategy ) ) { + builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ) + .addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "TABLE" ) ) + .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); + idResult.append(builder.getResult()); + buildAnnTableGenerator( wholeString, properties ); + } + else { + isGenericGenerator = true; + builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); + builder.addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); + idResult.append(builder.getResult()); + } + } + else { + builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ); + idResult.append(builder.getResult()); + } + } + if ( isGenericGenerator ) { + builder.resetAnnotation( importType("org.hibernate.annotations.GenericGenerator") ) + .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) + .addQuotedAttribute( "strategy", strategy); + + List params = new ArrayList<>(); + //wholeString.append( "parameters = { " ); + if ( properties != null ) { + Enumeration propNames = properties.propertyNames(); + while ( propNames.hasMoreElements() ) { + + String propertyName = (String) propNames.nextElement(); + AnnotationBuilder parameter = AnnotationBuilder.createAnnotation( importType("org.hibernate.annotations.Parameter") ) + .addQuotedAttribute( "name", propertyName ) + .addQuotedAttribute( "value", properties.getProperty( propertyName ) ); + params.add( parameter ); + } + } + builder.addAttributes( "parameters", params.iterator() ); + wholeString.append(builder.getResult()); + } + wholeString.append( idResult ); + } + return wholeString.toString(); + } + + private void buildAnnTableGenerator(StringBuffer wholeString, Properties properties) { + + AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.TableGenerator") ); + builder.addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ); + builder.addQuotedAttribute( "table", properties.getProperty( "generatorTableName", "hibernate_sequences" ) ); + if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.CATALOG, properties ) ) { + builder.addQuotedAttribute( "catalog", properties.getProperty( PersistentIdentifierGenerator.CATALOG, "") ); + } + if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.SCHEMA, properties ) ) { + builder.addQuotedAttribute( "schema", properties.getProperty( PersistentIdentifierGenerator.SCHEMA, "") ); + } + if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_VALUE_PARAM, properties ) ) { + builder.addQuotedAttribute( "pkColumnValue", properties.getProperty( TableGenerator.SEGMENT_VALUE_PARAM, "") ); + } + if (propertyDoesNotHaveDefaultValue( TableGenerator.INCREMENT_PARAM, properties, "50" ) ) { + builder.addAttribute( "allocationSize", properties.getProperty( TableGenerator.INCREMENT_PARAM, "50" ) ); + } + if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_COLUMN_PARAM, properties ) ) { + builder.addQuotedAttribute( "pkColumnName", properties.getProperty( TableGenerator.SEGMENT_COLUMN_PARAM, "") ); + } + if (propertyDoesNotHaveDefaultValue( TableGenerator.VALUE_COLUMN_PARAM, properties) ) { + builder.addQuotedAttribute( "valueColumnName", properties.getProperty( TableGenerator.VALUE_COLUMN_PARAM, "") ); + } + wholeString.append(builder.getResult()).append("\n "); + } + + private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties) { + return propertyDoesNotHaveDefaultValue(property, properties, null); + } + + private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties, String defaultValue) { + String propertyValue = properties.getProperty(property); + if (defaultValue == null) { + return StringHelper.isNotEmpty(propertyValue); + } + else { + return !defaultValue.equals(propertyValue); + } + } + + public String generateJoinColumnsAnnotation(Property property, Metadata md) { + boolean insertable = property.isInsertable(); + boolean updatable = property.isUpdatable(); + Value value = property.getValue(); + int span; + Iterator selectablesIterator; + Iterator referencedSelectablesIterator = null; + if (value instanceof Collection collection) { span = collection.getKey().getColumnSpan(); - selectablesIterator = collection.getKey().getSelectables().iterator(); - } - else { - span = property.getColumnSpan(); - selectablesIterator = property.getSelectables().iterator(); - } - - if(property.getValue() instanceof ToOne) { - String referencedEntityName = ((ToOne)property.getValue()).getReferencedEntityName(); - PersistentClass target = md.getEntityBinding(referencedEntityName); - if(target!=null) { - referencedSelectablesIterator = target.getKey().getSelectables().iterator(); - } - } - - StringBuffer annotations = new StringBuffer( " " ); - if ( span == 1 ) { - Selectable selectable = selectablesIterator.next(); - buildJoinColumnAnnotation( selectable, null, annotations, insertable, updatable ); - } - else { + selectablesIterator = collection.getKey().getSelectables().iterator(); + } + else { + span = property.getColumnSpan(); + selectablesIterator = property.getSelectables().iterator(); + } + + if(property.getValue() instanceof ToOne) { + String referencedEntityName = ((ToOne)property.getValue()).getReferencedEntityName(); + PersistentClass target = md.getEntityBinding(referencedEntityName); + if(target!=null) { + referencedSelectablesIterator = target.getKey().getSelectables().iterator(); + } + } + + StringBuffer annotations = new StringBuffer( " " ); + if ( span == 1 ) { + Selectable selectable = selectablesIterator.next(); + buildJoinColumnAnnotation( selectable, null, annotations, insertable, updatable ); + } + else { annotations.append("@").append( importType("jakarta.persistence.JoinColumns") ).append("( { " ); - buildArrayOfJoinColumnAnnotation(selectablesIterator, referencedSelectablesIterator, annotations, insertable, updatable ); - annotations.append( " } )" ); - } - return annotations.toString(); - } - - private void buildArrayOfJoinColumnAnnotation( - Iterator columns, - Iterator referencedColumnsIterator, - StringBuffer annotations, - boolean insertable, - boolean updatable - ) { - while ( columns.hasNext() ) { - Selectable selectable = columns.next(); + buildArrayOfJoinColumnAnnotation(selectablesIterator, referencedSelectablesIterator, annotations, insertable, updatable ); + annotations.append( " } )" ); + } + return annotations.toString(); + } + + private void buildArrayOfJoinColumnAnnotation( + Iterator columns, + Iterator referencedColumnsIterator, + StringBuffer annotations, + boolean insertable, + boolean updatable + ) { + while ( columns.hasNext() ) { + Selectable selectable = columns.next(); Selectable referencedColumn = null; if(referencedColumnsIterator!=null) { - referencedColumn = referencedColumnsIterator.next(); - } - - //TODO formula in multicolumns not supported by annotations - if (!( selectable.isFormula() )) { - annotations.append( "\n " ); - buildJoinColumnAnnotation( selectable, referencedColumn, annotations, insertable, updatable ); - annotations.append( ", " ); - } - } - annotations.setLength( annotations.length() - 2 ); - } - - private void buildJoinColumnAnnotation( - Selectable selectable, - Selectable referencedColumn, - StringBuffer annotations, - boolean insertable, - boolean updatable) { - //TODO not supported by HA - if (!( selectable.isFormula() )) { - Column column = (Column) selectable; - annotations.append("@").append( importType("jakarta.persistence.JoinColumn") ) - .append("(name=\"" ).append( column.getName() ).append( "\"" ); - //TODO handle referenced column name, this is a hard one - if(referencedColumn!=null) { - annotations.append(", referencedColumnName=\"" ).append( referencedColumn.getText() ).append( "\"" ); - } - - appendCommonColumnInfo(annotations, column, insertable, updatable); - //TODO support secondary table - annotations.append( ")" ); - } - } - - public String[] getCascadeTypes(Property property) { - StringTokenizer st = new StringTokenizer( property.getCascade(), ", ", false ); - List types = new ArrayList(); - while ( st.hasMoreElements() ) { - String element = ( (String) st.nextElement() ).toLowerCase(); + referencedColumn = referencedColumnsIterator.next(); + } + + //TODO formula in multicolumns not supported by annotations + if (!( selectable.isFormula() )) { + annotations.append( "\n " ); + buildJoinColumnAnnotation( selectable, referencedColumn, annotations, insertable, updatable ); + annotations.append( ", " ); + } + } + annotations.setLength( annotations.length() - 2 ); + } + + private void buildJoinColumnAnnotation( + Selectable selectable, + Selectable referencedColumn, + StringBuffer annotations, + boolean insertable, + boolean updatable) { + //TODO not supported by HA + if (!( selectable.isFormula() )) { + Column column = (Column) selectable; + annotations.append("@").append( importType("jakarta.persistence.JoinColumn") ) + .append("(name=\"" ).append( column.getName() ).append( "\"" ); + //TODO handle referenced column name, this is a hard one + if(referencedColumn!=null) { + annotations.append(", referencedColumnName=\"" ).append( referencedColumn.getText() ).append( "\"" ); + } + + appendCommonColumnInfo(annotations, column, insertable, updatable); + //TODO support secondary table + annotations.append( ")" ); + } + } + + public String[] getCascadeTypes(Property property) { + StringTokenizer st = new StringTokenizer( property.getCascade(), ", ", false ); + List types = new ArrayList<>(); + while ( st.hasMoreElements() ) { + String element = ( (String) st.nextElement() ).toLowerCase(); switch (element) { case "persist" -> types.add(importType("jakarta.persistence.CascadeType") + ".PERSIST"); case "merge" -> types.add(importType("jakarta.persistence.CascadeType") + ".MERGE"); @@ -443,65 +446,65 @@ public String[] getCascadeTypes(Property property) { case "refresh" -> types.add(importType("jakarta.persistence.CascadeType") + ".REFRESH"); case "all" -> types.add(importType("jakarta.persistence.CascadeType") + ".ALL"); } - } - return types.toArray(new String[0]); - } + } + return types.toArray(new String[0]); + } - public String generateManyToOneAnnotation(Property property) { + public String generateManyToOneAnnotation(Property property) { return AnnotationBuilder.createAnnotation(importType("jakarta.persistence.ManyToOne")) .addAttribute("cascade", getCascadeTypes(property)) .addAttribute("fetch", getFetchType(property)) .getResult() + getHibernateCascadeTypeAnnotation(property); - } + } - public boolean isSharedPkBasedOneToOne(OneToOne oneToOne){ - Iterator joinSelectablesIt = oneToOne.getSelectables().iterator(); - Set joinSelectables = new HashSet(); - while ( joinSelectablesIt.hasNext() ) { - joinSelectables.add( joinSelectablesIt.next() ); - } + public boolean isSharedPkBasedOneToOne(OneToOne oneToOne){ + Iterator joinSelectablesIt = oneToOne.getSelectables().iterator(); + Set joinSelectables = new HashSet<>(); + while ( joinSelectablesIt.hasNext() ) { + joinSelectables.add( joinSelectablesIt.next() ); + } - if (joinSelectables.isEmpty()) - return false; + if (joinSelectables.isEmpty()) + return false; for (Selectable selectable : getIdentifierProperty().getSelectables()) { if (!joinSelectables.contains(selectable)) return false; } - return true; - } + return true; + } - public String generateOneToOneAnnotation(Property property, Metadata md) { - OneToOne oneToOne = (OneToOne)property.getValue(); + public String generateOneToOneAnnotation(Property property, Metadata md) { + OneToOne oneToOne = (OneToOne)property.getValue(); - boolean pkIsAlsoFk = isSharedPkBasedOneToOne(oneToOne); + boolean pkIsAlsoFk = isSharedPkBasedOneToOne(oneToOne); - AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.OneToOne") ) - .addAttribute( "cascade", getCascadeTypes(property)) - .addAttribute( "fetch", getFetchType(property)); + AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.OneToOne") ) + .addAttribute( "cascade", getCascadeTypes(property)) + .addAttribute( "fetch", getFetchType(property)); - if ( oneToOne.getForeignKeyType().equals(ForeignKeyDirection.TO_PARENT) ){ - ab.addQuotedAttribute("mappedBy", getOneToOneMappedBy(md, oneToOne)); - } + if ( oneToOne.getForeignKeyType().equals(ForeignKeyDirection.TO_PARENT) ){ + ab.addQuotedAttribute("mappedBy", getOneToOneMappedBy(md, oneToOne)); + } - StringBuilder buffer = new StringBuilder(ab.getResult()); - buffer.append(getHibernateCascadeTypeAnnotation(property)); + StringBuilder buffer = new StringBuilder(ab.getResult()); + buffer.append(getHibernateCascadeTypeAnnotation(property)); - if ( pkIsAlsoFk && oneToOne.getForeignKeyType().equals(ForeignKeyDirection.FROM_PARENT) ){ - AnnotationBuilder ab1 = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.PrimaryKeyJoinColumn") ); - buffer.append(ab1.getResult()); - } + if ( pkIsAlsoFk && oneToOne.getForeignKeyType().equals(ForeignKeyDirection.FROM_PARENT) ){ + AnnotationBuilder ab1 = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.PrimaryKeyJoinColumn") ); + buffer.append(ab1.getResult()); + } - return buffer.toString(); - } + return buffer.toString(); + } - public String getHibernateCascadeTypeAnnotation(Property property) { - StringTokenizer st = new StringTokenizer( property.getCascade(), ", ", false ); - String cascadeType = null; - StringBuilder cascade = new StringBuilder(); - while ( st.hasMoreElements() ) { - String element = ( (String) st.nextElement() ).toLowerCase(); + public String getHibernateCascadeTypeAnnotation(Property property) { + StringTokenizer st = new StringTokenizer( property.getCascade(), ", ", false ); + String cascadeType = null; + StringBuilder cascade = new StringBuilder(); + while ( st.hasMoreElements() ) { + String element = ( (String) st.nextElement() ).toLowerCase(); switch (element) { case "all-delete-orphan" -> { if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); @@ -529,389 +532,399 @@ public String getHibernateCascadeTypeAnnotation(Property property) { cascade.append(cascadeType).append(".EVICT").append(", "); } } - } - if ( cascade.length() >= 2 ) { - String hibernateCascade = importType("org.hibernate.annotations.Cascade"); - cascade.insert(0, "@" + hibernateCascade + "( {"); - cascade.setLength( cascade.length() - 2 ); - cascade.append("} )"); - } - return cascade.toString(); - } - - public String getFetchType(Property property) { - Value value = property.getValue(); - String fetchType = importType( "jakarta.persistence.FetchType"); - boolean lazy = false; - if ( value instanceof ToOne ) { - lazy = ( (ToOne) value ).isLazy(); - } - else if ( value instanceof Collection ) { - lazy = ( (Collection) value ).isLazy(); - } - else { - //we're not collection neither *toone so we are looking for property fetching - lazy = property.isLazy(); - } - if ( lazy ) { - return fetchType + "." + "LAZY"; - } - else { - return fetchType + "." + "EAGER"; - } - } - - public Object getDecoratedObject() { - return clazz; - } - - public String generateCollectionAnnotation(Property property, Metadata md) { - StringBuffer annotation = new StringBuffer(); - Value value = property.getValue(); - if (value instanceof Collection collection) { + } + if ( cascade.length() >= 2 ) { + String hibernateCascade = importType("org.hibernate.annotations.Cascade"); + cascade.insert(0, "@" + hibernateCascade + "( {"); + cascade.setLength( cascade.length() - 2 ); + cascade.append("} )"); + } + return cascade.toString(); + } + + public String getFetchType(Property property) { + Value value = property.getValue(); + String fetchType = importType( "jakarta.persistence.FetchType"); + boolean lazy; + if ( value instanceof ToOne ) { + lazy = ( (ToOne) value ).isLazy(); + } + else if ( value instanceof Collection ) { + lazy = ( (Collection) value ).isLazy(); + } + else { + //we're not collection neither *toone so we are looking for property fetching + lazy = property.isLazy(); + } + if ( lazy ) { + return fetchType + "." + "LAZY"; + } + else { + return fetchType + "." + "EAGER"; + } + } + + public Object getDecoratedObject() { + return clazz; + } + + public String generateCollectionAnnotation(Property property, Metadata md) { + StringBuffer annotation = new StringBuffer(); + Value value = property.getValue(); + if (value instanceof Collection collection) { if ( collection.isOneToMany() ) { - String mappedBy = null; - AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType( "jakarta.persistence.OneToMany") ); - ab.addAttribute( "cascade", getCascadeTypes( property ) ); - ab.addAttribute( "fetch", getFetchType (property) ); - if ( collection.isInverse() ) { - mappedBy = getOneToManyMappedBy( md, collection ); - ab.addQuotedAttribute( "mappedBy", mappedBy ); - } - annotation.append( ab.getResult() ); - - if (mappedBy == null) annotation.append("\n").append( generateJoinColumnsAnnotation(property, md) ); - } - else { - //TODO do the @OneToMany @JoinTable - //TODO composite element - String mappedBy = null; - AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType( "jakarta.persistence.ManyToMany") ); - ab.addAttribute( "cascade", getCascadeTypes( property ) ); - ab.addAttribute( "fetch", getFetchType (property) ); - - if ( collection.isInverse() ) { - mappedBy = getManyToManyMappedBy( md, collection ); - ab.addQuotedAttribute( "mappedBy", mappedBy ); - } - annotation.append(ab.getResult()); - if (mappedBy == null) { - annotation.append("\n @"); - annotation.append( importType( "jakarta.persistence.JoinTable") ).append( "(name=\"" ); - Table table = collection.getCollectionTable(); - - annotation.append( table.getName() ); - annotation.append( "\"" ); - if ( StringHelper.isNotEmpty( table.getSchema() ) ) { - annotation.append(", schema=\"").append( table.getSchema() ).append("\""); - } - if ( StringHelper.isNotEmpty( table.getCatalog() ) ) { - annotation.append(", catalog=\"").append( table.getCatalog() ).append("\""); - } - String uniqueConstraint = generateAnnTableUniqueConstraint(table); - if (!uniqueConstraint.isEmpty()) { - annotation.append(", uniqueConstraints=").append(uniqueConstraint); - } - annotation.append( ", joinColumns = { "); - buildArrayOfJoinColumnAnnotation( - collection.getKey().getSelectables().iterator(), - null, - annotation, - property.isInsertable(), - property.isUpdatable() - ); - annotation.append( " }"); - annotation.append( ", inverseJoinColumns = { "); - buildArrayOfJoinColumnAnnotation( - collection.getElement().getSelectables().iterator(), - null, - annotation, - property.isInsertable(), - property.isUpdatable() - ); - annotation.append( " }"); - annotation.append(")"); - } - - } - String hibernateCascade = getHibernateCascadeTypeAnnotation( property ); - if (!hibernateCascade.isEmpty()) annotation.append("\n ").append(hibernateCascade); - } - return annotation.toString(); - } - - private String getManyToManyMappedBy(Metadata md, Collection collection) { - String mappedBy; - Iterator joinColumnsIt = collection.getKey().getSelectables().iterator(); - Set joinColumns = new HashSet(); - while ( joinColumnsIt.hasNext() ) { - joinColumns.add( joinColumnsIt.next() ); - } - ManyToOne manyToOne = (ManyToOne) collection.getElement(); - PersistentClass pc = md.getEntityBinding(manyToOne.getReferencedEntityName()); - Iterator properties = pc.getProperties().iterator(); - //TODO we should check the table too - boolean isOtherSide = false; - mappedBy = "unresolved"; - while ( ! isOtherSide && properties.hasNext() ) { - Property collectionProperty = properties.next(); - Value collectionValue = collectionProperty.getValue(); - if (collectionValue instanceof Collection realCollectionValue) { + String mappedBy = null; + AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType( "jakarta.persistence.OneToMany") ); + ab.addAttribute( "cascade", getCascadeTypes( property ) ); + ab.addAttribute( "fetch", getFetchType (property) ); + if ( collection.isInverse() ) { + mappedBy = getOneToManyMappedBy( md, collection ); + ab.addQuotedAttribute( "mappedBy", mappedBy ); + } + annotation.append( ab.getResult() ); + + if (mappedBy == null) annotation.append("\n").append( generateJoinColumnsAnnotation(property, md) ); + } + else { + //TODO do the @OneToMany @JoinTable + //TODO composite element + String mappedBy = null; + AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType( "jakarta.persistence.ManyToMany") ); + ab.addAttribute( "cascade", getCascadeTypes( property ) ); + ab.addAttribute( "fetch", getFetchType (property) ); + + if ( collection.isInverse() ) { + mappedBy = getManyToManyMappedBy( md, collection ); + ab.addQuotedAttribute( "mappedBy", mappedBy ); + } + annotation.append(ab.getResult()); + if (mappedBy == null) { + annotation.append("\n @"); + annotation.append( importType( "jakarta.persistence.JoinTable") ).append( "(name=\"" ); + Table table = collection.getCollectionTable(); + + annotation.append( table.getName() ); + annotation.append( "\"" ); + if ( StringHelper.isNotEmpty( table.getSchema() ) ) { + annotation.append(", schema=\"").append( table.getSchema() ).append("\""); + } + if ( StringHelper.isNotEmpty( table.getCatalog() ) ) { + annotation.append(", catalog=\"").append( table.getCatalog() ).append("\""); + } + String uniqueConstraint = generateAnnTableUniqueConstraint(table); + if (!uniqueConstraint.isEmpty()) { + annotation.append(", uniqueConstraints=").append(uniqueConstraint); + } + annotation.append( ", joinColumns = { "); + buildArrayOfJoinColumnAnnotation( + collection.getKey().getSelectables().iterator(), + null, + annotation, + property.isInsertable(), + property.isUpdatable() + ); + annotation.append( " }"); + annotation.append( ", inverseJoinColumns = { "); + buildArrayOfJoinColumnAnnotation( + collection.getElement().getSelectables().iterator(), + null, + annotation, + property.isInsertable(), + property.isUpdatable() + ); + annotation.append( " }"); + annotation.append(")"); + } + + } + String hibernateCascade = getHibernateCascadeTypeAnnotation( property ); + if (!hibernateCascade.isEmpty()) annotation.append("\n ").append(hibernateCascade); + } + return annotation.toString(); + } + + private String getManyToManyMappedBy(Metadata md, Collection collection) { + String mappedBy; + Iterator joinColumnsIt = collection.getKey().getSelectables().iterator(); + Set joinColumns = new HashSet<>(); + while ( joinColumnsIt.hasNext() ) { + joinColumns.add( joinColumnsIt.next() ); + } + ManyToOne manyToOne = (ManyToOne) collection.getElement(); + PersistentClass pc = md.getEntityBinding(manyToOne.getReferencedEntityName()); + Iterator properties = pc.getProperties().iterator(); + //TODO we should check the table too + boolean isOtherSide = false; + mappedBy = "unresolved"; + while ( ! isOtherSide && properties.hasNext() ) { + Property collectionProperty = properties.next(); + Value collectionValue = collectionProperty.getValue(); + if (collectionValue instanceof Collection realCollectionValue) { if ( ! realCollectionValue.isOneToMany() ) { - if ( joinColumns.size() == realCollectionValue.getElement().getColumnSpan() ) { - isOtherSide = true; + if ( joinColumns.size() == realCollectionValue.getElement().getColumnSpan() ) { + isOtherSide = true; for (Selectable selectable : realCollectionValue.getElement().getSelectables()) { if (!joinColumns.contains(selectable)) { isOtherSide = false; break; } } - if (isOtherSide) { - mappedBy = collectionProperty.getName(); - } - } - } - } - } - return mappedBy; - } - - private String getOneToManyMappedBy(Metadata md, Collection collection) { - String mappedBy; - Iterator joinColumnsIt = collection.getKey().getSelectables().iterator(); - Set joinColumns = new HashSet(); - while ( joinColumnsIt.hasNext() ) { - joinColumns.add( joinColumnsIt.next() ); - } - OneToMany oneToMany = (OneToMany) collection.getElement(); - PersistentClass pc = md.getEntityBinding(oneToMany.getReferencedEntityName()); - Iterator properties = pc.getProperties().iterator(); - //TODO we should check the table too - boolean isOtherSide = false; - mappedBy = "unresolved"; - while ( ! isOtherSide && properties.hasNext() ) { - Property manyProperty = properties.next(); - Value manyValue = manyProperty.getValue(); - if (manyValue instanceof ManyToOne) { - if ( joinColumns.size() == manyValue.getColumnSpan() ) { - isOtherSide = true; + if (isOtherSide) { + mappedBy = collectionProperty.getName(); + } + } + } + } + } + return mappedBy; + } + + private String getOneToManyMappedBy(Metadata md, Collection collection) { + String mappedBy; + Iterator joinColumnsIt = collection.getKey().getSelectables().iterator(); + Set joinColumns = new HashSet<>(); + while ( joinColumnsIt.hasNext() ) { + joinColumns.add( joinColumnsIt.next() ); + } + OneToMany oneToMany = (OneToMany) collection.getElement(); + PersistentClass pc = md.getEntityBinding(oneToMany.getReferencedEntityName()); + Iterator properties = pc.getProperties().iterator(); + //TODO we should check the table too + boolean isOtherSide = false; + mappedBy = "unresolved"; + while ( ! isOtherSide && properties.hasNext() ) { + Property manyProperty = properties.next(); + Value manyValue = manyProperty.getValue(); + if (manyValue instanceof ManyToOne) { + if ( joinColumns.size() == manyValue.getColumnSpan() ) { + isOtherSide = true; for (Selectable selectable : manyValue.getSelectables()) { if (!joinColumns.contains(selectable)) { isOtherSide = false; break; } } - if (isOtherSide) { - mappedBy = manyProperty.getName(); - } - } - - } - } - return mappedBy; - } - - private String getOneToOneMappedBy(Metadata md, OneToOne oneToOne) { - String mappedBy; - Iterator joinSelectablesIt = oneToOne.getSelectables().iterator(); - Set joinSelectables = new HashSet(); - while ( joinSelectablesIt.hasNext() ) { - joinSelectables.add( joinSelectablesIt.next() ); - } - PersistentClass pc = md.getEntityBinding(oneToOne.getReferencedEntityName()); - String referencedPropertyName = oneToOne.getReferencedPropertyName(); - if ( referencedPropertyName != null ) - return referencedPropertyName; - - Iterator properties = pc.getProperties().iterator(); - //TODO we should check the table too - boolean isOtherSide = false; - mappedBy = "unresolved"; - - - while ( ! isOtherSide && properties.hasNext() ) { - Property oneProperty = properties.next(); - Value manyValue = oneProperty.getValue(); - if ((manyValue instanceof OneToOne || manyValue instanceof ManyToOne)) { - if ( joinSelectables.size() == manyValue.getColumnSpan() ) { - isOtherSide = true; + if (isOtherSide) { + mappedBy = manyProperty.getName(); + } + } + + } + } + return mappedBy; + } + + private String getOneToOneMappedBy(Metadata md, OneToOne oneToOne) { + String mappedBy; + Iterator joinSelectablesIt = oneToOne.getSelectables().iterator(); + Set joinSelectables = new HashSet<>(); + while ( joinSelectablesIt.hasNext() ) { + joinSelectables.add( joinSelectablesIt.next() ); + } + PersistentClass pc = md.getEntityBinding(oneToOne.getReferencedEntityName()); + String referencedPropertyName = oneToOne.getReferencedPropertyName(); + if ( referencedPropertyName != null ) + return referencedPropertyName; + + Iterator properties = pc.getProperties().iterator(); + //TODO we should check the table too + boolean isOtherSide = false; + mappedBy = "unresolved"; + + + while ( ! isOtherSide && properties.hasNext() ) { + Property oneProperty = properties.next(); + Value manyValue = oneProperty.getValue(); + if ((manyValue instanceof OneToOne || manyValue instanceof ManyToOne)) { + if ( joinSelectables.size() == manyValue.getColumnSpan() ) { + isOtherSide = true; for (Selectable selectable : manyValue.getSelectables()) { if (!joinSelectables.contains(selectable)) { isOtherSide = false; break; } } - if (isOtherSide) { - mappedBy = oneProperty.getName(); - } - } - - } - } - return mappedBy; - } - - public boolean isSubclass() { - return clazz.getSuperclass()!=null; - } - - public List getPropertyClosureForFullConstructor() { - return getPropertyClosureForFullConstructor(clazz); - } - - protected List getPropertyClosureForFullConstructor(PersistentClass pc) { - List l = new ArrayList(getPropertyClosureForSuperclassFullConstructor( pc )); - l.addAll(getPropertiesForFullConstructor( pc )); - return l; - } - - public List getPropertiesForFullConstructor() { - return getPropertiesForFullConstructor(clazz); - } - - protected List getPropertiesForFullConstructor(PersistentClass pc) { - List result = new ArrayList(); - - for ( Iterator myFields = getAllPropertiesIterator(pc); myFields.hasNext() ; ) { - Property field = (Property) myFields.next(); - // TODO: if(!field.isGenerated() ) ) { - if(field.equals(pc.getIdentifierProperty()) && !isAssignedIdentifier(pc, field)) { - continue; // dont add non assigned identifiers - } else if(field.equals(pc.getVersion())) { - continue; // version prop - } else if(field.isBackRef()) { - continue; - } else if(isFormula(field)) { - continue; - } else { - result.add( field ); - } - } - - return result; - } - - private boolean isFormula(Property field) { - Value value = field.getValue(); - boolean foundFormula = false; - - if(value!=null && value.getColumnSpan()>0) { + if (isOtherSide) { + mappedBy = oneProperty.getName(); + } + } + + } + } + return mappedBy; + } + + public boolean isSubclass() { + return clazz.getSuperclass()!=null; + } + + public List getPropertyClosureForFullConstructor() { + return getPropertyClosureForFullConstructor(clazz); + } + + protected List getPropertyClosureForFullConstructor(PersistentClass pc) { + List l = new ArrayList<>( getPropertyClosureForSuperclassFullConstructor( pc ) ); + l.addAll(getPropertiesForFullConstructor( pc )); + return l; + } + + public List getPropertiesForFullConstructor() { + return getPropertiesForFullConstructor(clazz); + } + + protected List getPropertiesForFullConstructor(PersistentClass pc) { + List result = new ArrayList<>(); + + for ( Iterator myFields = getAllPropertiesIterator(pc); myFields.hasNext() ; ) { + Property field = myFields.next(); + // TODO: if(!field.isGenerated() ) ) { + if(field.equals(pc.getIdentifierProperty()) && !isAssignedIdentifier(pc, field)) { + continue; // dont add non assigned identifiers + } + else if(field.equals(pc.getVersion())) { + continue; // version prop + } + else if(field.isBackRef()) { + continue; + } + else if(isFormula(field)) { + continue; + } + else { + result.add( field ); + } + } + + return result; + } + + private boolean isFormula(Property field) { + Value value = field.getValue(); + boolean foundFormula = false; + + if(value!=null && value.getColumnSpan()>0) { for (Selectable element : value.getSelectables()) { if (!(element instanceof Formula)) { return false; - } else { + } + else { foundFormula = true; } } - } else { - return false; - } - return foundFormula; - } - - public List getPropertyClosureForSuperclassFullConstructor() { - return getPropertyClosureForSuperclassFullConstructor(clazz); - } - - public List getPropertyClosureForSuperclassFullConstructor(PersistentClass pc) { - List result = new ArrayList(); - if ( pc.getSuperclass() != null ) { - // The correct sequence is vital here, as the subclass should be - // able to invoke the fullconstructor based on the sequence returned - // by this method! - result.addAll( getPropertyClosureForSuperclassFullConstructor( pc.getSuperclass() ) ); - result.addAll( getPropertiesForFullConstructor( pc.getSuperclass() ) ); - } - - return result; - } - - - public List getPropertyClosureForMinimalConstructor() { - return getPropertyClosureForMinimalConstructor(clazz); - } - - protected List getPropertyClosureForMinimalConstructor(PersistentClass pc) { - List l = new ArrayList(getPropertyClosureForSuperclassMinConstructor( pc )); - l.addAll(getPropertiesForMinimalConstructor( pc )); - return l; - } - - public List getPropertiesForMinimalConstructor() { - return getPropertiesForMinimalConstructor(clazz); - } - - protected List getPropertiesForMinimalConstructor(PersistentClass pc) { - List result = new ArrayList(); - - for ( Iterator myFields = getAllPropertiesIterator(pc); myFields.hasNext() ; ) { - Property property = (Property) myFields.next(); - if(property.equals(pc.getIdentifierProperty())) { - if(isAssignedIdentifier(pc, property)) { - result.add(property); - } else { - continue; - } - } else if (property.equals(pc.getVersion())) { - continue; // the version property should not be in the result. - } else if( isRequiredInConstructor(property) ) { - result.add(property); - } - } - - return result; - } - - protected boolean isAssignedIdentifier(PersistentClass pc, Property property) { - if(property.equals(pc.getIdentifierProperty())) { - if(property.getValue() instanceof EnhancedValue sv) { + } + else { + return false; + } + return foundFormula; + } + + public List getPropertyClosureForSuperclassFullConstructor() { + return getPropertyClosureForSuperclassFullConstructor(clazz); + } + + public List getPropertyClosureForSuperclassFullConstructor(PersistentClass pc) { + List result = new ArrayList<>(); + if ( pc.getSuperclass() != null ) { + // The correct sequence is vital here, as the subclass should be + // able to invoke the fullconstructor based on the sequence returned + // by this method! + result.addAll( getPropertyClosureForSuperclassFullConstructor( pc.getSuperclass() ) ); + result.addAll( getPropertiesForFullConstructor( pc.getSuperclass() ) ); + } + + return result; + } + + + public List getPropertyClosureForMinimalConstructor() { + return getPropertyClosureForMinimalConstructor(clazz); + } + + protected List getPropertyClosureForMinimalConstructor(PersistentClass pc) { + List l = new ArrayList<>( getPropertyClosureForSuperclassMinConstructor( pc ) ); + l.addAll(getPropertiesForMinimalConstructor( pc )); + return l; + } + + public List getPropertiesForMinimalConstructor() { + return getPropertiesForMinimalConstructor(clazz); + } + + protected List getPropertiesForMinimalConstructor(PersistentClass pc) { + List result = new ArrayList<>(); + + for ( Iterator myFields = getAllPropertiesIterator(pc); myFields.hasNext() ; ) { + Property property = myFields.next(); + if(property.equals(pc.getIdentifierProperty())) { + if(isAssignedIdentifier(pc, property)) { + result.add(property); + } + else { + continue; + } + } + else if (property.equals(pc.getVersion())) { + continue; // the version property should not be in the result. + } + else if( isRequiredInConstructor(property) ) { + result.add(property); + } + } + + return result; + } + + protected boolean isAssignedIdentifier(PersistentClass pc, Property property) { + if(property.equals(pc.getIdentifierProperty())) { + if(property.getValue() instanceof EnhancedValue sv) { return "assigned".equals(sv.getIdentifierGeneratorStrategy()); - } else if (property.getValue().isSimpleValue()) { - ValueUtil v = new ValueUtil((SimpleValue)property.getValue()); + } + else if (property.getValue().isSimpleValue()) { + ValueUtil v = new ValueUtil((SimpleValue)property.getValue()); return "assigned".equals(v.getIdentifierGeneratorStrategy()); - } - } - return false; - } - - public List getPropertyClosureForSuperclassMinimalConstructor() { - return getPropertyClosureForSuperclassMinConstructor(clazz); - } - - protected List getPropertyClosureForSuperclassMinConstructor(PersistentClass pc) { - List result = new ArrayList(); - if ( pc.getSuperclass() != null ) { - // The correct sequence is vital here, as the subclass should be - // able to invoke the fullconstructor based on the sequence returned - // by this method! - result.addAll( getPropertyClosureForSuperclassMinConstructor( pc.getSuperclass() ) ); - result.addAll( getPropertiesForMinimalConstructor( pc.getSuperclass() ) ); - } - - return result; - } - - public POJOClass getSuperClass(){ - if (!isSubclass()) - return null; - return new EntityPOJOClass(clazz.getSuperclass(),c2j); - } - - - public String toString() { - return "Entity: " + (clazz==null?"":clazz.getEntityName()); - } - - public boolean hasVersionProperty() { - return clazz.isVersioned() && clazz instanceof RootClass; - } - - /* - * @see org.hibernate.tool.hbm2x.pojo.POJOClass#getVersionProperty() - */ - public Property getVersionProperty() - { - return clazz.getVersion(); - } + } + } + return false; + } + + public List getPropertyClosureForSuperclassMinimalConstructor() { + return getPropertyClosureForSuperclassMinConstructor(clazz); + } + + protected List getPropertyClosureForSuperclassMinConstructor(PersistentClass pc) { + List result = new ArrayList<>(); + if ( pc.getSuperclass() != null ) { + // The correct sequence is vital here, as the subclass should be + // able to invoke the fullconstructor based on the sequence returned + // by this method! + result.addAll( getPropertyClosureForSuperclassMinConstructor( pc.getSuperclass() ) ); + result.addAll( getPropertiesForMinimalConstructor( pc.getSuperclass() ) ); + } + + return result; + } + + public POJOClass getSuperClass(){ + if (!isSubclass()) + return null; + return new EntityPOJOClass(clazz.getSuperclass(),c2j); + } + + + public String toString() { + return "Entity: " + (clazz==null?"":clazz.getEntityName()); + } + + public boolean hasVersionProperty() { + return clazz.isVersioned() && clazz instanceof RootClass; + } + + /* + * @see org.hibernate.tool.hbm2x.pojo.POJOClass#getVersionProperty() + */ + public Property getVersionProperty() + { + return clazz.getVersion(); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/ImportContextImpl.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/ImportContextImpl.java index 821d7b3d31..f6f48fa11c 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/ImportContextImpl.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/ImportContextImpl.java @@ -26,130 +26,132 @@ public class ImportContextImpl implements ImportContext { - Set imports = new TreeSet(); - Set staticImports = new TreeSet(); - Map simpleNames = new HashMap(); - - String basePackage = ""; - - // TODO: share this somehow, redundant from Cfg2JavaTool - private static final Map PRIMITIVES = new HashMap(); - static { - PRIMITIVES.put( "char", "Character" ); - - PRIMITIVES.put( "byte", "Byte" ); - PRIMITIVES.put( "short", "Short" ); - PRIMITIVES.put( "int", "Integer" ); - PRIMITIVES.put( "long", "Long" ); - - PRIMITIVES.put( "boolean", "Boolean" ); - - PRIMITIVES.put( "float", "Float" ); - PRIMITIVES.put( "double", "Double" ); - - } - - public ImportContextImpl(String basePackage) { - this.basePackage = basePackage; - } - - /** - * Add fqcn to the import list. Returns fqcn as needed in source code. - * Attempts to handle fqcn with array and generics references. - *

- * e.g. - * java.util.Collection imports java.util.Collection and returns Collection - * org.marvel.Hulk[] imports org.marvel.Hulk and returns Hulk - * - * - * @return import string - */ - public String importType(String fqcn) { - String result = fqcn; - - String additionalTypePart = null; - if(fqcn.indexOf('<')>=0) { - additionalTypePart = result.substring(fqcn.indexOf('<')); - result = result.substring(0,fqcn.indexOf('<')); - fqcn = result; - } else if(fqcn.indexOf('[')>=0) { - additionalTypePart = result.substring(fqcn.indexOf('[')); - result = result.substring(0,fqcn.indexOf('[')); - fqcn = result; - } - - String pureFqcn = fqcn.replace( '$', '.' ); - - boolean canBeSimple = true; - - - String simpleName = StringHelper.unqualify(fqcn); - if(simpleNames.containsKey(simpleName)) { - String existingFqcn = (String) simpleNames.get(simpleName); + Set imports = new TreeSet<>(); + Set staticImports = new TreeSet<>(); + Map simpleNames = new HashMap<>(); + + String basePackage; + + // TODO: share this somehow, redundant from Cfg2JavaTool + private static final Map PRIMITIVES = new HashMap<>(); + static { + PRIMITIVES.put( "char", "Character" ); + + PRIMITIVES.put( "byte", "Byte" ); + PRIMITIVES.put( "short", "Short" ); + PRIMITIVES.put( "int", "Integer" ); + PRIMITIVES.put( "long", "Long" ); + + PRIMITIVES.put( "boolean", "Boolean" ); + + PRIMITIVES.put( "float", "Float" ); + PRIMITIVES.put( "double", "Double" ); + + } + + public ImportContextImpl(String basePackage) { + this.basePackage = basePackage; + } + + /** + * Add fqcn to the import list. Returns fqcn as needed in source code. + * Attempts to handle fqcn with array and generics references. + *

+ * e.g. + * java.util.Collection imports java.util.Collection and returns Collection + * org.marvel.Hulk[] imports org.marvel.Hulk and returns Hulk + * + * + * @return import string + */ + public String importType(String fqcn) { + String result = fqcn; + + String additionalTypePart = null; + if(fqcn.indexOf('<')>=0) { + additionalTypePart = result.substring(fqcn.indexOf('<')); + result = result.substring(0,fqcn.indexOf('<')); + fqcn = result; + } + else if(fqcn.indexOf('[')>=0) { + additionalTypePart = result.substring(fqcn.indexOf('[')); + result = result.substring(0,fqcn.indexOf('[')); + fqcn = result; + } + + String pureFqcn = fqcn.replace( '$', '.' ); + + boolean canBeSimple = true; + + + String simpleName = StringHelper.unqualify(fqcn); + if(simpleNames.containsKey(simpleName)) { + String existingFqcn = simpleNames.get(simpleName); canBeSimple = existingFqcn.equals(pureFqcn); - } else { + } + else { simpleNames.put(simpleName, pureFqcn); - imports.add( pureFqcn ); - } - - - if ( inSamePackage(fqcn) || (imports.contains( pureFqcn ) && canBeSimple) ) { - result = StringHelper.unqualify( result ); // dequalify - } else if ( inJavaLang( fqcn ) ) { - result = result.substring( "java.lang.".length() ); - } - - if(additionalTypePart!=null) { - result = result + additionalTypePart; - } - - result = result.replace( '$', '.' ); - return result; - } - - public String staticImport(String fqcn, String member) { - String local = fqcn + "." + member; - imports.add(local); - staticImports.add(local); - - if(member.equals("*")) { - return ""; - } else { - return member; - } - } - - private boolean inDefaultPackage(String className) { - return !className.contains("."); - } - - private boolean isPrimitive(String className) { - return PRIMITIVES.containsKey( className ); - } - - private boolean inSamePackage(String className) { - return StringHelper.qualifier( className ).equals(basePackage); - } - - private boolean inJavaLang(String className) { - return "java.lang".equals( StringHelper.qualifier( className ) ); - } - - public String generateImports() { - StringBuilder buf = new StringBuilder(); + imports.add( pureFqcn ); + } + + + if ( inSamePackage(fqcn) || (imports.contains( pureFqcn ) && canBeSimple) ) { + result = StringHelper.unqualify( result ); // dequalify + } + else if ( inJavaLang( fqcn ) ) { + result = result.substring( "java.lang.".length() ); + } + + if(additionalTypePart!=null) { + result = result + additionalTypePart; + } + + result = result.replace( '$', '.' ); + return result; + } + + public String staticImport(String fqcn, String member) { + String local = fqcn + "." + member; + imports.add(local); + staticImports.add(local); + + if(member.equals("*")) { + return ""; + } + else { + return member; + } + } + + private boolean inDefaultPackage(String className) { + return !className.contains("."); + } + + private boolean isPrimitive(String className) { + return PRIMITIVES.containsKey( className ); + } + + private boolean inSamePackage(String className) { + return StringHelper.qualifier( className ).equals(basePackage); + } + + private boolean inJavaLang(String className) { + return "java.lang".equals( StringHelper.qualifier( className ) ); + } + + public String generateImports() { + StringBuilder buf = new StringBuilder(); for (String next : imports) { if (!(isPrimitive(next) || inDefaultPackage(next) || inJavaLang(next) || inSamePackage(next))) { - if (staticImports.contains(next)) { + if (staticImports.contains(next)) { buf.append("import static ").append(next).append(";\r\n"); - } else { + } + else { buf.append("import ").append(next).append(";\r\n"); } } } - - if(buf.indexOf( "$" )>=0) { - return buf.toString(); - } - return buf.toString(); - } + + return buf.toString(); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/JavaTypeFromValueVisitor.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/JavaTypeFromValueVisitor.java index 1cc4ba2765..397b5861ea 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/JavaTypeFromValueVisitor.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/JavaTypeFromValueVisitor.java @@ -33,86 +33,84 @@ public class JavaTypeFromValueVisitor extends DefaultValueVisitor { - - private boolean preferRawTypeNames = true; - - public JavaTypeFromValueVisitor() { - super( true ); - } - - // special handling for Map's to avoid initialization of comparators that depends on the keys/values which might not be generated yet. - public Object accept(Map o) { - if ( o.isSorted() ) { - return "java.util.SortedMap"; - } - return super.accept(o); - } - - // special handling for Set's to avoid initialization of comparators that depends on the keys/values which might not be generated yet. - public Object accept(Set o) { - if ( o.isSorted() ) { - return "java.util.SortedSet"; - } - return super.accept(o); - } - - public Object accept(Component value) { - // composite-element breaks without it. - return value.getComponentClassName(); - } - - public Object accept(OneToOne o) { - return acceptToOne(o); - } - - public Object accept(ManyToOne o) { - return acceptToOne(o); - } - - private Object acceptToOne(ToOne value) { - return value.getReferencedEntityName(); // should get the cfg and lookup the persistenclass. - } - - public Object accept(OneToMany value) { - return value.getAssociatedClass().getClassName(); - } - - private String toName(Class c) { - - if ( c.isArray() ) { - Class a = c.getComponentType(); - - return a.getName() + "[]"; - } - else { - return c.getName(); - } - } - - protected Object handle(Value o) { - Value value = (Value) o; - try { - // have to attempt calling gettype to decide if its custom type. - Type type = value.getType(); - if(type instanceof CustomType) { - return toName( type.getReturnedClass() ); - } - } catch(HibernateException he) { - // ignore - } - - if ( preferRawTypeNames && value.isSimpleValue() ) { - // this logic make us use the raw typename if it is something else than an Hibernate type. So, if user wrote long we will use long...if he meant to have a Long then he should use the java.lang.Long version. - String typename = ( (SimpleValue) value ).getTypeName(); - if ( !Cfg2JavaTool.isNonPrimitiveTypeName( typename ) ) { - String val = ( (SimpleValue) value ).getTypeName(); - if(val!=null) return val; // val can be null when type is any - } - } - - return toName( value.getType().getReturnedClass() ); - - } - - + + public JavaTypeFromValueVisitor() { + super( true ); + } + + // special handling for Map's to avoid initialization of comparators that depends on the keys/values which might not be generated yet. + public Object accept(Map o) { + if ( o.isSorted() ) { + return "java.util.SortedMap"; + } + return super.accept(o); + } + + // special handling for Set's to avoid initialization of comparators that depends on the keys/values which might not be generated yet. + public Object accept(Set o) { + if ( o.isSorted() ) { + return "java.util.SortedSet"; + } + return super.accept(o); + } + + public Object accept(Component value) { + // composite-element breaks without it. + return value.getComponentClassName(); + } + + public Object accept(OneToOne o) { + return acceptToOne(o); + } + + public Object accept(ManyToOne o) { + return acceptToOne(o); + } + + private Object acceptToOne(ToOne value) { + return value.getReferencedEntityName(); // should get the cfg and lookup the persistenclass. + } + + public Object accept(OneToMany value) { + return value.getAssociatedClass().getClassName(); + } + + private String toName(Class c) { + + if ( c.isArray() ) { + Class a = c.getComponentType(); + + return a.getName() + "[]"; + } + else { + return c.getName(); + } + } + + protected Object handle(Value o) { + try { + // have to attempt calling gettype to decide if its custom type. + Type type = o.getType(); + if(type instanceof CustomType) { + return toName( type.getReturnedClass() ); + } + } + catch(HibernateException he) { + // ignore + } + + if ( o.isSimpleValue() ) { + // this logic make us use the raw typename if it is something else than an Hibernate type. So, if user wrote long we will use long...if he meant to have a Long then he should use the java.lang.Long version. + String typename = ( (SimpleValue) o).getTypeName(); + if ( !Cfg2JavaTool.isNonPrimitiveTypeName( typename ) ) { + String val = ( (SimpleValue) o).getTypeName(); + if(val!=null) return val; // val can be null when type is any + } + } + + return toName( o.getType().getReturnedClass() ); + + } + + } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/lint/InstrumentationDetector.java b/orm/src/main/java/org/hibernate/tool/internal/export/lint/InstrumentationDetector.java index cb4c361306..ba66bc2504 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/lint/InstrumentationDetector.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/lint/InstrumentationDetector.java @@ -26,68 +26,68 @@ import org.hibernate.mapping.Property; public class InstrumentationDetector extends EntityModelDetector { - - public String getName() { - return "instrument"; - } - private boolean enhanceEnabled; - - public void initialize(Metadata metadata) { - super.initialize(metadata); - if (metadata instanceof MetadataImplementor) { - final BytecodeProvider bytecodeProvider = - ((MetadataImplementor)metadata).getMetadataBuildingOptions().getServiceRegistry() - .getService( BytecodeProvider.class ); - if(bytecodeProvider != null - && !(bytecodeProvider instanceof org.hibernate.bytecode.internal.none.BytecodeProviderImpl)) { - enhanceEnabled = true; - } - } - } - - protected void visit(PersistentClass clazz, IssueCollector collector) { - Class mappedClass; - try { - mappedClass = clazz.getMappedClass(); - } catch(MappingException me) { - // ignore - return; - } + public String getName() { + return "instrument"; + } - if(clazz.isLazy()) { - try { - mappedClass.getConstructor( new Class[0] ); - } - catch (SecurityException e) { - // ignore - } - catch (NoSuchMethodException e) { - collector.reportIssue(new Issue("LAZY_NO_DEFAULT_CONSTRUCTOR",Issue.NORMAL_PRIORITY, "lazy='true' set for '" + clazz.getEntityName() +"', but class has no default constructor." )); - return; - } + private boolean enhanceEnabled; - } else if(enhanceEnabled){ - Class[] interfaces = mappedClass.getInterfaces(); - boolean enhanced = false; + public void initialize(Metadata metadata) { + super.initialize(metadata); + if (metadata instanceof MetadataImplementor) { + final BytecodeProvider bytecodeProvider = + ((MetadataImplementor)metadata).getMetadataBuildingOptions().getServiceRegistry() + .getService( BytecodeProvider.class ); + if(bytecodeProvider != null + && !(bytecodeProvider instanceof org.hibernate.bytecode.internal.none.BytecodeProviderImpl)) { + enhanceEnabled = true; + } + } + } + + protected void visit(PersistentClass clazz, IssueCollector collector) { + Class mappedClass; + try { + mappedClass = clazz.getMappedClass(); + } + catch(MappingException me) { + // ignore + return; + } + + if(clazz.isLazy()) { + try { + mappedClass.getConstructor(); + } + catch (SecurityException e) { + // ignore + } + catch (NoSuchMethodException e) { + collector.reportIssue(new Issue("LAZY_NO_DEFAULT_CONSTRUCTOR",Issue.NORMAL_PRIORITY, "lazy='true' set for '" + clazz.getEntityName() +"', but class has no default constructor." )); + } + + } + else if(enhanceEnabled){ + Class[] interfaces = mappedClass.getInterfaces(); + boolean enhanced = false; for (Class intface : interfaces) { if (intface.getName().equals(Managed.class.getName())) { enhanced = true; break; } } - - if (!enhanced) { - collector.reportIssue( new Issue("LAZY_NOT_INSTRUMENTED", Issue.HIGH_PRIORITY, "'" + clazz.getEntityName() + "' has lazy='false', but its class '" + mappedClass.getName() + "' has not been instrumented with javaassist") ); - return; - } - - } - } - @Override - protected void visitProperty( - Property property, - IssueCollector collector) { - } + if (!enhanced) { + collector.reportIssue( new Issue("LAZY_NOT_INSTRUMENTED", Issue.HIGH_PRIORITY, "'" + clazz.getEntityName() + "' has lazy='false', but its class '" + mappedClass.getName() + "' has not been instrumented with javaassist") ); + } + + } + } + + @Override + protected void visitProperty( + Property property, + IssueCollector collector) { + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/lint/SchemaByMetaDataDetector.java b/orm/src/main/java/org/hibernate/tool/internal/export/lint/SchemaByMetaDataDetector.java index 3cee0c2eb5..99ff32b978 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/lint/SchemaByMetaDataDetector.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/lint/SchemaByMetaDataDetector.java @@ -54,285 +54,273 @@ import org.hibernate.tool.internal.util.TableNameQualifier; import org.hibernate.type.MappingContext; -@SuppressWarnings("deprecation") public class SchemaByMetaDataDetector extends RelationalModelDetector { - public String getName() { - return "schema"; - } - - DatabaseReader reader; - - private SequenceCollector sequenceCollector; - - private TableSelectorStrategy tableSelector; - - private RevengDialect metadataDialect; - - private Dialect dialect; - - private MappingContext mapping; - - private Properties properties; - - /** current table as read from the database */ - Table currentDbTable = null; - - public void initialize(Metadata metadata) { - super.initialize( metadata); - StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); - ServiceRegistry serviceRegistry = builder.build(); - - properties = Environment.getProperties(); - dialect = serviceRegistry.getService(JdbcServices.class).getDialect(); - - tableSelector = new TableSelectorStrategy( - new DefaultStrategy() ); - metadataDialect = RevengDialectFactory - .createMetaDataDialect( - dialect, - properties ); - reader = DatabaseReader.create( - properties, - tableSelector, - metadataDialect, - serviceRegistry); - ConnectionProvider connectionProvider = serviceRegistry.getService(ConnectionProvider.class); - sequenceCollector = SequenceCollector.create(connectionProvider); - } - - public void visit(IssueCollector collector) { - super.visit(collector); - visitGenerators(collector); - } - - public void visitGenerators(IssueCollector collector) { - Iterator iter = iterateGenerators(); - - Set sequences = Collections.EMPTY_SET; - if(dialect.getSequenceSupport().supportsSequences()) { - sequences = sequenceCollector.readSequences(dialect.getQuerySequencesString()); - } - - // TODO: move this check into something that could check per class or collection instead. - while ( iter.hasNext() ) { - PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next(); - Object key = getGeneratorKey(generator); - if ( !isSequence(key, sequences) && !isTable( key ) ) { - collector.reportIssue( new Issue( "MISSING_ID_GENERATOR", Issue.HIGH_PRIORITY, "Missing sequence or table: " + key)); - } - } - - } - - private boolean isSequence(Object key, Set sequences) { - if(key instanceof String) { - if ( sequences.contains( key ) ) { - return true; - } else { - String[] strings = StringHelper.split(".", (String) key); - if(strings.length==3) { - return sequences.contains(strings[2]); - } else if (strings.length==2) { - return sequences.contains(strings[1]); - } - } - } - return false; - } - - private boolean isTable(Object key) throws HibernateException { - // BIG HACK - should probably utilize the table cache before going to the jdbcreader :( - if(key instanceof String) { - String[] strings = StringHelper.split(".", (String) key); - if(strings.length==1) { - tableSelector.clearSchemaSelections(); - tableSelector.addSchemaSelection( createSchemaSelection(null,null, strings[0]) ); - Collection

collection = readFromDatabase(); - return !collection.isEmpty(); - } else if(strings.length==3) { - tableSelector.clearSchemaSelections(); - tableSelector.addSchemaSelection( createSchemaSelection(strings[0],strings[1], strings[2]) ); - Collection
collection = readFromDatabase(); - return !collection.isEmpty(); - } else if (strings.length==2) { - tableSelector.clearSchemaSelections(); - tableSelector.addSchemaSelection( createSchemaSelection(null,strings[0], strings[1]) ); - Collection
collection = readFromDatabase(); - return !collection.isEmpty(); - } - } - return false; - } - - public void visit(Table table, IssueCollector pc) { - - if ( table.isPhysicalTable() ) { - setSchemaSelection( table ); - - Collection
collection = readFromDatabase(); - - if ( collection.isEmpty() ) { - pc.reportIssue( new Issue( "SCHEMA_TABLE_MISSING", - Issue.HIGH_PRIORITY, "Missing table " - + TableNameQualifier.qualify( table.getCatalog(), table - .getSchema(), table.getName() ) ) ); - return; - } - else if ( collection.size() > 1 ) { - pc.reportIssue( new Issue( "SCHEMA_TABLE_MISSING", - Issue.NORMAL_PRIORITY, "Found " - + collection.size() - + " tables for " - + TableNameQualifier.qualify( table.getCatalog(), table - .getSchema(), table.getName() ) ) ); - return; - } - else { - currentDbTable = collection.iterator().next(); - visitColumns(table,pc); - } - } - else { - // log? - } - } - - String table(Table t) { - return TableNameQualifier.qualify( t.getCatalog(), t.getSchema(), t.getName() ); - } - - public void visit( - Table table, - Column col, - IssueCollector pc) { - if ( currentDbTable == null ) { - return; - } - - Column dbColumn = currentDbTable - .getColumn( new Column( col.getName() ) ); - - if ( dbColumn == null ) { - pc.reportIssue( new Issue( "SCHEMA_COLUMN_MISSING", - Issue.HIGH_PRIORITY, table(table) + " is missing column: " + col.getName() ) ); - } - else { - //TODO: this needs to be able to know if a type is truly compatible or not. Right now it requires an exact match. - //String sqlType = col.getSqlType( dialect, mapping ); - int dbTypeCode = dbColumn.getSqlTypeCode().intValue(); - int modelTypeCode = col - .getSqlTypeCode( mapping ); - // TODO: sqltype name string - if ( !(dbTypeCode == modelTypeCode ) ) { - pc.reportIssue( new Issue( "SCHEMA_COLUMN_TYPE_MISMATCH", - Issue.NORMAL_PRIORITY, table(table) + " has a wrong column type for " - + col.getName() + ", expected: " - + JdbcToHibernateTypeHelper.getJDBCTypeName(modelTypeCode) + " but was " + JdbcToHibernateTypeHelper.getJDBCTypeName(dbTypeCode) + " in db") ); - } - } - } - - private void setSchemaSelection(Table table) { - tableSelector.clearSchemaSelections(); - tableSelector.addSchemaSelection( createSchemaSelection( - table.getCatalog(), - table.getSchema(), - table.getName() ) ); - } - - /** - * - * @param cfg - * @return iterator over all the IdentifierGenerator's found in the entitymodel and return a list of unique IdentifierGenerators - * @throws MappingException - */ - private Iterator iterateGenerators() throws MappingException { - - TreeMap generators = - new TreeMap(); - - Iterator persistentClassIterator = getMetadata().getEntityBindings().iterator(); - while ( persistentClassIterator.hasNext() ) { - PersistentClass pc = persistentClassIterator.next(); - - if ( !pc.isInherited() ) { - - Generator ig = pc.getIdentifier() - .createGenerator( - dialect, - (RootClass) pc - ); - - if ( ig instanceof PersistentIdentifierGenerator ) { - generators.put( getGeneratorKey( (PersistentIdentifierGenerator) ig ), ig ); - } - - } - } - - Iterator collectionIterator = getMetadata().getCollectionBindings().iterator(); - while ( collectionIterator.hasNext() ) { - org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) collectionIterator.next(); - - if ( collection.isIdentified() ) { - - Generator ig = ( (IdentifierCollection) collection ).getIdentifier() - .createGenerator( - dialect, - null - ); - - if ( ig instanceof PersistentIdentifierGenerator ) { - generators.put( ( getGeneratorKey((PersistentIdentifierGenerator) ig )), ig ); - } - - } - } - - return generators.values().iterator(); - } - - private Collection
readFromDatabase() { - RevengMetadataCollector revengMetadataCollector = new RevengMetadataCollector(); - reader.readDatabaseSchema(revengMetadataCollector); - return revengMetadataCollector.getTables(); - } - - private SchemaSelection createSchemaSelection(String matchCatalog, String matchSchema, String matchTable) { - return new SchemaSelection() { - @Override - public String getMatchCatalog() { - return matchCatalog; - } - @Override - public String getMatchSchema() { - return matchSchema; - } - @Override - public String getMatchTable() { - return matchTable; - } - - }; - } - - private String getGeneratorKey(PersistentIdentifierGenerator ig) { - String result = null; - if (ig instanceof SequenceStyleGenerator) { - result = getKeyForSequenceStyleGenerator((SequenceStyleGenerator)ig); - } else if (ig instanceof TableGenerator) { - result = getKeyForTableGenerator((TableGenerator)ig); - } - return result; - } - - private String getKeyForSequenceStyleGenerator(SequenceStyleGenerator ig) { - return ig.getDatabaseStructure().getPhysicalName().render(); - } - - private String getKeyForTableGenerator(TableGenerator ig) { - return ig.getTableName(); - } + public String getName() { + return "schema"; + } + + DatabaseReader reader; + + private SequenceCollector sequenceCollector; + + private TableSelectorStrategy tableSelector; + + private Dialect dialect; + + private MappingContext mapping; + + /** current table as read from the database */ + Table currentDbTable = null; + + public void initialize(Metadata metadata) { + super.initialize( metadata); + StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); + ServiceRegistry serviceRegistry = builder.build(); + + Properties properties = Environment.getProperties(); + JdbcServices jdbcServices = serviceRegistry.getService(JdbcServices.class); + if (jdbcServices != null) { + dialect = jdbcServices.getDialect(); + } + + tableSelector = new TableSelectorStrategy( + new DefaultStrategy() ); + RevengDialect metadataDialect = RevengDialectFactory + .createMetaDataDialect( + dialect, + properties ); + reader = DatabaseReader.create( + properties, + tableSelector, + metadataDialect, + serviceRegistry); + ConnectionProvider connectionProvider = serviceRegistry.getService(ConnectionProvider.class); + sequenceCollector = SequenceCollector.create(connectionProvider); + } + + public void visit(IssueCollector collector) { + super.visit(collector); + visitGenerators(collector); + } + + public void visitGenerators(IssueCollector collector) { + Iterator iter = iterateGenerators(); + + Set sequences = Collections.EMPTY_SET; + if(dialect.getSequenceSupport().supportsSequences()) { + sequences = sequenceCollector.readSequences(dialect.getQuerySequencesString()); + } + + // TODO: move this check into something that could check per class or collection instead. + while ( iter.hasNext() ) { + PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next(); + Object key = getGeneratorKey(generator); + if ( !isSequence(key, sequences) && !isTable( key ) ) { + collector.reportIssue( new Issue( "MISSING_ID_GENERATOR", Issue.HIGH_PRIORITY, "Missing sequence or table: " + key)); + } + } + + } + + private boolean isSequence(Object key, Set sequences) { + if(key instanceof String) { + if ( sequences.contains( key ) ) { + return true; + } + else { + String[] strings = StringHelper.split(".", (String) key); + if(strings.length==3) { + return sequences.contains(strings[2]); + } + else if (strings.length==2) { + return sequences.contains(strings[1]); + } + } + } + return false; + } + + private boolean isTable(Object key) throws HibernateException { + // BIG HACK - should probably utilize the table cache before going to the jdbcreader :( + if(key instanceof String) { + String[] strings = StringHelper.split(".", (String) key); + if(strings.length==1) { + tableSelector.clearSchemaSelections(); + tableSelector.addSchemaSelection( createSchemaSelection(null,null, strings[0]) ); + Collection
collection = readFromDatabase(); + return !collection.isEmpty(); + } + else if(strings.length==3) { + tableSelector.clearSchemaSelections(); + tableSelector.addSchemaSelection( createSchemaSelection(strings[0],strings[1], strings[2]) ); + Collection
collection = readFromDatabase(); + return !collection.isEmpty(); + } + else if (strings.length==2) { + tableSelector.clearSchemaSelections(); + tableSelector.addSchemaSelection( createSchemaSelection(null,strings[0], strings[1]) ); + Collection
collection = readFromDatabase(); + return !collection.isEmpty(); + } + } + return false; + } + + public void visit(Table table, IssueCollector pc) { + + if ( table.isPhysicalTable() ) { + setSchemaSelection( table ); + + Collection
collection = readFromDatabase(); + + if ( collection.isEmpty() ) { + pc.reportIssue( new Issue( "SCHEMA_TABLE_MISSING", + Issue.HIGH_PRIORITY, "Missing table " + + TableNameQualifier.qualify( table.getCatalog(), table + .getSchema(), table.getName() ) ) ); + } + else if ( collection.size() > 1 ) { + pc.reportIssue( new Issue( "SCHEMA_TABLE_MISSING", + Issue.NORMAL_PRIORITY, "Found " + + collection.size() + + " tables for " + + TableNameQualifier.qualify( table.getCatalog(), table + .getSchema(), table.getName() ) ) ); + } + else { + currentDbTable = collection.iterator().next(); + visitColumns(table,pc); + } + } + } + + String table(Table t) { + return TableNameQualifier.qualify( t.getCatalog(), t.getSchema(), t.getName() ); + } + + public void visit( + Table table, + Column col, + IssueCollector pc) { + if ( currentDbTable == null ) { + return; + } + + Column dbColumn = currentDbTable + .getColumn( new Column( col.getName() ) ); + + if ( dbColumn == null ) { + pc.reportIssue( new Issue( "SCHEMA_COLUMN_MISSING", + Issue.HIGH_PRIORITY, table(table) + " is missing column: " + col.getName() ) ); + } + else { + //TODO: this needs to be able to know if a type is truly compatible or not. Right now it requires an exact match. + //String sqlType = col.getSqlType( dialect, mapping ); + int dbTypeCode = dbColumn.getSqlTypeCode(); + int modelTypeCode = col + .getSqlTypeCode( mapping ); + // TODO: sqltype name string + if ( !(dbTypeCode == modelTypeCode ) ) { + pc.reportIssue( new Issue( "SCHEMA_COLUMN_TYPE_MISMATCH", + Issue.NORMAL_PRIORITY, table(table) + " has a wrong column type for " + + col.getName() + ", expected: " + + JdbcToHibernateTypeHelper.getJDBCTypeName(modelTypeCode) + " but was " + JdbcToHibernateTypeHelper.getJDBCTypeName(dbTypeCode) + " in db") ); + } + } + } + + private void setSchemaSelection(Table table) { + tableSelector.clearSchemaSelections(); + tableSelector.addSchemaSelection( createSchemaSelection( + table.getCatalog(), + table.getSchema(), + table.getName() ) ); + } + + /** + * @return iterator over all the IdentifierGenerator's found in the entitymodel and return a list of unique IdentifierGenerators + */ + private Iterator iterateGenerators() throws MappingException { + + TreeMap generators = + new TreeMap<>(); + + for ( PersistentClass pc : getMetadata().getEntityBindings() ) { + if ( !pc.isInherited() ) { + + Generator ig = pc.getIdentifier() + .createGenerator( + dialect, + (RootClass) pc + ); + + if ( ig instanceof PersistentIdentifierGenerator ) { + generators.put( getGeneratorKey( (PersistentIdentifierGenerator) ig ), ig ); + } + + } + } + + for ( org.hibernate.mapping.Collection collection : getMetadata().getCollectionBindings() ) { + if ( collection.isIdentified() ) { + + Generator ig = ((IdentifierCollection) collection).getIdentifier().createGenerator( + dialect, + null + ); + + if ( ig instanceof PersistentIdentifierGenerator ) { + generators.put( (getGeneratorKey( (PersistentIdentifierGenerator) ig )), ig ); + } + + } + } + + return generators.values().iterator(); + } + + private Collection
readFromDatabase() { + RevengMetadataCollector revengMetadataCollector = new RevengMetadataCollector(); + reader.readDatabaseSchema(revengMetadataCollector); + return revengMetadataCollector.getTables(); + } + + private SchemaSelection createSchemaSelection(String matchCatalog, String matchSchema, String matchTable) { + return new SchemaSelection() { + @Override + public String getMatchCatalog() { + return matchCatalog; + } + @Override + public String getMatchSchema() { + return matchSchema; + } + @Override + public String getMatchTable() { + return matchTable; + } + + }; + } + + private String getGeneratorKey(PersistentIdentifierGenerator ig) { + String result = null; + if (ig instanceof SequenceStyleGenerator) { + result = getKeyForSequenceStyleGenerator((SequenceStyleGenerator)ig); + } + else if (ig instanceof TableGenerator) { + result = getKeyForTableGenerator((TableGenerator)ig); + } + return result; + } + + private String getKeyForSequenceStyleGenerator(SequenceStyleGenerator ig) { + return ig.getDatabaseStructure().getPhysicalName().render(); + } + + private String getKeyForTableGenerator(TableGenerator ig) { + return ig.getTableName(); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/lint/SequenceCollector.java b/orm/src/main/java/org/hibernate/tool/internal/export/lint/SequenceCollector.java index 2a09504d1b..d765f14ad6 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/lint/SequenceCollector.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/lint/SequenceCollector.java @@ -27,51 +27,45 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; public class SequenceCollector { - - public static SequenceCollector create(ConnectionProvider provider) { - return new SequenceCollector(provider); - } - - final private ConnectionProvider provider; - - private SequenceCollector(ConnectionProvider provider) { - this.provider = provider; - } - public Set readSequences(String sql) { - Set sequences = new HashSet(); - if (sql != null) { - Connection connection = null; - try { + public static SequenceCollector create(ConnectionProvider provider) { + return new SequenceCollector(provider); + } - connection = provider.getConnection(); - Statement statement = null; - ResultSet rs = null; - try { - statement = connection.createStatement(); - rs = statement.executeQuery(sql); - while (rs.next()) { - sequences.add(rs.getString("SEQUENCE_NAME").toLowerCase().trim()); - } - } finally { - if (rs != null) - rs.close(); - if (statement != null) - statement.close(); - } + final private ConnectionProvider provider; - } catch (SQLException e) { - throw new RuntimeException("Problem while closing connection", e); - } finally { - if (connection != null) - try { - provider.closeConnection(connection); - } catch (SQLException e) { - throw new RuntimeException("Problem while closing connection", e); - } - } - } - return sequences; - } + private SequenceCollector(ConnectionProvider provider) { + this.provider = provider; + } + + public Set readSequences(String sql) { + Set sequences = new HashSet<>(); + if (sql != null) { + Connection connection = null; + try { + connection = provider.getConnection(); + try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery( sql )) { + while ( rs.next() ) { + sequences.add( rs.getString( "SEQUENCE_NAME" ).toLowerCase().trim() ); + } + } + + } + catch (SQLException e) { + throw new RuntimeException("Problem while closing connection", e); + } + finally { + if (connection != null) { + try { + provider.closeConnection( connection ); + } + catch (SQLException e) { + throw new RuntimeException( "Problem while closing connection", e ); + } + } + } + } + return sequences; + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/query/QueryExporter.java b/orm/src/main/java/org/hibernate/tool/internal/export/query/QueryExporter.java index 9676e263cf..731df72aee 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/query/QueryExporter.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/query/QueryExporter.java @@ -21,7 +21,6 @@ import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; -import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; @@ -36,70 +35,72 @@ **/ public class QueryExporter extends AbstractExporter { - public void doStart() { - Session session = null; - SessionFactory sessionFactory = null; - Transaction transaction = null; - try { - sessionFactory = buildMetadata().buildSessionFactory(); - session = sessionFactory.openSession(); - transaction = session.beginTransaction(); - for (Iterator iter = getQueryList().iterator(); iter.hasNext();) { - String query = (String) iter.next(); - - List list = session.createQuery(query, null).getResultList(); - - if(getFileName()!=null) { - PrintWriter pw = null; - try { - File file = new File( getOutputDirectory(), getFileName() ); - getTemplateHelper().ensureExistence( file ); - pw = new PrintWriter( new FileWriter( file, true ) ); - getArtifactCollector().addFile( file, "query-output" ); - - for (Iterator iter1 = list.iterator(); iter1.hasNext();) { - Object element = iter1.next(); - pw.println(element); - } - - } - catch (IOException e) { - throw new RuntimeException("Could not write query output",e); - } finally { - if(pw!=null) { - pw.flush(); - pw.close(); - } - } - } - } - transaction.commit(); - } catch(HibernateException he) { - if(transaction!=null) { - transaction.rollback(); - } - throw new RuntimeException("Error occured while trying to execute query", he); - } finally { - if(session!=null) { - session.close(); - } - if(sessionFactory!=null) { - sessionFactory.close(); - } - - } - } + public void doStart() { + Session session = null; + SessionFactory sessionFactory = null; + Transaction transaction = null; + try { + sessionFactory = buildMetadata().buildSessionFactory(); + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + for ( Object o : getQueryList() ) { + String query = (String) o; - private String getFileName() { - return (String)getProperties().get(OUTPUT_FILE_NAME); - } - - private List getQueryList() { - return (List)getProperties().get(QUERY_LIST); - } + List list = session.createQuery( query, null ).getResultList(); - public void setQueries(List queryStrings) { - getProperties().put(QUERY_LIST, queryStrings); - } + if ( getFileName() != null ) { + PrintWriter pw = null; + try { + File file = new File( getOutputDirectory(), getFileName() ); + getTemplateHelper().ensureExistence( file ); + pw = new PrintWriter( new FileWriter( file, true ) ); + getArtifactCollector().addFile( file, "query-output" ); + + for ( Object element : list ) { + pw.println( element ); + } + + } + catch (IOException e) { + throw new RuntimeException( "Could not write query output", e ); + } + finally { + if ( pw != null ) { + pw.flush(); + pw.close(); + } + } + } + } + transaction.commit(); + } + catch(HibernateException he) { + if(transaction!=null) { + transaction.rollback(); + } + throw new RuntimeException("Error occured while trying to execute query", he); + } + finally { + if(session!=null) { + session.close(); + } + if(sessionFactory!=null) { + sessionFactory.close(); + } + + } + } + + private String getFileName() { + return (String)getProperties().get(OUTPUT_FILE_NAME); + } + + private List getQueryList() { + return (List)getProperties().get(QUERY_LIST); + } + + public void setQueries(List queryStrings) { + getProperties().put(QUERY_LIST, queryStrings); + } }