diff --git a/build-logic/docs-core/src/main/groovy/org/grails/doc/gradle/FixGroovydocLinksTask.groovy b/build-logic/docs-core/src/main/groovy/org/grails/doc/gradle/FixGroovydocLinksTask.groovy new file mode 100644 index 00000000000..714419b84bf --- /dev/null +++ b/build-logic/docs-core/src/main/groovy/org/grails/doc/gradle/FixGroovydocLinksTask.groovy @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.doc.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.tasks.InputDirectory +import org.gradle.api.tasks.TaskAction +import java.nio.file.* +import java.util.regex.Matcher +import java.util.regex.Pattern + +/** + * A task that repairs malformed navigation links in generated Groovydocs. + * Specifically targets 'phantom' links and relative path issues in navigation files + * like overview-summary.html, deprecated-list.html, and help-doc.html. + */ +abstract class FixGroovydocLinksTask extends DefaultTask { + + @InputDirectory + abstract DirectoryProperty getApiDocsDir() + + @TaskAction + void fixLinks() { + File apiDir = apiDocsDir.get().asFile + if (!apiDir.exists()) { + logger.warn "API documentation directory does not exist: ${apiDir.absolutePath}" + return + } + + // Patterns common to Groovydoc navigation failures + Map replacements = [ + (Pattern.compile(/href='([^']+?)\/deprecated-list\.html'/)): "href='deprecated-list.html'", + (Pattern.compile(/href='([^']+?)\/help-doc\.html'/)): "href='help-doc.html'", + (Pattern.compile(/href='([^']+?)\/index-all\.html'/)): "href='index-all.html'", + (Pattern.compile(/href='([^']+?)\/overview-summary\.html'/)): "href='overview-summary.html'" + ] + + apiDir.eachFileRecurse { File file -> + if (file.name.endsWith(".html")) { + String content = file.text + boolean changed = false + + replacements.each { pattern, replacement -> + Matcher matcher = pattern.matcher(content) + if (matcher.find()) { + content = matcher.replaceAll(replacement) + changed = true + } + } + + // Fix specific inner class path issues like Query/Order.Direction.html -> Query.Order.Direction.html + // We only do this if the file actually exists + Pattern innerClassPattern = Pattern.compile(/href='([^']+?)\/([A-Z][A-Za-z0-9_]*?)\/([A-Z][A-Za-z0-9_.]*?\.html)'/) + Matcher innerMatcher = innerClassPattern.matcher(content) + while (innerMatcher.find()) { + String relPath = innerMatcher.group(1) + String outer = innerMatcher.group(2) + String inner = innerMatcher.group(3) + + Path currentPath = file.toPath().parent + Path targetPath = currentPath.resolve(relPath).resolve("${outer}.${inner}").normalize() + + if (Files.exists(targetPath)) { + String newHref = "href='${relPath}/${outer}.${inner}'" + content = content.replace(innerMatcher.group(0), newHref) + changed = true + } + } + + if (changed) { + file.text = content + } + } + } + + logger.lifecycle "Groovydoc link repair completed for ${apiDir.absolutePath}" + } +} diff --git a/gradle/docs-dependencies.gradle b/gradle/docs-dependencies.gradle index fd33607c98f..a032a7cc43d 100644 --- a/gradle/docs-dependencies.gradle +++ b/gradle/docs-dependencies.gradle @@ -31,16 +31,10 @@ dependencies { } String resolveProjectVersion(String artifact) { - String version = configurations.runtimeClasspath - .resolvedConfiguration - .resolvedArtifacts - .find { - it.moduleVersion.id.name == artifact - }?.moduleVersion?.id?.version - if (!version) { - return null + def component = configurations.runtimeClasspath.incoming.resolutionResult.allComponents.find { + it.moduleVersion?.name == artifact } - version + return component?.moduleVersion?.version } def configureGroovyDoc = tasks.register('configureGroovyDoc') { @@ -56,12 +50,35 @@ def configureGroovyDoc = tasks.register('configureGroovyDoc') { } def springVersion = resolveProjectVersion('spring-core') if (springVersion) { - links << [packages: 'org.springframework.core.', href: "https://docs.spring.io/spring-framework/docs/${springVersion}/javadoc-api/"] + links << [packages: 'org.springframework.', href: "https://docs.spring.io/spring-framework/docs/${springVersion}/javadoc-api/"] } def springBootVersion = resolveProjectVersion('spring-boot') if (springBootVersion) { links << [packages: 'org.springframework.boot.', href: "https://docs.spring.io/spring-boot/docs/${springBootVersion}/api/"] } + def hibernateVersion = resolveProjectVersion('hibernate-core') + if (hibernateVersion) { + def shortVersion = hibernateVersion.split('\\.').take(2).join('.') + links << [packages: 'org.hibernate.', href: "https://docs.jboss.org/hibernate/orm/${shortVersion}/javadocs/"] + } + def jakartaValidationVersion = resolveProjectVersion('jakarta.validation-api') + if (jakartaValidationVersion) { + links << [packages: 'jakarta.validation.', href: "https://jakarta.ee/specifications/bean-validation/3.0/apidocs/"] + } + def jakartaPersistenceVersion = resolveProjectVersion('jakarta.persistence-api') + if (jakartaPersistenceVersion) { + links << [packages: 'jakarta.persistence.', href: "https://jakarta.ee/specifications/persistence/3.1/apidocs/"] + } + def jakartaServletVersion = resolveProjectVersion('jakarta.servlet-api') + if (jakartaServletVersion) { + links << [packages: 'jakarta.servlet.', href: "https://jakarta.ee/specifications/platform/10/apidocs/"] + } + links << [packages: 'org.grails.datastore.', href: "https://gorm.grails.org/latest/api/"] + links << [packages: 'grails.gorm.', href: "https://gorm.grails.org/latest/api/"] + links << [packages: 'org.grails.gorm.', href: "https://gorm.grails.org/latest/api/"] + links << [packages: 'groovy.', href: "https://docs.groovy-lang.org/latest/html/gapi/"] + links << [packages: 'org.apache.groovy.', href: "https://docs.groovy-lang.org/latest/html/gapi/"] + links << [packages: 'org.codehaus.groovy.', href: "https://docs.groovy-lang.org/latest/html/gapi/"] if (it.ext.has('groovydocLinks')) { links.addAll(it.ext.groovydocLinks as List>) } diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java index 1c5715728c5..74b12cf5085 100644 --- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java +++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java @@ -121,8 +121,10 @@ import org.grails.orm.hibernate.access.TraitPropertyAccessStrategy; /** - * Handles the binding Grails domain classes and properties to the Hibernate runtime meta model. - * Based on the HbmBinder code in Hibernate core and influenced by AnnotationsBinder. + * Handles the binding Grails domain classes and properties to the Hibernate + * runtime meta model. + * Based on the HbmBinder code in Hibernate core and influenced by + * AnnotationsBinder. * * @author Graeme Rocher * @since 0.1 @@ -147,8 +149,10 @@ public class GrailsDomainBinder implements MetadataContributor { protected static final Logger LOG = LoggerFactory.getLogger(GrailsDomainBinder.class); public static final String SEQUENCE_KEY = "sequence"; /** - * Overrideable naming strategy. Defaults to ImprovedNamingStrategy but can - * be configured in DataSource.groovy via hibernate.naming_strategy = .... + * Overrideable naming strategy. Defaults to ImprovedNamingStrategy + * but can + * be configured in DataSource.groovy via + * hibernate.naming_strategy = .... */ public static Map NAMING_STRATEGIES = new HashMap<>(); @@ -157,7 +161,8 @@ public class GrailsDomainBinder implements MetadataContributor { } protected final CollectionType CT = new CollectionType(null, this) { - public Collection create(ToMany property, PersistentClass owner, String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + public Collection create(ToMany property, PersistentClass owner, String path, + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { return null; } }; @@ -183,7 +188,9 @@ public GrailsDomainBinder( } /** - * The default mapping defined by {@link org.grails.datastore.mapping.config.Settings#SETTING_DEFAULT_MAPPING} + * The default mapping defined by + * {@link org.grails.datastore.mapping.config.Settings#SETTING_DEFAULT_MAPPING} + * * @param defaultMapping The default mapping */ public void setDefaultMapping(Closure defaultMapping) { @@ -206,13 +213,13 @@ public void contribute(InFlightMetadataCollector metadataCollector, IndexView ja this.metadataBuildingContext = new MetadataBuildingContextRootImpl( metadataCollector.getBootstrapContext(), options, - metadataCollector - ); + metadataCollector); java.util.Collection persistentEntities = hibernateMappingContext.getPersistentEntities(); for (PersistentEntity persistentEntity : persistentEntities) { if (!persistentEntity.getJavaClass().isAnnotationPresent(Entity.class)) { - if (ConnectionSourcesSupport.usesConnectionSource(persistentEntity, dataSourceName) && persistentEntity.isRoot()) { + if (ConnectionSourcesSupport.usesConnectionSource(persistentEntity, dataSourceName) + && persistentEntity.isRoot()) { bindRoot((HibernatePersistentEntity) persistentEntity, metadataCollector, sessionFactoryName); } } @@ -220,13 +227,19 @@ public void contribute(InFlightMetadataCollector metadataCollector, IndexView ja } /** - * Override the default naming strategy for the default datasource given a Class or a full class name. + * Override the default naming strategy for the default datasource given a Class + * or a full class name. + * * @param strategy the class or name - * @throws ClassNotFoundException When the class was not found for specified strategy - * @throws InstantiationException When an error occurred instantiating the strategy - * @throws IllegalAccessException When an error occurred instantiating the strategy + * @throws ClassNotFoundException When the class was not found for specified + * strategy + * @throws InstantiationException When an error occurred instantiating the + * strategy + * @throws IllegalAccessException When an error occurred instantiating the + * strategy */ - public static void configureNamingStrategy(final Object strategy) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + public static void configureNamingStrategy(final Object strategy) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { configureNamingStrategy(ConnectionSource.DEFAULT, strategy); } @@ -235,25 +248,27 @@ public static void configureNamingStrategy(final Object strategy) throws ClassNo * or an instance of a NamingStrategy. * * @param datasourceName the datasource name - * @param strategy the class, name, or instance - * @throws ClassNotFoundException When the class was not found for specified strategy - * @throws InstantiationException When an error occurred instantiating the strategy - * @throws IllegalAccessException When an error occurred instantiating the strategy + * @param strategy the class, name, or instance + * @throws ClassNotFoundException When the class was not found for specified + * strategy + * @throws InstantiationException When an error occurred instantiating the + * strategy + * @throws IllegalAccessException When an error occurred instantiating the + * strategy */ - public static void configureNamingStrategy(final String datasourceName, final Object strategy) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + public static void configureNamingStrategy(final String datasourceName, final Object strategy) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class namingStrategyClass = null; NamingStrategy namingStrategy; if (strategy instanceof Class) { namingStrategyClass = (Class) strategy; - } - else if (strategy instanceof CharSequence) { + } else if (strategy instanceof CharSequence) { namingStrategyClass = Thread.currentThread().getContextClassLoader().loadClass(strategy.toString()); } if (namingStrategyClass == null) { namingStrategy = (NamingStrategy) strategy; - } - else { + } else { namingStrategy = (NamingStrategy) namingStrategyClass.newInstance(); } @@ -261,7 +276,7 @@ else if (strategy instanceof CharSequence) { } protected void bindMapSecondPass(ToMany property, InFlightMetadataCollector mappings, - Map persistentClasses, org.hibernate.mapping.Map map, String sessionFactoryBeanName) { + Map persistentClasses, org.hibernate.mapping.Map map, String sessionFactoryBeanName) { bindCollectionSecondPass(property, mappings, persistentClasses, map, sessionFactoryBeanName); SimpleValue value = new SimpleValue(metadataBuildingContext, map.getCollectionTable()); @@ -270,7 +285,8 @@ protected void bindMapSecondPass(ToMany property, InFlightMetadataCollector mapp getIndexColumnName(property, sessionFactoryBeanName), mappings); PropertyConfig pc = getPropertyConfig(property); if (pc != null && pc.getIndexColumn() != null) { - bindColumnConfigToColumn(property, getColumnForSimpleValue(value), getSingleColumnConfig(pc.getIndexColumn())); + bindColumnConfigToColumn(property, getColumnForSimpleValue(value), + getSingleColumnConfig(pc.getIndexColumn())); } if (!value.isTypeSpecified()) { @@ -278,7 +294,8 @@ protected void bindMapSecondPass(ToMany property, InFlightMetadataCollector mapp } map.setIndex(value); - if (!(property instanceof org.grails.datastore.mapping.model.types.OneToMany) && !(property instanceof ManyToMany)) { + if (!(property instanceof org.grails.datastore.mapping.model.types.OneToMany) + && !(property instanceof ManyToMany)) { SimpleValue elt = new SimpleValue(metadataBuildingContext, map.getCollectionTable()); map.setElement(elt); @@ -313,7 +330,7 @@ protected ColumnConfig getSingleColumnConfig(PropertyConfig propertyConfig) { } protected void bindListSecondPass(ToMany property, InFlightMetadataCollector mappings, - Map persistentClasses, org.hibernate.mapping.List list, String sessionFactoryBeanName) { + Map persistentClasses, org.hibernate.mapping.List list, String sessionFactoryBeanName) { bindCollectionSecondPass(property, mappings, persistentClasses, list, sessionFactoryBeanName); @@ -357,7 +374,8 @@ protected void bindListSecondPass(ToMany property, InFlightMetadataCollector map Backref prop = new Backref(); final PersistentEntity owner = property.getOwner(); prop.setEntityName(owner.getName()); - prop.setName(UNDERSCORE + addUnderscore(owner.getJavaClass().getSimpleName(), property.getName()) + "Backref"); + prop.setName(UNDERSCORE + addUnderscore(owner.getJavaClass().getSimpleName(), property.getName()) + + "Backref"); prop.setSelectable(false); prop.setUpdateable(false); if (isManyToMany) { @@ -393,7 +411,7 @@ protected void bindListSecondPass(ToMany property, InFlightMetadataCollector map } protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollector mappings, - Map persistentClasses, Collection collection, String sessionFactoryBeanName) { + Map persistentClasses, Collection collection, String sessionFactoryBeanName) { PersistentClass associatedClass = null; @@ -407,9 +425,11 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect PersistentEntity referenced = property.getAssociatedEntity(); if (propConfig != null && StringUtils.hasText(propConfig.getSort())) { - if (!property.isBidirectional() && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) { - throw new DatastoreConfigurationException("Default sort for associations [" + property.getOwner().getName() + "->" + property.getName() + - "] are not supported with unidirectional one to many relationships."); + if (!property.isBidirectional() + && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) { + throw new DatastoreConfigurationException( + "Default sort for associations [" + property.getOwner().getName() + "->" + property.getName() + + "] are not supported with unidirectional one to many relationships."); } if (referenced != null) { PersistentProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort()); @@ -418,8 +438,9 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); if (associatedClass != null) { - collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(), - propConfig.getOrder() != null ? propConfig.getOrder() : "asc")); + collection.setOrderBy( + buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(), + propConfig.getOrder() != null ? propConfig.getOrder() : "asc")); } } } @@ -446,7 +467,7 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect } } } - //NOTE: this will build the set for the in clause if it has sublcasses + // NOTE: this will build the set for the in clause if it has sublcasses Set discSet = buildDiscriminatorSet((HibernatePersistentEntity) referenced); String inclause = String.join(",", discSet); @@ -459,7 +480,8 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect associatedClass = (PersistentClass) persistentClasses.get(associatedClassName); // if there is no persistent class for the association throw exception if (associatedClass == null) { - throw new MappingException("Association references unmapped class: " + oneToMany.getReferencedEntityName()); + throw new MappingException( + "Association references unmapped class: " + oneToMany.getReferencedEntityName()); } oneToMany.setAssociatedClass(associatedClass); @@ -475,9 +497,11 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect String filterCondition = getMultiTenantFilterCondition(sessionFactoryBeanName, referenced); if (filterCondition != null) { if (isUnidirectionalOneToMany(property)) { - collection.addManyToManyFilter(GormProperties.TENANT_IDENTITY, filterCondition, true, Collections.emptyMap(), Collections.emptyMap()); + collection.addManyToManyFilter(GormProperties.TENANT_IDENTITY, filterCondition, true, + Collections.emptyMap(), Collections.emptyMap()); } else { - collection.addFilter(GormProperties.TENANT_IDENTITY, filterCondition, true, Collections.emptyMap(), Collections.emptyMap()); + collection.addFilter(GormProperties.TENANT_IDENTITY, filterCondition, true, Collections.emptyMap(), + Collections.emptyMap()); } } } @@ -492,7 +516,8 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect // link a bidirectional relationship if (property.isBidirectional()) { Association otherSide = property.getInverseSide(); - if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne) && shouldBindCollectionWithForeignKey(property)) { + if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne) + && shouldBindCollectionWithForeignKey(property)) { linkBidirectionalOneToMany(collection, associatedClass, key, otherSide); } else if ((otherSide instanceof ManyToMany) || Map.class.isAssignableFrom(property.getType())) { bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName); @@ -520,7 +545,9 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect if (property.isBidirectional()) { if (LOG.isDebugEnabled()) - LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + " as ManyToOne"); + LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "." + + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + + " as ManyToOne"); ManyToOne element = new ManyToOne(metadataBuildingContext, collection.getCollectionTable()); bindManyToMany((Association) otherSide, element, mappings, sessionFactoryBeanName); collection.setElement(element); @@ -536,9 +563,11 @@ protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollect } else if (isUnidirectionalOneToMany(property)) { // for non-inverse one-to-many, with a not-null fk, add a backref! - // there are problems with list and map mappings and join columns relating to duplicate key constraints + // there are problems with list and map mappings and join columns relating to + // duplicate key constraints // TODO change this when HHH-1268 is resolved - bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings, collection); + bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings, + collection); } } @@ -547,62 +576,57 @@ private String getMultiTenantFilterCondition(String sessionFactoryBeanName, Pers if (tenantId != null) { String defaultColumnName = getDefaultColumnName(tenantId, sessionFactoryBeanName); return ":tenantId = " + defaultColumnName; - } - else { + } else { return null; } } @SuppressWarnings("unchecked") - protected String buildOrderByClause(String hqlOrderBy, PersistentClass associatedClass, String role, String defaultOrder) { + protected String buildOrderByClause(String hqlOrderBy, PersistentClass associatedClass, String role, + String defaultOrder) { String orderByString = null; if (hqlOrderBy != null) { List properties = new ArrayList<>(); List ordering = new ArrayList<>(); StringBuilder orderByBuffer = new StringBuilder(); if (hqlOrderBy.length() == 0) { - //order by id + // order by id Iterator it = associatedClass.getIdentifier().getColumnIterator(); while (it.hasNext()) { Selectable col = (Selectable) it.next(); orderByBuffer.append(col.getText()).append(" asc").append(", "); } - } - else { + } else { StringTokenizer st = new StringTokenizer(hqlOrderBy, " ,", false); String currentOrdering = defaultOrder; - //FIXME make this code decent + // FIXME make this code decent while (st.hasMoreTokens()) { String token = st.nextToken(); if (isNonPropertyToken(token)) { if (currentOrdering != null) { throw new DatastoreConfigurationException( "Error while parsing sort clause: " + hqlOrderBy + - " (" + role + ")" - ); + " (" + role + ")"); } currentOrdering = token; - } - else { - //Add ordering of the previous + } else { + // Add ordering of the previous if (currentOrdering == null) { - //default ordering + // default ordering ordering.add("asc"); - } - else { + } else { ordering.add(currentOrdering); currentOrdering = null; } properties.add(token); } } - ordering.remove(0); //first one is the algorithm starter + ordering.remove(0); // first one is the algorithm starter // add last one ordering if (currentOrdering == null) { - //default ordering + // default ordering ordering.add(defaultOrder); - } - else { + } else { ordering.add(currentOrdering); currentOrdering = null; } @@ -613,8 +637,7 @@ protected String buildOrderByClause(String hqlOrderBy, PersistentClass associate if (p == null) { throw new DatastoreConfigurationException( "property from sort clause not found: " + - associatedClass.getEntityName() + "." + property - ); + associatedClass.getEntityName() + "." + property); } PersistentClass pc = p.getPersistentClass(); String table; @@ -624,7 +647,7 @@ protected String buildOrderByClause(String hqlOrderBy, PersistentClass associate else if (pc == associatedClass || (associatedClass instanceof SingleTableSubclass && - pc.getMappedClass().isAssignableFrom(associatedClass.getMappedClass()))) { + pc.getMappedClass().isAssignableFrom(associatedClass.getMappedClass()))) { table = ""; } else { table = pc.getTable().getQuotedName() + "."; @@ -648,10 +671,14 @@ else if (pc == associatedClass || } protected boolean isNonPropertyToken(String token) { - if (" ".equals(token)) return true; - if (",".equals(token)) return true; - if (token.equalsIgnoreCase("desc")) return true; - if (token.equalsIgnoreCase("asc")) return true; + if (" ".equals(token)) + return true; + if (",".equals(token)) + return true; + if (token.equalsIgnoreCase("desc")) + return true; + if (token.equalsIgnoreCase("asc")) + return true; return false; } @@ -670,12 +697,14 @@ protected Set buildDiscriminatorSet(HibernatePersistentEntity domainClas String quote = "'"; if (rootMapping != null && rootMapping.getDatasources() != null) { DiscriminatorConfig discriminatorConfig = rootMapping.getDiscriminator(); - if (discriminatorConfig != null && discriminatorConfig.getType() != null && !discriminatorConfig.getType().equals("string")) + if (discriminatorConfig != null && discriminatorConfig.getType() != null + && !discriminatorConfig.getType().equals("string")) quote = ""; } theSet.add(quote + discriminator + quote); - final java.util.Collection childEntities = domainClass.getMappingContext().getDirectChildEntities(domainClass); + final java.util.Collection childEntities = domainClass.getMappingContext() + .getDirectChildEntities(domainClass); for (PersistentEntity subClass : childEntities) { theSet.addAll(buildDiscriminatorSet((HibernatePersistentEntity) subClass)); } @@ -683,11 +712,13 @@ protected Set buildDiscriminatorSet(HibernatePersistentEntity domainClas } protected Mapping getRootMapping(PersistentEntity referenced) { - if (referenced == null) return null; + if (referenced == null) + return null; Class current = referenced.getJavaClass(); while (true) { Class superClass = current.getSuperclass(); - if (Object.class.equals(superClass)) break; + if (Object.class.equals(superClass)) + break; current = superClass; } @@ -699,7 +730,8 @@ protected boolean isBidirectionalOneToManyMap(Association property) { } protected void bindCollectionWithJoinTable(ToMany property, - InFlightMetadataCollector mappings, Collection collection, PropertyConfig config, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, Collection collection, PropertyConfig config, + String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); @@ -707,8 +739,7 @@ protected void bindCollectionWithJoinTable(ToMany property, final boolean isBasicCollectionType = property instanceof Basic; if (isBasicCollectionType) { element = new SimpleValue(metadataBuildingContext, collection.getCollectionTable()); - } - else { + } else { // for a normal unidirectional one-to-many we use a join column element = new ManyToOne(metadataBuildingContext, collection.getCollectionTable()); bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element); @@ -724,17 +755,15 @@ protected void bindCollectionWithJoinTable(ToMany property, final boolean isEnum = referencedType.isEnum(); if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); - } - else { - columnName = isEnum ? namingStrategy.propertyToColumnName(className) : - addUnderscore(namingStrategy.propertyToColumnName(property.getName()), + } else { + columnName = isEnum ? namingStrategy.propertyToColumnName(className) + : addUnderscore(namingStrategy.propertyToColumnName(property.getName()), namingStrategy.propertyToColumnName(className)); } if (isEnum) { bindEnumType(property, referencedType, element, columnName); - } - else { + } else { String typeName = getTypeName(property, config, getMapping(property.getOwner())); if (typeName == null) { @@ -745,12 +774,14 @@ protected void bindCollectionWithJoinTable(ToMany property, } if (typeName == null) { String domainName = property.getOwner().getName(); - throw new MappingException("Missing type or column for column[" + columnName + "] on domain[" + domainName + "] referencing[" + className + "]"); + throw new MappingException("Missing type or column for column[" + columnName + "] on domain[" + + domainName + "] referencing[" + className + "]"); } bindSimpleValue(typeName, element, true, columnName, mappings); if (hasJoinColumnMapping) { - bindColumnConfigToColumn(property, getColumnForSimpleValue(element), config.getJoinTable().getColumn()); + bindColumnConfigToColumn(property, getColumnForSimpleValue(element), + config.getJoinTable().getColumn()); } } } else { @@ -761,13 +792,12 @@ protected void bindCollectionWithJoinTable(ToMany property, CompositeIdentity ci = (CompositeIdentity) m.getIdentity(); bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH, sessionFactoryBeanName); - } - else { + } else { if (hasJoinColumnMapping) { columnName = config.getJoinTable().getColumn().getName(); - } - else { - columnName = namingStrategy.propertyToColumnName(NameUtils.decapitalize(domainClass.getName())) + FOREIGN_KEY_SUFFIX; + } else { + columnName = namingStrategy.propertyToColumnName(NameUtils.decapitalize(domainClass.getName())) + + FOREIGN_KEY_SUFFIX; } bindSimpleValue("long", element, true, columnName, mappings); @@ -808,7 +838,8 @@ protected String getTypeName(PersistentProperty property, PropertyConfig config, } protected void bindColumnConfigToColumn(PersistentProperty property, Column column, ColumnConfig columnConfig) { - final PropertyConfig mappedForm = property != null ? (PropertyConfig) property.getMapping().getMappedForm() : null; + final PropertyConfig mappedForm = property != null ? (PropertyConfig) property.getMapping().getMappedForm() + : null; boolean allowUnique = mappedForm != null && !mappedForm.isUniqueWithinGroup(); if (columnConfig == null) { @@ -844,7 +875,7 @@ protected boolean shouldCollectionBindWithJoinColumn(ToMany property) { } /** - * @param property The property to bind + * @param property The property to bind * @param manyToOne The inverse side */ protected void bindUnidirectionalOneToManyInverseValues(ToMany property, ManyToOne manyToOne) { @@ -895,19 +926,20 @@ public PropertyConfig getPropertyConfig(PersistentProperty property) { * @return true if it is unidirectional and a one-to-many */ protected boolean isUnidirectionalOneToMany(PersistentProperty property) { - return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && !((Association) property).isBidirectional()); + return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) + && !((Association) property).isBidirectional()); } /** * Binds the primary key value column * - * @param property The property - * @param key The key - * @param mappings The mappings + * @param property The property + * @param key The key + * @param mappings The mappings * @param sessionFactoryBeanName The name of the session factory */ protected void bindDependentKeyValue(PersistentProperty property, DependantValue key, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] binding [" + property.getName() + "] with dependant key"); @@ -919,15 +951,16 @@ protected void bindDependentKeyValue(PersistentProperty property, DependantValue if ((shouldCollectionBindWithJoinColumn((ToMany) property) && hasCompositeIdentifier) || (hasCompositeIdentifier && (property instanceof ManyToMany))) { CompositeIdentity ci = (CompositeIdentity) mapping.getIdentity(); - bindCompositeIdentifierToManyToOne((Association) property, key, ci, refDomainClass, EMPTY_PATH, sessionFactoryBeanName); - } - else { + bindCompositeIdentifierToManyToOne((Association) property, key, ci, refDomainClass, EMPTY_PATH, + sessionFactoryBeanName); + } else { bindSimpleValue(property, null, key, EMPTY_PATH, mappings, sessionFactoryBeanName); } } /** - * Creates the DependentValue object that forms a primary key reference for the collection. + * Creates the DependentValue object that forms a primary key reference for the + * collection. * * @param mappings * @param property The grails property @@ -936,7 +969,7 @@ protected void bindDependentKeyValue(PersistentProperty property, DependantValue * @return The DependantValue (key) */ protected DependantValue createPrimaryKeyValue(InFlightMetadataCollector mappings, PersistentProperty property, - Collection collection, Map persistentClasses) { + Collection collection, Map persistentClasses) { KeyValue keyValue; DependantValue key; String propertyRef = collection.getReferencedPropertyName(); @@ -948,7 +981,8 @@ protected DependantValue createPrimaryKeyValue(InFlightMetadataCollector mapping } if (LOG.isDebugEnabled()) - LOG.debug("[GrailsDomainBinder] creating dependant key value to table [" + keyValue.getTable().getName() + "]"); + LOG.debug("[GrailsDomainBinder] creating dependant key value to table [" + keyValue.getTable().getName() + + "]"); key = new DependantValue(metadataBuildingContext, collection.getCollectionTable(), keyValue); @@ -960,13 +994,15 @@ protected DependantValue createPrimaryKeyValue(InFlightMetadataCollector mapping } /** - * Binds a unidirectional one-to-many creating a psuedo back reference property in the process. + * Binds a unidirectional one-to-many creating a psuedo back reference property + * in the process. * * @param property * @param mappings * @param collection */ - protected void bindUnidirectionalOneToMany(org.grails.datastore.mapping.model.types.OneToMany property, InFlightMetadataCollector mappings, Collection collection) { + protected void bindUnidirectionalOneToMany(org.grails.datastore.mapping.model.types.OneToMany property, + InFlightMetadataCollector mappings, Collection collection) { Value v = collection.getElement(); v.createForeignKey(); String entityName; @@ -995,9 +1031,8 @@ protected void bindUnidirectionalOneToMany(org.grails.datastore.mapping.model.ty protected Property getProperty(PersistentClass associatedClass, String propertyName) throws MappingException { try { return associatedClass.getProperty(propertyName); - } - catch (MappingException e) { - //maybe it's squirreled away in a composite primary key + } catch (MappingException e) { + // maybe it's squirreled away in a composite primary key if (associatedClass.getKey() instanceof Component) { return ((Component) associatedClass.getKey()).getProperty(propertyName); } @@ -1006,17 +1041,20 @@ protected Property getProperty(PersistentClass associatedClass, String propertyN } /** - * Links a bidirectional one-to-many, configuring the inverse side and using a column copy to perform the link + * Links a bidirectional one-to-many, configuring the inverse side and using a + * column copy to perform the link * * @param collection The collection one-to-many * @param associatedClass The associated class * @param key The key * @param otherSide The other side of the relationship */ - protected void linkBidirectionalOneToMany(Collection collection, PersistentClass associatedClass, DependantValue key, PersistentProperty otherSide) { + protected void linkBidirectionalOneToMany(Collection collection, PersistentClass associatedClass, + DependantValue key, PersistentProperty otherSide) { collection.setInverse(true); - // Iterator mappedByColumns = associatedClass.getProperty(otherSide.getName()).getValue().getColumnIterator(); + // Iterator mappedByColumns = + // associatedClass.getProperty(otherSide.getName()).getValue().getColumnIterator(); Iterator mappedByColumns = getProperty(associatedClass, otherSide.getName()).getValue().getColumnIterator(); while (mappedByColumns.hasNext()) { Column column = (Column) mappedByColumns.next(); @@ -1046,7 +1084,7 @@ protected boolean isSorted(PersistentProperty property) { * @param mappings The mappings */ protected void bindManyToMany(Association property, ManyToOne element, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { bindManyToOne(property, element, EMPTY_PATH, mappings, sessionFactoryBeanName); element.setReferencedEntityName(property.getOwner().getName()); } @@ -1073,7 +1111,7 @@ protected void linkValueUsingAColumnCopy(PersistentProperty prop, Column column, * @param path */ protected void bindCollection(ToMany property, Collection collection, - PersistentClass owner, InFlightMetadataCollector mappings, String path, String sessionFactoryBeanName) { + PersistentClass owner, InFlightMetadataCollector mappings, String path, String sessionFactoryBeanName) { // set role String propertyName = getNameForPropertyAndPath(property, path); @@ -1084,11 +1122,9 @@ protected void bindCollection(ToMany property, Collection collection, final FetchMode fetchMode = pc.getFetchMode(); if (fetchMode == FetchMode.JOIN) { collection.setFetchMode(FetchMode.JOIN); - } - else if (pc.getFetchMode() != null) { + } else if (pc.getFetchMode() != null) { collection.setFetchMode(pc.getFetchMode()); - } - else { + } else { collection.setFetchMode(FetchMode.DEFAULT); } @@ -1114,16 +1150,15 @@ else if (pc.getFetchMode() != null) { // set up second pass if (collection instanceof org.hibernate.mapping.Set) { - mappings.addSecondPass(new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName)); - } - else if (collection instanceof org.hibernate.mapping.List) { + mappings.addSecondPass( + new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName)); + } else if (collection instanceof org.hibernate.mapping.List) { mappings.addSecondPass(new ListSecondPass(property, mappings, collection, sessionFactoryBeanName)); - } - else if (collection instanceof org.hibernate.mapping.Map) { + } else if (collection instanceof org.hibernate.mapping.Map) { mappings.addSecondPass(new MapSecondPass(property, mappings, collection, sessionFactoryBeanName)); - } - else { // Collection -> Bag - mappings.addSecondPass(new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName)); + } else { // Collection -> Bag + mappings.addSecondPass( + new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName)); } } @@ -1132,7 +1167,8 @@ else if (collection instanceof org.hibernate.mapping.Map) { * it is a unidirectional one-to-many that is. */ protected boolean shouldBindCollectionWithForeignKey(ToMany property) { - return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && property.isBidirectional() || + return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && property.isBidirectional() + || !shouldCollectionBindWithJoinColumn(property)) && !Map.class.isAssignableFrom(property.getType()) && !(property instanceof ManyToMany) && @@ -1147,14 +1183,15 @@ protected String getNameForPropertyAndPath(PersistentProperty property, String p } protected void bindCollectionTable(ToMany property, InFlightMetadataCollector mappings, - Collection collection, Table ownerTable, String sessionFactoryBeanName) { + Collection collection, Table ownerTable, String sessionFactoryBeanName) { String owningTableSchema = ownerTable.getSchema(); PropertyConfig config = getPropertyConfig(property); JoinTable jt = config != null ? config.getJoinTable() : null; NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); - String tableName = (jt != null && jt.getName() != null ? jt.getName() : namingStrategy.tableName(calculateTableForMany(property, sessionFactoryBeanName))); + String tableName = (jt != null && jt.getName() != null ? jt.getName() + : namingStrategy.tableName(calculateTableForMany(property, sessionFactoryBeanName))); String schemaName = getSchemaName(mappings); String catalogName = getCatalogName(mappings); if (jt != null) { @@ -1177,14 +1214,15 @@ protected void bindCollectionTable(ToMany property, InFlightMetadataCollector ma /** * Calculates the mapping table for a many-to-many. One side of - * the relationship has to "own" the relationship so that there is not a situation + * the relationship has to "own" the relationship so that there is not a + * situation * where you have two mapping tables for left_right and right_left */ protected String calculateTableForMany(ToMany property, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); String propertyColumnName = namingStrategy.propertyToColumnName(property.getName()); - //fix for GRAILS-5895 + // fix for GRAILS-5895 PropertyConfig config = getPropertyConfig(property); JoinTable jt = config != null ? config.getJoinTable() : null; boolean hasJoinTableMapping = jt != null && jt.getName() != null; @@ -1205,7 +1243,8 @@ protected String calculateTableForMany(ToMany property, String sessionFactoryBea } if (property.getAssociatedEntity() == null) { - throw new MappingException("Expected an entity to be associated with the association (" + property + ") and none was found. "); + throw new MappingException( + "Expected an entity to be associated with the association (" + property + ") and none was found. "); } String right = getTableName(property.getAssociatedEntity(), sessionFactoryBeanName); @@ -1217,7 +1256,8 @@ protected String calculateTableForMany(ToMany property, String sessionFactoryBea if (property.isOwningSide()) { return addUnderscore(left, propertyColumnName); } - return addUnderscore(right, namingStrategy.propertyToColumnName(((ManyToMany) property).getInversePropertyName())); + return addUnderscore(right, + namingStrategy.propertyToColumnName(((ManyToMany) property).getInversePropertyName())); } if (shouldCollectionBindWithJoinColumn(property)) { @@ -1269,9 +1309,8 @@ protected String getTableName(PersistentEntity domainClass, String sessionFactor } protected NamingStrategy getNamingStrategy(String sessionFactoryBeanName) { - String key = "sessionFactory".equals(sessionFactoryBeanName) ? - ConnectionSource.DEFAULT : - sessionFactoryBeanName.substring("sessionFactory_".length()); + String key = "sessionFactory".equals(sessionFactoryBeanName) ? ConnectionSource.DEFAULT + : sessionFactoryBeanName.substring("sessionFactory_".length()); NamingStrategy namingStrategy = NAMING_STRATEGIES.get(key); return namingStrategy != null ? namingStrategy : new ImprovedNamingStrategy(); } @@ -1279,14 +1318,15 @@ protected NamingStrategy getNamingStrategy(String sessionFactoryBeanName) { /** * Binds a Grails domain class to the Hibernate runtime meta model * - * @param entity The domain class to bind - * @param mappings The existing mappings - * @param sessionFactoryBeanName the session factory bean name - * @throws MappingException Thrown if the domain class uses inheritance which is not supported + * @param entity The domain class to bind + * @param mappings The existing mappings + * @param sessionFactoryBeanName the session factory bean name + * @throws MappingException Thrown if the domain class uses inheritance which is + * not supported */ public void bindClass(PersistentEntity entity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { - //if (domainClass.getClazz().getSuperclass() == Object.class) { + // if (domainClass.getClazz().getSuperclass() == Object.class) { if (entity.isRoot()) { bindRoot((HibernatePersistentEntity) entity, mappings, sessionFactoryBeanName); } @@ -1321,8 +1361,10 @@ public Mapping evaluateMapping(PersistentEntity domainClass, Closure defaultM } /** - * Checks for any custom cascading saves set up via the mapping DSL and records them within the persistent property. - * @param mapping The Mapping. + * Checks for any custom cascading saves set up via the mapping DSL and records + * them within the persistent property. + * + * @param mapping The Mapping. * @param persistentProperties The persistent properties of the domain class. */ protected void trackCustomCascadingSaves(Mapping mapping, Iterable persistentProperties) { @@ -1336,9 +1378,12 @@ protected void trackCustomCascadingSaves(Mapping mapping, Iterable theClass) { * @param persistentClass The persistant class * @param mappings Existing mappings */ - protected void bindClass(PersistentEntity domainClass, PersistentClass persistentClass, InFlightMetadataCollector mappings) { + protected void bindClass(PersistentEntity domainClass, PersistentClass persistentClass, + InFlightMetadataCollector mappings) { boolean autoImport = mappings.getMetadataBuildingOptions().getMappingDefaults().isAutoImportEnabled(); org.grails.datastore.mapping.config.Entity mappedForm = domainClass.getMapping().getMappedForm(); @@ -1426,11 +1473,12 @@ protected void bindClass(PersistentEntity domainClass, PersistentClass persisten * Binds a root class (one with no super classes) to the runtime meta model * based on the supplied Grails domain class * - * @param entity The Grails domain class - * @param mappings The Hibernate Mappings object - * @param sessionFactoryBeanName the session factory bean name + * @param entity The Grails domain class + * @param mappings The Hibernate Mappings object + * @param sessionFactoryBeanName the session factory bean name */ - public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector mappings, + String sessionFactoryBeanName) { if (mappings.getEntityBinding(entity.getName()) != null) { LOG.info("[GrailsDomainBinder] Class [" + entity.getName() + "] is already mapped, skipping.. "); return; @@ -1466,11 +1514,14 @@ public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector } /** - * Add a Hibernate filter for multitenancy if the persistent class is multitenant + * Add a Hibernate filter for multitenancy if the persistent class is + * multitenant * - * @param entity target persistent entity for get tenant information - * @param persistentClass persistent class for add the filter and get tenant property info - * @param mappings mappings to add the filter + * @param entity target persistent entity for get tenant + * information + * @param persistentClass persistent class for add the filter and get + * tenant property info + * @param mappings mappings to add the filter * @param sessionFactoryBeanName the session factory bean name */ protected void addMultiTenantFilterIfNecessary( @@ -1487,33 +1538,35 @@ protected void addMultiTenantFilterIfNecessary( filterCondition, true, Collections.emptyMap(), - Collections.emptyMap() - ); + Collections.emptyMap()); mappings.addFilterDefinition(new FilterDefinition( GormProperties.TENANT_IDENTITY, filterCondition, - Collections.singletonMap(GormProperties.TENANT_IDENTITY, getProperty(persistentClass, tenantId.getName()).getType()) - )); + Collections.singletonMap(GormProperties.TENANT_IDENTITY, + getProperty(persistentClass, tenantId.getName()).getType()))); } } } /** - * Binds the sub classes of a root class using table-per-heirarchy inheritance mapping + * Binds the sub classes of a root class using table-per-heirarchy inheritance + * mapping * - * @param domainClass The root domain class to bind - * @param parent The parent class instance - * @param mappings The mappings instance - * @param sessionFactoryBeanName the session factory bean name + * @param domainClass The root domain class to bind + * @param parent The parent class instance + * @param mappings The mappings instance + * @param sessionFactoryBeanName the session factory bean name */ protected void bindSubClasses(HibernatePersistentEntity domainClass, PersistentClass parent, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { - final java.util.Collection subClasses = domainClass.getMappingContext().getDirectChildEntities(domainClass); + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + final java.util.Collection subClasses = domainClass.getMappingContext() + .getDirectChildEntities(domainClass); for (PersistentEntity sub : subClasses) { final Class javaClass = sub.getJavaClass(); - if (javaClass.getSuperclass().equals(domainClass.getJavaClass()) && ConnectionSourcesSupport.usesConnectionSource(sub, dataSourceName)) { + if (javaClass.getSuperclass().equals(domainClass.getJavaClass()) + && ConnectionSourcesSupport.usesConnectionSource(sub, dataSourceName)) { bindSubClass((HibernatePersistentEntity) sub, parent, mappings, sessionFactoryBeanName); } } @@ -1522,13 +1575,13 @@ protected void bindSubClasses(HibernatePersistentEntity domainClass, PersistentC /** * Binds a sub class. * - * @param sub The sub domain class instance - * @param parent The parent persistent class instance - * @param mappings The mappings instance - * @param sessionFactoryBeanName the session factory bean name + * @param sub The sub domain class instance + * @param parent The parent persistent class instance + * @param mappings The mappings instance + * @param sessionFactoryBeanName the session factory bean name */ protected void bindSubClass(HibernatePersistentEntity sub, PersistentClass parent, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { evaluateMapping(sub, defaultMapping); Mapping m = getMapping(parent.getMappedClass()); Subclass subClass; @@ -1537,11 +1590,9 @@ protected void bindSubClass(HibernatePersistentEntity sub, PersistentClass paren final String fullName = sub.getName(); if (tablePerSubclass) { subClass = new JoinedSubclass(parent, this.metadataBuildingContext); - } - else if (tablePerConcreteClass) { + } else if (tablePerConcreteClass) { subClass = new UnionSubclass(parent, this.metadataBuildingContext); - } - else { + } else { subClass = new SingleTableSubclass(parent, this.metadataBuildingContext); // set the descriminator value as the name of the class. This is the // value used by Hibernate to decide what the type of the class is @@ -1549,7 +1600,9 @@ else if (tablePerConcreteClass) { Mapping subMapping = getMapping(sub); DiscriminatorConfig discriminatorConfig = subMapping != null ? subMapping.getDiscriminator() : null; - subClass.setDiscriminatorValue(discriminatorConfig != null && discriminatorConfig.getValue() != null ? discriminatorConfig.getValue() : fullName); + subClass.setDiscriminatorValue(discriminatorConfig != null && discriminatorConfig.getValue() != null + ? discriminatorConfig.getValue() + : fullName); if (subMapping != null) { configureDerivedProperties(sub, subMapping); @@ -1578,17 +1631,16 @@ else if (tablePerConcreteClass) { if (tablePerSubclass) { bindJoinedSubClass(sub, (JoinedSubclass) subClass, mappings, m, sessionFactoryBeanName); - } - else if (tablePerConcreteClass) { + } else if (tablePerConcreteClass) { bindUnionSubclass(sub, (UnionSubclass) subClass, mappings, sessionFactoryBeanName); - } - else { + } else { bindSubClass(sub, subClass, mappings, sessionFactoryBeanName); } addMultiTenantFilterIfNecessary(sub, subClass, mappings, sessionFactoryBeanName); - final java.util.Collection childEntities = sub.getMappingContext().getDirectChildEntities(sub); + final java.util.Collection childEntities = sub.getMappingContext() + .getDirectChildEntities(sub); if (!childEntities.isEmpty()) { // bind the sub classes bindSubClasses(sub, subClass, mappings, sessionFactoryBeanName); @@ -1596,7 +1648,7 @@ else if (tablePerConcreteClass) { } public void bindUnionSubclass(HibernatePersistentEntity subClass, UnionSubclass unionSubclass, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { bindClass(subClass, unionSubclass, mappings); Mapping subMapping = getMapping(subClass.getJavaClass()); @@ -1606,11 +1658,13 @@ public void bindUnionSubclass(HibernatePersistentEntity subClass, UnionSubclass UnionSubclassEntityPersister.class); } - String schema = subMapping != null && subMapping.getTable().getSchema() != null ? - subMapping.getTable().getSchema() : null; + String schema = subMapping != null && subMapping.getTable().getSchema() != null + ? subMapping.getTable().getSchema() + : null; - String catalog = subMapping != null && subMapping.getTable().getCatalog() != null ? - subMapping.getTable().getCatalog() : null; + String catalog = subMapping != null && subMapping.getTable().getCatalog() != null + ? subMapping.getTable().getCatalog() + : null; Table denormalizedSuperTable = unionSubclass.getSuperclass().getTable(); Table mytable = mappings.addDenormalizedTable( @@ -1619,15 +1673,13 @@ public void bindUnionSubclass(HibernatePersistentEntity subClass, UnionSubclass getTableName(subClass, sessionFactoryBeanName), unionSubclass.isAbstract() != null && unionSubclass.isAbstract(), null, - denormalizedSuperTable - ); + denormalizedSuperTable); unionSubclass.setTable(mytable); unionSubclass.setClassName(subClass.getName()); LOG.info( "Mapping union-subclass: " + unionSubclass.getEntityName() + - " -> " + unionSubclass.getTable().getName() - ); + " -> " + unionSubclass.getTable().getName()); createClassProperties(subClass, unionSubclass, mappings, sessionFactoryBeanName); @@ -1636,14 +1688,14 @@ public void bindUnionSubclass(HibernatePersistentEntity subClass, UnionSubclass /** * Binds a joined sub-class mapping using table-per-subclass * - * @param sub The Grails sub class - * @param joinedSubclass The Hibernate Subclass object - * @param mappings The mappings Object - * @param gormMapping The GORM mapping object - * @param sessionFactoryBeanName the session factory bean name + * @param sub The Grails sub class + * @param joinedSubclass The Hibernate Subclass object + * @param mappings The mappings Object + * @param gormMapping The GORM mapping object + * @param sessionFactoryBeanName the session factory bean name */ protected void bindJoinedSubClass(HibernatePersistentEntity sub, JoinedSubclass joinedSubclass, - InFlightMetadataCollector mappings, Mapping gormMapping, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, Mapping gormMapping, String sessionFactoryBeanName) { bindClass(sub, joinedSubclass, mappings); String schemaName = getSchemaName(mappings); @@ -1681,7 +1733,8 @@ protected String getJoinedSubClassTableName( String schemaName = getSchemaName(mappings); String catalogName = getCatalogName(mappings); - mappings.addTableNameBinding(schemaName, catalogName, logicalTableName, physicalTableName, denormalizedSuperTable); + mappings.addTableNameBinding(schemaName, catalogName, logicalTableName, physicalTableName, + denormalizedSuperTable); return physicalTableName; } @@ -1693,7 +1746,7 @@ protected String getJoinedSubClassTableName( * @param mappings The mappings instance */ protected void bindSubClass(HibernatePersistentEntity sub, Subclass subClass, InFlightMetadataCollector mappings, - String sessionFactoryBeanName) { + String sessionFactoryBeanName) { bindClass(sub, subClass, mappings); if (LOG.isDebugEnabled()) @@ -1705,7 +1758,8 @@ protected void bindSubClass(HibernatePersistentEntity sub, Subclass subClass, In } /** - * Creates and binds the discriminator property used in table-per-hierarchy inheritance to + * Creates and binds the discriminator property used in table-per-hierarchy + * inheritance to * discriminate between sub class instances * * @param table The table to bind onto @@ -1729,8 +1783,7 @@ protected void bindDiscriminatorProperty(Table table, RootClass entity, InFlight if (type != null) { if (type instanceof Class) { d.setTypeName(((Class) type).getName()); - } - else { + } else { d.setTypeName(type.toString()); } } @@ -1740,8 +1793,7 @@ protected void bindDiscriminatorProperty(Table table, RootClass entity, InFlight Formula formula = new Formula(); formula.setFormula(discriminatorConfig.getFormula()); d.addFormula(formula); - } - else { + } else { bindSimpleValue(STRING_TYPE, d, false, RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME, mappings); ColumnConfig cc = !hasDiscriminatorConfig ? null : discriminatorConfig.getColumn(); @@ -1767,10 +1819,11 @@ protected void configureDerivedProperties(PersistentEntity domainClass, Mapping } /* - * Binds a persistent classes to the table representation and binds the class properties + * Binds a persistent classes to the table representation and binds the class + * properties */ protected void bindRootPersistentClassCommonValues(HibernatePersistentEntity domainClass, - RootClass root, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + RootClass root, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { // get the schema and catalog names from the configuration Mapping m = getMapping(domainClass.getJavaClass()); @@ -1811,7 +1864,8 @@ protected void bindRootPersistentClassCommonValues(HibernatePersistentEntity dom catalog = m.getTable().getCatalog(); } - final boolean isAbstract = m != null && !m.getTablePerHierarchy() && m.isTablePerConcreteClass() && root.isAbstract(); + final boolean isAbstract = m != null && !m.getTablePerHierarchy() && m.isTablePerConcreteClass() + && root.isAbstract(); // create the table Table table = mappings.addTable(schema, catalog, getTableName(domainClass, sessionFactoryBeanName), @@ -1819,19 +1873,18 @@ protected void bindRootPersistentClassCommonValues(HibernatePersistentEntity dom root.setTable(table); if (LOG.isDebugEnabled()) { - LOG.debug("[GrailsDomainBinder] Mapping Grails domain class: " + domainClass.getName() + " -> " + root.getTable().getName()); + LOG.debug("[GrailsDomainBinder] Mapping Grails domain class: " + domainClass.getName() + " -> " + + root.getTable().getName()); } bindIdentity(domainClass, root, mappings, m, sessionFactoryBeanName); if (m == null) { bindVersion(domainClass.getVersion(), root, mappings, sessionFactoryBeanName); - } - else { + } else { if (m.getVersioned()) { bindVersion(domainClass.getVersion(), root, mappings, sessionFactoryBeanName); - } - else { + } else { root.setOptimisticLockStyle(OptimisticLockStyle.NONE); } } @@ -1865,7 +1918,8 @@ protected void bindIdentity( if (propertyName != null) { PersistentProperty namedIdentityProp = domainClass.getPropertyByName(propertyName); if (namedIdentityProp == null) { - throw new MappingException("Mapping specifies an identifier property name that doesn't exist [" + propertyName + "]"); + throw new MappingException( + "Mapping specifies an identifier property name that doesn't exist [" + propertyName + "]"); } if (!namedIdentityProp.equals(identifierProp)) { identifierProp = namedIdentityProp; @@ -1876,7 +1930,7 @@ protected void bindIdentity( } protected void bindCompositeId(PersistentEntity domainClass, RootClass root, - CompositeIdentity compositeIdentity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + CompositeIdentity compositeIdentity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { HibernatePersistentEntity hibernatePersistentEntity = (HibernatePersistentEntity) domainClass; Component id = new Component(metadataBuildingContext, root); id.setNullValue("undefined"); @@ -1894,8 +1948,9 @@ protected void bindCompositeId(PersistentEntity domainClass, RootClass root, final PersistentProperty[] composite = hibernatePersistentEntity.getCompositeIdentity(); for (PersistentProperty property : composite) { if (property == null) { - throw new MappingException("Property referenced in composite-id mapping of class [" + domainClass.getName() + - "] is not a valid property!"); + throw new MappingException( + "Property referenced in composite-id mapping of class [" + domainClass.getName() + + "] is not a valid property!"); } bindComponentProperty(id, null, property, root, "", root.getTable(), mappings, sessionFactoryBeanName); @@ -1903,16 +1958,17 @@ protected void bindCompositeId(PersistentEntity domainClass, RootClass root, } /** - * Creates and binds the properties for the specified Grails domain class and PersistentClass + * Creates and binds the properties for the specified Grails domain class and + * PersistentClass * and binds them to the Hibernate runtime meta model * - * @param domainClass The Grails domain class - * @param persistentClass The Hibernate PersistentClass instance - * @param mappings The Hibernate Mappings instance - * @param sessionFactoryBeanName the session factory bean name + * @param domainClass The Grails domain class + * @param persistentClass The Hibernate PersistentClass instance + * @param mappings The Hibernate Mappings instance + * @param sessionFactoryBeanName the session factory bean name */ protected void createClassProperties(HibernatePersistentEntity domainClass, PersistentClass persistentClass, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { final List persistentProperties = domainClass.getPersistentProperties(); Table table = persistentClass.getTable(); @@ -1931,9 +1987,12 @@ protected void createClassProperties(HibernatePersistentEntity domainClass, Pers if (currentGrailsProp.isInherited()) { continue; } - if (currentGrailsProp.getName().equals(GormProperties.VERSION)) continue; - if (isCompositeIdProperty(gormMapping, currentGrailsProp)) continue; - if (isIdentityProperty(gormMapping, currentGrailsProp)) continue; + if (currentGrailsProp.getName().equals(GormProperties.VERSION)) + continue; + if (isCompositeIdProperty(gormMapping, currentGrailsProp)) + continue; + if (isIdentityProperty(gormMapping, currentGrailsProp)) + continue; if (LOG.isDebugEnabled()) { LOG.debug("[GrailsDomainBinder] Binding persistent property [" + currentGrailsProp.getName() + "]"); @@ -1948,65 +2007,68 @@ protected void createClassProperties(HibernatePersistentEntity domainClass, Pers if (userType != null && !UserCollectionType.class.isAssignableFrom(userType)) { if (LOG.isDebugEnabled()) { - LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); + LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + + "] as SimpleValue"); } value = new SimpleValue(metadataBuildingContext, table); - bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, sessionFactoryBeanName); - } - else if (collectionType != null) { + bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, + sessionFactoryBeanName); + } else if (collectionType != null) { String typeName = getTypeName(currentGrailsProp, getPropertyConfig(currentGrailsProp), gormMapping); if ("serializable".equals(typeName)) { value = new SimpleValue(metadataBuildingContext, table); bindSimpleValue(typeName, (SimpleValue) value, currentGrailsProp.isNullable(), - getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null, sessionFactoryBeanName), mappings); - } - else { + getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null, + sessionFactoryBeanName), + mappings); + } else { // create collection Collection collection = collectionType.create((ToMany) currentGrailsProp, persistentClass, EMPTY_PATH, mappings, sessionFactoryBeanName); mappings.addCollectionBinding(collection); value = collection; } - } - else if (currentGrailsProp.getType().isEnum()) { + } else if (currentGrailsProp.getType().isEnum()) { value = new SimpleValue(metadataBuildingContext, table); bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName); - } - else if (currentGrailsProp instanceof Association) { + } else if (currentGrailsProp instanceof Association) { Association association = (Association) currentGrailsProp; if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.ManyToOne) { if (LOG.isDebugEnabled()) - LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne"); + LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + + "] as ManyToOne"); value = new ManyToOne(metadataBuildingContext, table); - bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); - } - else if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.OneToOne && userType == null) { + bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, + sessionFactoryBeanName); + } else if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.OneToOne + && userType == null) { if (LOG.isDebugEnabled()) { - LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne"); + LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + + "] as OneToOne"); } final boolean isHasOne = isHasOne(association); if (isHasOne && !association.isBidirectional()) { throw new MappingException("hasOne property [" + currentGrailsProp.getOwner().getName() + - "." + currentGrailsProp.getName() + "] is not bidirectional. Specify the other side of the relationship!"); - } - else if (canBindOneToOneWithSingleColumnAndForeignKey((Association) currentGrailsProp)) { + "." + currentGrailsProp.getName() + + "] is not bidirectional. Specify the other side of the relationship!"); + } else if (canBindOneToOneWithSingleColumnAndForeignKey((Association) currentGrailsProp)) { value = new OneToOne(metadataBuildingContext, table, persistentClass); - bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); - } - else { + bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, + (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); + } else { if (isHasOne && association.isBidirectional()) { value = new OneToOne(metadataBuildingContext, table, persistentClass); - bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); - } - else { + bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, + (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName); + } else { value = new ManyToOne(metadataBuildingContext, table); - bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName); + bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, + sessionFactoryBeanName); } } - } - else if (currentGrailsProp instanceof Embedded) { + } else if (currentGrailsProp instanceof Embedded) { embedded.add((Embedded) currentGrailsProp); continue; } @@ -2014,10 +2076,12 @@ else if (currentGrailsProp instanceof Embedded) { // work out what type of relationship it is and bind value else { if (LOG.isDebugEnabled()) { - LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); + LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + + "] as SimpleValue"); } value = new SimpleValue(metadataBuildingContext, table); - bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, sessionFactoryBeanName); + bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings, + sessionFactoryBeanName); } if (value != null) { @@ -2037,7 +2101,8 @@ else if (currentGrailsProp instanceof Embedded) { } private boolean isHasOne(Association association) { - return association instanceof org.grails.datastore.mapping.model.types.OneToOne && ((org.grails.datastore.mapping.model.types.OneToOne) association).isForeignKeyInChild(); + return association instanceof org.grails.datastore.mapping.model.types.OneToOne + && ((org.grails.datastore.mapping.model.types.OneToOne) association).isForeignKeyInChild(); } protected void bindNaturalIdentifier(Table table, Mapping mapping, PersistentClass persistentClass) { @@ -2061,7 +2126,8 @@ protected void bindNaturalIdentifier(Table table, Mapping mapping, PersistentCla Property property = persistentClass.getProperty(propertyName); property.setNaturalIdentifier(true); - if (!mutable) property.setUpdateable(false); + if (!mutable) + property.setUpdateable(false); uk.addColumns(property.getColumnIterator()); } @@ -2080,8 +2146,7 @@ protected void setGeneratedUniqueName(UniqueKey uk) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); - } - catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } @@ -2126,12 +2191,13 @@ protected boolean isIdentityProperty(Mapping gormMapping, PersistentProperty cur } protected void bindEnumType(PersistentProperty property, SimpleValue simpleValue, - String path, String sessionFactoryBeanName) { + String path, String sessionFactoryBeanName) { bindEnumType(property, property.getType(), simpleValue, getColumnNameForPropertyAndPath(property, path, null, sessionFactoryBeanName)); } - protected void bindEnumType(PersistentProperty property, Class propertyType, SimpleValue simpleValue, String columnName) { + protected void bindEnumType(PersistentProperty property, Class propertyType, SimpleValue simpleValue, + String columnName) { PropertyConfig pc = getPropertyConfig(property); final PersistentEntity owner = property.getOwner(); @@ -2146,16 +2212,13 @@ protected void bindEnumType(PersistentProperty property, Class propertyType, if (isDefaultEnumType || "string".equalsIgnoreCase(enumType)) { enumProperties.put(EnumType.TYPE, String.valueOf(Types.VARCHAR)); enumProperties.put(EnumType.NAMED, Boolean.TRUE.toString()); - } - else if ("identity".equals(enumType)) { + } else if ("identity".equals(enumType)) { simpleValue.setTypeName(IdentityEnumType.class.getName()); - } - else if (!"ordinal".equalsIgnoreCase(enumType)) { + } else if (!"ordinal".equalsIgnoreCase(enumType)) { simpleValue.setTypeName(enumType); } simpleValue.setTypeParameters(enumProperties); - } - else { + } else { simpleValue.setTypeName(typeName); } @@ -2178,7 +2241,8 @@ else if (!"ordinal".equalsIgnoreCase(enumType)) { } column.setValue(simpleValue); column.setName(columnName); - if (t != null) t.addColumn(column); + if (t != null) + t.addColumn(column); simpleValue.addColumn(column); @@ -2219,7 +2283,8 @@ protected boolean isCompositeIdProperty(Mapping gormMapping, PersistentProperty String[] propertyNames = ((CompositeIdentity) id).getPropertyNames(); String property = currentGrailsProp.getName(); for (String currentName : propertyNames) { - if (currentName != null && currentName.equals(property)) return true; + if (currentName != null && currentName.equals(property)) + return true; } } } @@ -2227,20 +2292,22 @@ protected boolean isCompositeIdProperty(Mapping gormMapping, PersistentProperty } protected boolean isBidirectionalManyToOne(PersistentProperty currentGrailsProp) { - return ((currentGrailsProp instanceof org.grails.datastore.mapping.model.types.ManyToOne) && ((Association) currentGrailsProp).isBidirectional()); + return ((currentGrailsProp instanceof org.grails.datastore.mapping.model.types.ManyToOne) + && ((Association) currentGrailsProp).isBidirectional()); } /** - * Binds a Hibernate component type using the given GrailsDomainClassProperty instance + * Binds a Hibernate component type using the given GrailsDomainClassProperty + * instance * - * @param component The component to bind - * @param property The property - * @param isNullable Whether it is nullable or not - * @param mappings The Hibernate Mappings object - * @param sessionFactoryBeanName the session factory bean name + * @param component The component to bind + * @param property The property + * @param isNullable Whether it is nullable or not + * @param mappings The Hibernate Mappings object + * @param sessionFactoryBeanName the session factory bean name */ protected void bindComponent(Component component, Embedded property, - boolean isNullable, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + boolean isNullable, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { component.setEmbedded(true); Class type = property.getType(); String role = qualify(type.getName(), property.getName()); @@ -2256,8 +2323,10 @@ protected void bindComponent(Component component, Embedded property, Class propertyType = property.getOwner().getJavaClass(); for (PersistentProperty currentGrailsProp : properties) { - if (currentGrailsProp.equals(domainClass.getIdentity())) continue; - if (currentGrailsProp.getName().equals(GormProperties.VERSION)) continue; + if (currentGrailsProp.equals(domainClass.getIdentity())) + continue; + if (currentGrailsProp.getName().equals(GormProperties.VERSION)) + continue; if (currentGrailsProp.getType().equals(propertyType)) { component.setParentProperty(currentGrailsProp.getName()); @@ -2270,8 +2339,8 @@ protected void bindComponent(Component component, Embedded property, } protected void bindComponentProperty(Component component, PersistentProperty componentProperty, - PersistentProperty currentGrailsProp, PersistentClass persistentClass, - String path, Table table, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + PersistentProperty currentGrailsProp, PersistentClass persistentClass, + String path, Table table, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { Value value; // see if it's a collection type CollectionType collectionType = CT.collectionTypeForClass(currentGrailsProp.getType()); @@ -2295,26 +2364,24 @@ else if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.M if (canBindOneToOneWithSingleColumnAndForeignKey((Association) currentGrailsProp)) { value = new OneToOne(metadataBuildingContext, table, persistentClass); - bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, (OneToOne) value, path, sessionFactoryBeanName); - } - else { + bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp, (OneToOne) value, + path, sessionFactoryBeanName); + } else { value = new ManyToOne(metadataBuildingContext, table); - bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, path, mappings, sessionFactoryBeanName); + bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, path, mappings, + sessionFactoryBeanName); } - } - else if (currentGrailsProp instanceof Embedded) { + } else if (currentGrailsProp instanceof Embedded) { value = new Component(metadataBuildingContext, persistentClass); bindComponent((Component) value, (Embedded) currentGrailsProp, true, mappings, sessionFactoryBeanName); - } - else { + } else { if (LOG.isDebugEnabled()) LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue"); value = new SimpleValue(metadataBuildingContext, table); if (currentGrailsProp.getType().isEnum()) { bindEnumType(currentGrailsProp, (SimpleValue) value, path, sessionFactoryBeanName); - } - else { + } else { bindSimpleValue(currentGrailsProp, componentProperty, (SimpleValue) value, path, mappings, sessionFactoryBeanName); } @@ -2334,16 +2401,20 @@ else if (currentGrailsProp instanceof Embedded) { } protected boolean isComponentPropertyNullable(PersistentProperty componentProperty) { - if (componentProperty == null) return false; + if (componentProperty == null) + return false; final PersistentEntity domainClass = componentProperty.getOwner(); final Mapping mapping = getMapping(domainClass.getJavaClass()); - return !domainClass.isRoot() && (mapping == null || mapping.isTablePerHierarchy()) || componentProperty.isNullable(); + return !domainClass.isRoot() && (mapping == null || mapping.isTablePerHierarchy()) + || componentProperty.isNullable(); } /* - * Creates a persistent class property based on the GrailDomainClassProperty instance. + * Creates a persistent class property based on the GrailDomainClassProperty + * instance. */ - protected Property createProperty(Value value, PersistentClass persistentClass, PersistentProperty grailsProperty, InFlightMetadataCollector mappings) { + protected Property createProperty(Value value, PersistentClass persistentClass, PersistentProperty grailsProperty, + InFlightMetadataCollector mappings) { // set type value.setTypeUsingReflection(persistentClass.getClassName(), grailsProperty.getName()); @@ -2357,7 +2428,8 @@ protected Property createProperty(Value value, PersistentClass persistentClass, return prop; } - protected void bindOneToMany(org.grails.datastore.mapping.model.types.OneToMany currentGrailsProp, OneToMany one, InFlightMetadataCollector mappings) { + protected void bindOneToMany(org.grails.datastore.mapping.model.types.OneToMany currentGrailsProp, OneToMany one, + InFlightMetadataCollector mappings) { one.setReferencedEntityName(currentGrailsProp.getAssociatedEntity().getName()); one.setIgnoreNotFound(true); } @@ -2368,19 +2440,19 @@ protected void bindOneToMany(org.grails.datastore.mapping.model.types.OneToMany */ @SuppressWarnings("unchecked") protected void bindManyToOne(Association property, ManyToOne manyToOne, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); bindManyToOneValues(property, manyToOne); - PersistentEntity refDomainClass = property instanceof ManyToMany ? property.getOwner() : property.getAssociatedEntity(); + PersistentEntity refDomainClass = property instanceof ManyToMany ? property.getOwner() + : property.getAssociatedEntity(); Mapping mapping = getMapping(refDomainClass); boolean isComposite = hasCompositeIdentifier(mapping); if (isComposite) { CompositeIdentity ci = (CompositeIdentity) mapping.getIdentity(); bindCompositeIdentifierToManyToOne(property, manyToOne, ci, refDomainClass, path, sessionFactoryBeanName); - } - else { + } else { if (property.isCircular() && (property instanceof ManyToMany)) { PropertyConfig pc = getPropertyConfig(property); @@ -2396,8 +2468,7 @@ protected void bindManyToOne(Association property, ManyToOne manyToOne, pc.setJoinTable(jt); } bindSimpleValue(property, manyToOne, path, pc, sessionFactoryBeanName); - } - else { + } else { // bind column bindSimpleValue(property, null, manyToOne, path, mappings, sessionFactoryBeanName); } @@ -2409,16 +2480,15 @@ protected void bindManyToOne(Association property, ManyToOne manyToOne, Column c = getColumnForSimpleValue(manyToOne); if (config != null && !config.isUniqueWithinGroup()) { c.setUnique(config.isUnique()); - } - else if (property.isBidirectional() && isHasOne(property.getInverseSide())) { + } else if (property.isBidirectional() && isHasOne(property.getInverseSide())) { c.setUnique(true); } } } protected void bindCompositeIdentifierToManyToOne(Association property, - SimpleValue value, CompositeIdentity compositeId, PersistentEntity refDomainClass, - String path, String sessionFactoryBeanName) { + SimpleValue value, CompositeIdentity compositeId, PersistentEntity refDomainClass, + String path, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); @@ -2453,8 +2523,10 @@ protected void bindCompositeIdentifierToManyToOne(Association property, PersistentProperty[] compositeIdentity = toOne.getAssociatedEntity().getCompositeIdentity(); if (compositeIdentity != null) { for (PersistentProperty cip : compositeIdentity) { - // for each property of a composite id by default we use the table name and the property name as a prefix - String compositeIdPrefix = addUnderscore(prefix, namingStrategy.propertyToColumnName(referencedProperty.getName())); + // for each property of a composite id by default we use the table name and the + // property name as a prefix + String compositeIdPrefix = addUnderscore(prefix, + namingStrategy.propertyToColumnName(referencedProperty.getName())); String suffix = getDefaultColumnName(cip, sessionFactoryBeanName); String finalColumnName = addUnderscore(compositeIdPrefix, suffix); cc = new ColumnConfig(); @@ -2475,8 +2547,10 @@ protected void bindCompositeIdentifierToManyToOne(Association property, bindSimpleValue(property, value, path, config, sessionFactoryBeanName); } - // each property may consist of one or many columns (due to composite ids) so in order to get the - // number of columns required for a column key we have to perform the calculation here + // each property may consist of one or many columns (due to composite ids) so in + // order to get the + // number of columns required for a column key we have to perform the + // calculation here private int calculateForeignKeyColumnCount(PersistentEntity refDomainClass, String[] propertyNames) { int expectedForeignKeyColumnLength = 0; for (String propertyName : propertyNames) { @@ -2486,12 +2560,10 @@ private int calculateForeignKeyColumnCount(PersistentEntity refDomainClass, Stri PersistentProperty[] compositeIdentity = toOne.getAssociatedEntity().getCompositeIdentity(); if (compositeIdentity != null) { expectedForeignKeyColumnLength += compositeIdentity.length; - } - else { + } else { expectedForeignKeyColumnLength++; } - } - else { + } else { expectedForeignKeyColumnLength++; } } @@ -2503,21 +2575,19 @@ protected boolean hasCompositeIdentifier(Mapping mapping) { } protected void bindOneToOne(final org.grails.datastore.mapping.model.types.OneToOne property, OneToOne oneToOne, - String path, String sessionFactoryBeanName) { + String path, String sessionFactoryBeanName) { PropertyConfig config = getPropertyConfig(property); final Association otherSide = property.getInverseSide(); final boolean hasOne = isHasOne(otherSide); oneToOne.setConstrained(hasOne); - oneToOne.setForeignKeyType(oneToOne.isConstrained() ? - ForeignKeyDirection.FROM_PARENT : - ForeignKeyDirection.TO_PARENT); + oneToOne.setForeignKeyType( + oneToOne.isConstrained() ? ForeignKeyDirection.FROM_PARENT : ForeignKeyDirection.TO_PARENT); oneToOne.setAlternateUniqueKey(true); if (config != null && config.getFetchMode() != null) { oneToOne.setFetchMode(config.getFetchMode()); - } - else { + } else { oneToOne.setFetchMode(FetchMode.DEFAULT); } @@ -2530,25 +2600,25 @@ protected void bindOneToOne(final org.grails.datastore.mapping.model.types.OneTo if (hasOne) { PropertyConfig pc = getPropertyConfig(property); bindSimpleValue(property, oneToOne, path, pc, sessionFactoryBeanName); - } - else { + } else { oneToOne.setReferencedPropertyName(otherSide.getName()); } } - protected void bindOneToOneInternal(org.grails.datastore.mapping.model.types.OneToOne property, OneToOne oneToOne, String path) { - //no-op, for subclasses to extend + protected void bindOneToOneInternal(org.grails.datastore.mapping.model.types.OneToOne property, OneToOne oneToOne, + String path) { + // no-op, for subclasses to extend } /** */ - protected void bindManyToOneValues(org.grails.datastore.mapping.model.types.Association property, ManyToOne manyToOne) { + protected void bindManyToOneValues(org.grails.datastore.mapping.model.types.Association property, + ManyToOne manyToOne) { PropertyConfig config = getPropertyConfig(property); if (config != null && config.getFetchMode() != null) { manyToOne.setFetchMode(config.getFetchMode()); - } - else { + } else { manyToOne.setFetchMode(FetchMode.DEFAULT); } @@ -2563,7 +2633,7 @@ protected void bindManyToOneValues(org.grails.datastore.mapping.model.types.Asso } protected void bindVersion(PersistentProperty version, RootClass entity, - InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, String sessionFactoryBeanName) { if (version != null) { @@ -2579,8 +2649,7 @@ protected void bindVersion(PersistentProperty version, RootClass entity, "; must be one of [int, Integer, long, Long, Timestamp, Date]. Not mapping the version."); return; } - } - else { + } else { val.setTypeName("version".equals(version.getName()) ? "integer" : "timestamp"); } Property prop = new Property(); @@ -2592,15 +2661,14 @@ protected void bindVersion(PersistentProperty version, RootClass entity, entity.setDeclaredVersion(prop); entity.setOptimisticLockStyle(OptimisticLockStyle.VERSION); entity.addProperty(prop); - } - else { + } else { entity.setOptimisticLockStyle(OptimisticLockStyle.NONE); } } @SuppressWarnings("unchecked") protected void bindSimpleId(PersistentProperty identifier, RootClass entity, - InFlightMetadataCollector mappings, Identity mappedId, String sessionFactoryBeanName) { + InFlightMetadataCollector mappings, Identity mappedId, String sessionFactoryBeanName) { Mapping mapping = getMapping(identifier.getOwner()); boolean useSequence = mapping != null && mapping.isTablePerConcreteClass(); @@ -2637,7 +2705,8 @@ protected void bindSimpleId(PersistentProperty identifier, RootClass entity, String schemaName = getSchemaName(mappings); String catalogName = getCatalogName(mappings); - params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, this.metadataBuildingContext.getObjectNameNormalizer()); + params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, + this.metadataBuildingContext.getObjectNameNormalizer()); if (schemaName != null) { params.setProperty(PersistentIdentifierGenerator.SCHEMA, schemaName); @@ -2679,7 +2748,8 @@ private String getCatalogName(InFlightMetadataCollector mappings) { } /** - * Binds a property to Hibernate runtime meta model. Deals with cascade strategy based on the Grails domain model + * Binds a property to Hibernate runtime meta model. Deals with cascade strategy + * based on the Grails domain model * * @param grailsProperty The grails property instance * @param prop The Hibernate property @@ -2697,20 +2767,17 @@ protected void bindProperty(PersistentProperty grailsProperty, Property prop, In } AccessType accessType = AccessType.getAccessStrategy( - grailsProperty.getMapping().getMappedForm().getAccessType() - ); + grailsProperty.getMapping().getMappedForm().getAccessType()); if (accessType == AccessType.FIELD) { EntityReflector.PropertyReader reader = grailsProperty.getReader(); Method getter = reader != null ? reader.getter() : null; if (getter != null && getter.getAnnotation(Traits.Implemented.class) != null) { prop.setPropertyAccessorName(TraitPropertyAccessStrategy.class.getName()); - } - else { + } else { prop.setPropertyAccessorName(accessType.getType()); } - } - else { + } else { prop.setPropertyAccessorName(accessType.getType()); } @@ -2728,7 +2795,8 @@ protected void bindProperty(PersistentProperty grailsProperty, Property prop, In final boolean isLazy = getLaziness(grailsProperty); prop.setLazy(isLazy); - if (isLazy && isToOne && !(PersistentAttributeInterceptable.class.isAssignableFrom(propertyOwner.getJavaClass()))) { + if (isLazy && isToOne + && !(PersistentAttributeInterceptable.class.isAssignableFrom(propertyOwner.getJavaClass()))) { // handleLazyProxy(propertyOwner, grailsProperty); } } @@ -2739,8 +2807,7 @@ protected boolean getLaziness(PersistentProperty grailsProperty) { final Boolean lazy = config.getLazy(); if (lazy == null && grailsProperty instanceof Association) { return true; - } - else if (lazy != null) { + } else if (lazy != null) { return lazy; } return false; @@ -2780,19 +2847,16 @@ protected void setCascadeBehaviour(PersistentProperty grailsProperty, Property p PersistentEntity referenced = association.getAssociatedEntity(); if (isHasOne(association)) { cascadeStrategy = CASCADE_ALL; - } - else if (association instanceof org.grails.datastore.mapping.model.types.OneToOne) { + } else if (association instanceof org.grails.datastore.mapping.model.types.OneToOne) { if (referenced != null && association.isOwningSide()) { cascadeStrategy = CASCADE_ALL; - } - else { + } else { cascadeStrategy = CASCADE_SAVE_UPDATE; } } else if (association instanceof org.grails.datastore.mapping.model.types.OneToMany) { if (referenced != null && association.isOwningSide()) { cascadeStrategy = CASCADE_ALL; - } - else { + } else { cascadeStrategy = CASCADE_SAVE_UPDATE; } } else if (grailsProperty instanceof ManyToMany) { @@ -2800,20 +2864,17 @@ else if (association instanceof org.grails.datastore.mapping.model.types.OneToOn cascadeStrategy = CASCADE_SAVE_UPDATE; } } else if (grailsProperty instanceof org.grails.datastore.mapping.model.types.ManyToOne) { - if (referenced != null && referenced.isOwningEntity(domainClass) && !isCircularAssociation(grailsProperty)) { + if (referenced != null && referenced.isOwningEntity(domainClass) + && !isCircularAssociation(grailsProperty)) { cascadeStrategy = CASCADE_ALL; - } - else if (isCompositeIdProperty((Mapping) domainClass.getMapping().getMappedForm(), grailsProperty)) { + } else if (isCompositeIdProperty((Mapping) domainClass.getMapping().getMappedForm(), grailsProperty)) { cascadeStrategy = CASCADE_ALL; - } - else { + } else { cascadeStrategy = CASCADE_NONE; } - } - else if (grailsProperty instanceof Basic) { + } else if (grailsProperty instanceof Basic) { cascadeStrategy = CASCADE_ALL; - } - else if (Map.class.isAssignableFrom(grailsProperty.getType())) { + } else if (Map.class.isAssignableFrom(grailsProperty.getType())) { referenced = association.getAssociatedEntity(); if (referenced != null && referenced.isOwningEntity(domainClass)) { cascadeStrategy = CASCADE_ALL; @@ -2833,7 +2894,9 @@ protected boolean isCircularAssociation(PersistentProperty grailsProperty) { protected void logCascadeMapping(Association grailsProperty, String cascadeStrategy, PersistentEntity referenced) { if (LOG.isDebugEnabled() & referenced != null) { String assType = getAssociationDescription(grailsProperty); - LOG.debug("Mapping cascade strategy for " + assType + " property " + grailsProperty.getOwner().getName() + "." + grailsProperty.getName() + " referencing type [" + referenced.getJavaClass().getName() + "] -> [CASCADE: " + cascadeStrategy + "]"); + LOG.debug("Mapping cascade strategy for " + assType + " property " + grailsProperty.getOwner().getName() + + "." + grailsProperty.getName() + " referencing type [" + referenced.getJavaClass().getName() + + "] -> [CASCADE: " + cascadeStrategy + "]"); } } @@ -2859,25 +2922,26 @@ protected String getAssociationDescription(Association grailsProperty) { * * @param property * @param parentProperty - * @param simpleValue The simple value to bind + * @param simpleValue The simple value to bind * @param path - * @param mappings The Hibernate mappings instance - * @param sessionFactoryBeanName the session factory bean name + * @param mappings The Hibernate mappings instance + * @param sessionFactoryBeanName the session factory bean name */ protected void bindSimpleValue(PersistentProperty property, PersistentProperty parentProperty, - SimpleValue simpleValue, String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { + SimpleValue simpleValue, String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { // set type - bindSimpleValue(property, parentProperty, simpleValue, path, getPropertyConfig(property), sessionFactoryBeanName); + bindSimpleValue(property, parentProperty, simpleValue, path, getPropertyConfig(property), + sessionFactoryBeanName); } protected void bindSimpleValue(PersistentProperty grailsProp, SimpleValue simpleValue, - String path, PropertyConfig propertyConfig, String sessionFactoryBeanName) { + String path, PropertyConfig propertyConfig, String sessionFactoryBeanName) { bindSimpleValue(grailsProp, null, simpleValue, path, propertyConfig, sessionFactoryBeanName); } protected void bindSimpleValue(PersistentProperty grailsProp, - PersistentProperty parentProperty, SimpleValue simpleValue, - String path, PropertyConfig propertyConfig, String sessionFactoryBeanName) { + PersistentProperty parentProperty, SimpleValue simpleValue, + String path, PropertyConfig propertyConfig, String sessionFactoryBeanName) { setTypeForPropertyConfig(grailsProp, simpleValue, propertyConfig); final PropertyConfig mappedForm = (PropertyConfig) grailsProp.getMapping().getMappedForm(); if (mappedForm.isDerived() && !(grailsProp instanceof TenantId)) { @@ -2897,7 +2961,8 @@ protected void bindSimpleValue(PersistentProperty grailsProp, generatorProps.putAll(params); if (generatorProps.containsKey(SEQUENCE_KEY)) { - generatorProps.put(SequenceStyleGenerator.SEQUENCE_PARAM, generatorProps.getProperty(SEQUENCE_KEY)); + generatorProps.put(SequenceStyleGenerator.SEQUENCE_PARAM, + generatorProps.getProperty(SEQUENCE_KEY)); } simpleValue.setIdentifierGeneratorProperties(generatorProps); } @@ -2907,8 +2972,7 @@ protected void bindSimpleValue(PersistentProperty grailsProp, // not all custom mapped properties will have column definitions, // in which case we still need to create a Hibernate column for // this value. - List columnDefinitions = hasConfig ? propertyConfig.getColumns() : - Arrays.asList(new Object[] { null }); + List columnDefinitions = hasConfig ? propertyConfig.getColumns() : Arrays.asList(new Object[] { null }); if (columnDefinitions.isEmpty()) { columnDefinitions = Arrays.asList(new Object[] { null }); } @@ -2955,12 +3019,13 @@ protected void bindSimpleValue(PersistentProperty grailsProp, } } - protected void setTypeForPropertyConfig(PersistentProperty grailsProp, SimpleValue simpleValue, PropertyConfig config) { - final String typeName = getTypeName(grailsProp, getPropertyConfig(grailsProp), getMapping(grailsProp.getOwner())); + protected void setTypeForPropertyConfig(PersistentProperty grailsProp, SimpleValue simpleValue, + PropertyConfig config) { + final String typeName = getTypeName(grailsProp, getPropertyConfig(grailsProp), + getMapping(grailsProp.getOwner())); if (typeName == null) { simpleValue.setTypeName(grailsProp.getType().getName()); - } - else { + } else { simpleValue.setTypeName(typeName); if (config != null) { simpleValue.setTypeParameters(config.getTypeParams()); @@ -2978,7 +3043,7 @@ protected void setTypeForPropertyConfig(PersistentProperty grailsProp, SimpleVal * @param mappings The mappings */ protected void bindSimpleValue(String type, SimpleValue simpleValue, boolean nullable, - String columnName, InFlightMetadataCollector mappings) { + String columnName, InFlightMetadataCollector mappings) { simpleValue.setTypeName(type); Table t = simpleValue.getTable(); @@ -2986,7 +3051,8 @@ protected void bindSimpleValue(String type, SimpleValue simpleValue, boolean nul column.setNullable(nullable); column.setValue(simpleValue); column.setName(columnName); - if (t != null) t.addColumn(column); + if (t != null) + t.addColumn(column); simpleValue.addColumn(column); } @@ -2994,15 +3060,15 @@ protected void bindSimpleValue(String type, SimpleValue simpleValue, boolean nul /** * Binds a Column instance to the Hibernate meta model * - * @param property The Grails domain class property + * @param property The Grails domain class property * @param parentProperty - * @param column The column to bind + * @param column The column to bind * @param path - * @param table The table name - * @param sessionFactoryBeanName the session factory bean name + * @param table The table name + * @param sessionFactoryBeanName the session factory bean name */ protected void bindColumn(PersistentProperty property, PersistentProperty parentProperty, - Column column, ColumnConfig cc, String path, Table table, String sessionFactoryBeanName) { + Column column, ColumnConfig cc, String path, Table table, String sessionFactoryBeanName) { if (cc != null) { column.setComment(cc.getComment()); @@ -3021,29 +3087,26 @@ protected void bindColumn(PersistentProperty property, PersistentProperty parent } if (property instanceof ManyToMany) { column.setNullable(false); - } - else if (property instanceof org.grails.datastore.mapping.model.types.OneToOne && association.isBidirectional() && !association.isOwningSide()) { + } else if (property instanceof org.grails.datastore.mapping.model.types.OneToOne + && association.isBidirectional() && !association.isOwningSide()) { if (isHasOne(((Association) property).getInverseSide())) { column.setNullable(false); - } - else { + } else { column.setNullable(true); } - } - else if ((property instanceof ToOne) && association.isCircular()) { + } else if ((property instanceof ToOne) && association.isCircular()) { column.setNullable(true); - } - else { + } else { column.setNullable(property.isNullable()); } - } - else { + } else { column.setName(columnName); column.setNullable(property.isNullable() || (parentProperty != null && parentProperty.isNullable())); // Use the constraints for this property to more accurately define // the column's length, precision, and scale - if (String.class.isAssignableFrom(property.getType()) || byte[].class.isAssignableFrom(property.getType())) { + if (String.class.isAssignableFrom(property.getType()) + || byte[].class.isAssignableFrom(property.getType())) { bindStringColumnConstraints(column, property); } @@ -3061,7 +3124,8 @@ else if ((property instanceof ToOne) && association.isCircular()) { Mapping mapping = getMapping(owner); if (mapping == null || mapping.getTablePerHierarchy()) { if (LOG.isDebugEnabled()) - LOG.debug("[GrailsDomainBinder] Sub class property [" + property.getName() + "] for column name [" + column.getName() + "] set to nullable"); + LOG.debug("[GrailsDomainBinder] Sub class property [" + property.getName() + "] for column name [" + + column.getName() + "] set to nullable"); column.setNullable(true); } else { column.setNullable(property.isNullable()); @@ -3069,18 +3133,20 @@ else if ((property instanceof ToOne) && association.isCircular()) { } if (LOG.isDebugEnabled()) - LOG.debug("[GrailsDomainBinder] bound property [" + property.getName() + "] to column name [" + column.getName() + "] in table [" + table.getName() + "]"); + LOG.debug("[GrailsDomainBinder] bound property [" + property.getName() + "] to column name [" + + column.getName() + "] in table [" + table.getName() + "]"); } protected void createKeyForProps(PersistentProperty grailsProp, String path, Table table, - String columnName, List propertyNames, String sessionFactoryBeanName) { + String columnName, List propertyNames, String sessionFactoryBeanName) { List keyList = new ArrayList<>(); keyList.add(new Column(columnName)); for (Iterator i = propertyNames.iterator(); i.hasNext();) { String propertyName = (String) i.next(); PersistentProperty otherProp = grailsProp.getOwner().getPropertyByName(propertyName); if (otherProp == null) { - throw new MappingException(grailsProp.getOwner().getJavaClass().getName() + " references an unknown property " + propertyName); + throw new MappingException(grailsProp.getOwner().getJavaClass().getName() + + " references an unknown property " + propertyName); } String otherColumnName = getColumnNameForPropertyAndPath(otherProp, path, null, sessionFactoryBeanName); keyList.add(new Column(otherColumnName)); @@ -3114,8 +3180,7 @@ protected void bindIndex(String columnName, Column column, ColumnConfig cc, Tabl if (b) { indexDefinition = table.getName() + '_' + columnName + "_idx"; } - } - else if (indexObj != null) { + } else if (indexObj != null) { indexDefinition = indexObj.toString(); } if (indexDefinition == null) { @@ -3129,7 +3194,7 @@ else if (indexObj != null) { } protected String getColumnNameForPropertyAndPath(PersistentProperty grailsProp, - String path, ColumnConfig cc, String sessionFactoryBeanName) { + String path, ColumnConfig cc, String sessionFactoryBeanName) { NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); @@ -3144,23 +3209,19 @@ protected String getColumnNameForPropertyAndPath(PersistentProperty grailsProp, if (supportsJoinColumnMapping(grailsProp) && hasJoinKeyMapping(c)) { columnName = c.getJoinTable().getKey().getName(); - } - else if (c != null && c.getColumn() != null) { + } else if (c != null && c.getColumn() != null) { columnName = c.getColumn(); } } - } - else { + } else { if (supportsJoinColumnMapping(grailsProp)) { PropertyConfig pc = getPropertyConfig(grailsProp); if (hasJoinKeyMapping(pc)) { columnName = pc.getJoinTable().getKey().getName(); - } - else { + } else { columnName = cc.getName(); } - } - else { + } else { columnName = cc.getName(); } } @@ -3204,13 +3265,15 @@ protected String getDefaultColumnName(PersistentProperty property, String sessio return getForeignKeyForPropertyDomainClass(property, sessionFactoryBeanName); } - if (!association.isBidirectional() && association instanceof org.grails.datastore.mapping.model.types.OneToMany) { + if (!association.isBidirectional() + && association instanceof org.grails.datastore.mapping.model.types.OneToMany) { String prefix = namingStrategy.classToTableName(property.getOwner().getName()); return addUnderscore(prefix, columnName) + FOREIGN_KEY_SUFFIX; } if (property.isInherited() && isBidirectionalManyToOne(property)) { - return namingStrategy.propertyToColumnName(property.getOwner().getName()) + '_' + columnName + FOREIGN_KEY_SUFFIX; + return namingStrategy.propertyToColumnName(property.getOwner().getName()) + '_' + columnName + + FOREIGN_KEY_SUFFIX; } return columnName + FOREIGN_KEY_SUFFIX; @@ -3220,7 +3283,7 @@ protected String getDefaultColumnName(PersistentProperty property, String sessio } protected String getForeignKeyForPropertyDomainClass(PersistentProperty property, - String sessionFactoryBeanName) { + String sessionFactoryBeanName) { final String propertyName = NameUtils.decapitalize(property.getOwner().getName()); NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); return namingStrategy.propertyToColumnName(propertyName) + FOREIGN_KEY_SUFFIX; @@ -3232,7 +3295,8 @@ protected String getIndexColumnName(PersistentProperty property, String sessionF return pc.getIndexColumn().getColumn(); } NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); - return namingStrategy.propertyToColumnName(property.getName()) + UNDERSCORE + IndexedCollection.DEFAULT_INDEX_COLUMN_NAME; + return namingStrategy.propertyToColumnName(property.getName()) + UNDERSCORE + + IndexedCollection.DEFAULT_INDEX_COLUMN_NAME; } protected String getIndexColumnType(PersistentProperty property, String defaultType) { @@ -3251,22 +3315,28 @@ protected String getMapElementName(PersistentProperty property, String sessionFa } NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName); - return namingStrategy.propertyToColumnName(property.getName()) + UNDERSCORE + IndexedCollection.DEFAULT_ELEMENT_COLUMN_NAME; + return namingStrategy.propertyToColumnName(property.getName()) + UNDERSCORE + + IndexedCollection.DEFAULT_ELEMENT_COLUMN_NAME; } protected boolean hasJoinTableColumnNameMapping(PropertyConfig pc) { - return pc != null && pc.getJoinTable() != null && pc.getJoinTable().getColumn() != null && pc.getJoinTable().getColumn().getName() != null; + return pc != null && pc.getJoinTable() != null && pc.getJoinTable().getColumn() != null + && pc.getJoinTable().getColumn().getName() != null; } /** - * Interrogates the specified constraints looking for any constraints that would limit the - * length of the property's value. If such constraints exist, this method adjusts the length + * Interrogates the specified constraints looking for any constraints that would + * limit the + * length of the property's value. If such constraints exist, this method + * adjusts the length * of the column accordingly. - * @param column the column that corresponds to the property + * + * @param column the column that corresponds to the property * @param constrainedProperty the property's constraints */ protected void bindStringColumnConstraints(Column column, PersistentProperty constrainedProperty) { - final org.grails.datastore.mapping.config.Property mappedForm = constrainedProperty.getMapping().getMappedForm(); + final org.grails.datastore.mapping.config.Property mappedForm = constrainedProperty.getMapping() + .getMappedForm(); Number columnLength = mappedForm.getMaxSize(); List inListValues = mappedForm.getInList(); if (columnLength != null) { @@ -3281,12 +3351,15 @@ protected void bindNumericColumnConstraints(Column column, PersistentProperty co } /** - * Interrogates the specified constraints looking for any constraints that would limit the - * precision and/or scale of the property's value. If such constraints exist, this method adjusts + * Interrogates the specified constraints looking for any constraints that would + * limit the + * precision and/or scale of the property's value. If such constraints exist, + * this method adjusts * the precision and/or scale of the column accordingly. - * @param column the column that corresponds to the property + * + * @param column the column that corresponds to the property * @param property the property's constraints - * @param cc the column configuration + * @param cc the column configuration */ protected void bindNumericColumnConstraints(Column column, PersistentProperty property, ColumnConfig cc) { int scale = Column.DEFAULT_SCALE; @@ -3302,8 +3375,7 @@ protected void bindNumericColumnConstraints(Column column, PersistentProperty pr if (cc != null && cc.getPrecision() > -1) { column.setPrecision(cc.getPrecision()); - } - else { + } else { Comparable minConstraintValue = constrainedProperty.getMin(); Comparable maxConstraintValue = constrainedProperty.getMax(); @@ -3327,7 +3399,8 @@ protected void bindNumericColumnConstraints(Column column, PersistentProperty pr precision = Math.max(minConstraintValueLength, maxConstraintValueLength); } else { // Overwise we should also use default precision - precision = DefaultGroovyMethods.max(new Integer[]{precision, minConstraintValueLength, maxConstraintValueLength}); + precision = DefaultGroovyMethods + .max(new Integer[] { precision, minConstraintValueLength, maxConstraintValueLength }); } column.setPrecision(precision); @@ -3363,14 +3436,15 @@ protected int getMaxSize(List inListValues) { return maxSize; } - protected void handleUniqueConstraint(PersistentProperty property, Column column, String path, Table table, String columnName, String sessionFactoryBeanName) { + protected void handleUniqueConstraint(PersistentProperty property, Column column, String path, Table table, + String columnName, String sessionFactoryBeanName) { final PropertyConfig mappedForm = (PropertyConfig) property.getMapping().getMappedForm(); if (mappedForm.isUnique()) { if (!mappedForm.isUniqueWithinGroup()) { column.setUnique(true); - } - else { - createKeyForProps(property, path, table, columnName, mappedForm.getUniquenessGroup(), sessionFactoryBeanName); + } else { + createKeyForProps(property, path, table, columnName, mappedForm.getUniquenessGroup(), + sessionFactoryBeanName); } } @@ -3409,7 +3483,7 @@ class GrailsCollectionSecondPass implements SecondPass { protected String sessionFactoryBeanName; public GrailsCollectionSecondPass(ToMany property, InFlightMetadataCollector mappings, - Collection coll, String sessionFactoryBeanName) { + Collection coll, String sessionFactoryBeanName) { this.property = property; this.mappings = mappings; this.collection = coll; @@ -3443,7 +3517,8 @@ protected String columns(Value val) { Iterator iter = val.getColumnIterator(); while (iter.hasNext()) { columns.append(((Selectable) iter.next()).getText()); - if (iter.hasNext()) columns.append(", "); + if (iter.hasNext()) + columns.append(", "); } return columns.toString(); } @@ -3459,7 +3534,7 @@ class ListSecondPass extends GrailsCollectionSecondPass { private static final long serialVersionUID = -3024674993774205193L; public ListSecondPass(ToMany property, InFlightMetadataCollector mappings, - Collection coll, String sessionFactoryBeanName) { + Collection coll, String sessionFactoryBeanName) { super(property, mappings, coll, sessionFactoryBeanName); } @@ -3481,7 +3556,7 @@ class MapSecondPass extends GrailsCollectionSecondPass { private static final long serialVersionUID = -3244991685626409031L; public MapSecondPass(ToMany property, InFlightMetadataCollector mappings, - Collection coll, String sessionFactoryBeanName) { + Collection coll, String sessionFactoryBeanName) { super(property, mappings, coll, sessionFactoryBeanName); } @@ -3504,7 +3579,7 @@ public void doSecondPass(Map persistentClasses) throws MappingException { * * @author Graeme */ - static abstract class CollectionType { + protected static abstract class CollectionType { protected final Class clazz; protected final GrailsDomainBinder binder; @@ -3519,7 +3594,7 @@ static abstract class CollectionType { protected final Map, CollectionType> INSTANCES = new HashMap<>(); public abstract Collection create(ToMany property, PersistentClass owner, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException; + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException; protected CollectionType(Class clazz, GrailsDomainBinder binder) { this.clazz = clazz; @@ -3543,7 +3618,8 @@ protected void createInstances() { SET = new CollectionType(Set.class, binder) { @Override public Collection create(ToMany property, PersistentClass owner, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) + throws MappingException { org.hibernate.mapping.Set coll = new org.hibernate.mapping.Set(buildingContext, owner); coll.setCollectionTable(owner.getTable()); coll.setTypeName(getTypeName(property)); @@ -3557,7 +3633,8 @@ public Collection create(ToMany property, PersistentClass owner, LIST = new CollectionType(List.class, binder) { @Override public Collection create(ToMany property, PersistentClass owner, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) + throws MappingException { org.hibernate.mapping.List coll = new org.hibernate.mapping.List(buildingContext, owner); coll.setCollectionTable(owner.getTable()); coll.setTypeName(getTypeName(property)); @@ -3570,7 +3647,8 @@ public Collection create(ToMany property, PersistentClass owner, BAG = new CollectionType(java.util.Collection.class, binder) { @Override public Collection create(ToMany property, PersistentClass owner, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) + throws MappingException { Bag coll = new Bag(buildingContext, owner); coll.setCollectionTable(owner.getTable()); coll.setTypeName(getTypeName(property)); @@ -3583,7 +3661,8 @@ public Collection create(ToMany property, PersistentClass owner, MAP = new CollectionType(Map.class, binder) { @Override public Collection create(ToMany property, PersistentClass owner, - String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException { + String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) + throws MappingException { org.hibernate.mapping.Map map = new org.hibernate.mapping.Map(buildingContext, owner); map.setTypeName(getTypeName(property)); binder.bindCollection(property, map, owner, mappings, path, sessionFactoryBeanName); diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/IdentityEnumType.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/IdentityEnumType.java index 0b56d2016ea..4412c31cedd 100644 --- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/IdentityEnumType.java +++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/cfg/IdentityEnumType.java @@ -65,15 +65,15 @@ public class IdentityEnumType implements UserType, ParameterizedType, Serializab protected AbstractStandardBasicType type; protected int[] sqlTypes; - public static BidiEnumMap getBidiEnumMap(Class> cls) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { + public static BidiEnumMap getBidiEnumMap(Class> cls) + throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { BidiEnumMap m = ENUM_MAPPINGS.get(cls); if (m == null) { synchronized (ENUM_MAPPINGS) { if (!ENUM_MAPPINGS.containsKey(cls)) { m = new BidiEnumMap(cls); ENUM_MAPPINGS.put(cls, m); - } - else { + } else { m = ENUM_MAPPINGS.get(cls); } } @@ -90,13 +90,13 @@ public void setParameterValues(Properties properties) { LOG.debug(String.format("Building ID-mapping for Enum Class %s", enumClass.getName())); } bidiMap = getBidiEnumMap(enumClass); - type = (AbstractStandardBasicType) typeConfiguration.getBasicTypeRegistry().getRegisteredType(bidiMap.keyType.getName()); + type = (AbstractStandardBasicType) typeConfiguration.getBasicTypeRegistry() + .getRegisteredType(bidiMap.keyType.getName()); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Mapped Basic Type is %s", type)); } sqlTypes = type.sqlTypes(null); - } - catch (Exception e) { + } catch (Exception e) { throw new MappingException("Error mapping Enum Class using IdentifierEnumType", e); } } @@ -118,7 +118,8 @@ public int hashCode(Object o) throws HibernateException { } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { + public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) + throws HibernateException, SQLException { Object id = type.nullSafeGet(rs, names[0], session); if ((!rs.wasNull()) && id != null) { return bidiMap.getEnumValue(id); @@ -127,11 +128,11 @@ public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImp } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { + public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) + throws HibernateException, SQLException { if (value == null) { st.setNull(index, sqlTypes[0]); - } - else { + } else { type.nullSafeSet(st, bidiMap.getKey(value), index, session); } } @@ -156,15 +157,16 @@ public Object replace(Object orig, Object target, Object owner) throws Hibernate return orig; } - @SuppressWarnings({"rawtypes", "unchecked"}) - private static class BidiEnumMap implements Serializable { + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected static class BidiEnumMap implements Serializable { private static final long serialVersionUID = 3325751131102095834L; private final Map enumToKey; private final Map keytoEnum; private Class keyType; - private BidiEnumMap(Class enumClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + private BidiEnumMap(Class enumClass) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (LOG.isDebugEnabled()) { LOG.debug("Building Bidirectional Enum Map..."); } diff --git a/grails-doc/build.gradle b/grails-doc/build.gradle index 8ba84684edb..1f611e41006 100644 --- a/grails-doc/build.gradle +++ b/grails-doc/build.gradle @@ -20,6 +20,7 @@ import grails.doc.git.FetchTagsTask import grails.doc.dropdown.CreateReleaseDropDownTask import grails.doc.gradle.PublishGuideTask +import org.grails.doc.gradle.FixGroovydocLinksTask plugins { id 'base' @@ -121,6 +122,11 @@ combinedGroovydoc.configure { Groovydoc gdoc -> gdoc.outputs.dir(gdoc.destinationDir) } +def fixGroovydocLinks = tasks.register('fixGroovydocLinks', FixGroovydocLinksTask) { + dependsOn combinedGroovydoc + apiDocsDir = combinedGroovydoc.get().destinationDir +} + String getVersion(String artifact) { String version = configurations.runtimeClasspath .resolvedConfiguration @@ -278,7 +284,7 @@ createReleaseDropdownTask.configure { def docsTask = tasks.register('docs', Sync) docsTask.configure { Sync it -> - it.dependsOn(combinedGroovydoc, createReleaseDropdownTask, ':grails-data-docs-stage:docs') + it.dependsOn(combinedGroovydoc, fixGroovydocLinks, createReleaseDropdownTask, ':grails-data-docs-stage:docs') it.group = 'documentation' def manualDocsDir = project.layout.buildDirectory.dir('modified-guide') diff --git a/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/Tokens.java b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/Tokens.java index 02499f8ae5d..ad8deed3f1a 100644 --- a/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/Tokens.java +++ b/grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/Tokens.java @@ -19,23 +19,24 @@ package org.grails.gsp.compiler; /** - * NOTE: Based on work done by on the GSP standalone project (https://gsp.dev.java.net/) + * NOTE: Based on work done by on the GSP standalone project + * (https://gsp.dev.java.net/) * * Interface defining an enumeration of tokens for the different scriptlet types * * @author Troy Heninger * @author Graeme Rocher * - * Date: Jan 10, 2004 + * Date: Jan 10, 2004 */ -interface Tokens { +public interface Tokens { int EOF = -1; int HTML = 0; - int JEXPR = 1; // <%= ... %> + int JEXPR = 1; // <%= ... %> int JSCRIPT = 2; // <% .... %> int JDIRECT = 3; // <%@ ... %> int JDECLAR = 4; // <%! ... %> - int GEXPR = 11; // ${ ... } + int GEXPR = 11; // ${ ... } int GSCRIPT = 12; // %{ ... }% int GDIRECT = 13; // @{ ... } int GDECLAR = 14; // !{ ... }!