This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch groovyism/web-databinding-taglib in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 2f76cec8ffa5bc5eeec58b53a0e9072abec60f2b Author: Walter Duque de Estrada <[email protected]> AuthorDate: Fri Oct 16 19:20:38 2026 -0500 refactor(web-taglib,web-databinding): idiomatic Groovy for the java-to-groovy conversion output Idiom pass over the Java-to-Groovy conversion output for grails-gsp/grails-web-taglib and grails-web-databinding. No behaviour or public API change. Applied: - Collection literals: new ArrayList/HashMap/HashSet/LinkedHashSet/LinkedHashMap -> []/[:]/ [] as Set - String equals -> == (Strings and ClassNode, which overrides equals() by text so == is identical) - map.get(k)/map.put(k,v) -> map[k]/map[k]=v where the return value is unused - list.get(i)/list.set(i,v) -> list[i]/list[i]=v - .contains(x) -> x in collection; Map.containsKey(k) -> k in map - Flow-typing cast removal after instanceof (locals/params, incl. within && chains and ternaries) - Safe navigation (x != null ? x.foo() : null -> x?.foo()) and elvis-assign (?=) for single-hop null guards where the original did not also tolerate a null second hop - String concatenation -> GString where the result lands in a String-typed slot - str.length() == 0 -> str.isEmpty(); size() > 0 -> !isEmpty() - Property syntax (getX()/isX() -> .x) only after checking for isX/getX collisions and subclass overrides on the receiver's type Deliberately left (Tier B exclusions / Tier C): - ConcurrentHashMap fields in BindingIncludeLists/DataBindingUtils: not literal-interchangeable with [:] (LinkedHashMap), would drop thread-safety - new ArrayList(existingCollection) copy-constructors: no literal equivalent - `x != null ? x : y` ternaries where x is a List/Set/Map: Elvis would also collapse an empty- but-non-null collection, which these call sites distinguish from null - GrailsWebDataBinder#getLocale, #ignoredBindingPropertyMessage, #missingNoArgConstructorMessage: left the surrounding ternary/concat structure as-is, only converted the inner accessor - Blind (non-instanceof-driven) casts left as explicit casts: no flow-typing basis - CompiledTagCallRewriter/LocalNameCollector/PageBindingCollector/TagLibArtefactTypeAstTransformation/ TagLibraryTransformer/ASTDatabindingHelper/DefaultASTDatabindingHelper: conservative on AST node getter property-syntax (left as explicit calls) given the identity/equals-contract risk flagged for AST transform classes; only safe, well-understood conversions (collection literals, String/ ClassNode equals->==, contains->in, flow-typing cast removal, GString merges) were applied - DataBindingLazyMetaPropertyMap: its put() override is the deliberate dynamic-dispatch mechanism for property-based data binding; only internal temp-variable construction was simplified, the dynamic dispatch itself (and every MetaClass/MetaProperty reflective call throughout MissingPropertyClearer, BindingIncludeLists, DefaultASTDatabindingHelper and GrailsWebDataBinder) was left untouched Unchanged (already idiomatic or nothing to convert): grails.gsp.TagLib, BindAllowed, InvalidRequestBodyException, DataBindingRuntimeHints, ASTDatabindingHelper, WebRequestOutputContext, MissingPropertyClearerSpec, DataBindingRuntimeHintsSpec. Verification: grails-web-taglib and grails-web-databinding compileGroovy/compileTestGroovy, codenarcMain/codenarcTest, checkstyleMain and full test all green (81/81 and 73/73 tests); javap dynamic-dispatch audit on every changed class shows only expected adapters (compareEqual/compareNotEqual from == conversions, isIn from `in`, createList/initMetaClass, and pre-existing MetaClass/MetaProperty reflective calls); no setGroovyObjectProperty/ getGroovyObjectProperty and no invokeMethodN traceable to a property-syntax conversion. Co-Authored-By: Claude Sonnet 5 <[email protected]> --- .../taglib/compiler/CompiledTagCallRewriter.groovy | 20 ++-- .../gsp/taglib/compiler/LocalNameCollector.groovy | 5 +- .../taglib/compiler/PageBindingCollector.groovy | 2 +- .../TagLibArtefactTypeAstTransformation.groovy | 10 +- .../web/taglib/TagLibraryTransformer.groovy | 6 +- .../org/grails/web/taglib/LayoutWriterStack.groovy | 12 +-- .../WebRequestTemplateVariableBinding.groovy | 70 ++++++------- .../taglib/encoder/WebOutputContextLookup.groovy | 50 ++------- .../grails/web/databinding/DataBindingUtils.groovy | 60 +++++------ .../web/databinding/GrailsWebDataBinder.groovy | 114 ++++++++++---------- .../web/databinding/MissingPropertyClearer.groovy | 90 ++++++++-------- .../web/databinding/BindingIncludeLists.groovy | 24 ++--- .../DataBindingLazyMetaPropertyMap.groovy | 12 +-- .../databinding/DefaultASTDatabindingHelper.groovy | 116 +++++++++++---------- 14 files changed, 275 insertions(+), 316 deletions(-) diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/CompiledTagCallRewriter.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/CompiledTagCallRewriter.groovy index 55be8a3dd4..1773b00c3e 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/CompiledTagCallRewriter.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/CompiledTagCallRewriter.groovy @@ -151,7 +151,7 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { // getMethods() reaches inherited methods, whose bodies belong to the class that declared // them. Rewriting one here would change a superclass through a subclass that happens to be // able to call tags. Trait methods are woven as declarations on this class and so remain. - if (method.getDeclaringClass() != null && !classNode.equals(method.getDeclaringClass())) { + if (method.getDeclaringClass() != null && classNode != method.getDeclaringClass()) { continue } if (method.getCode() != null && !method.isAbstract()) { @@ -164,7 +164,7 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { } } for (FieldNode field in classNode.getFields()) { - if (field.getDeclaringClass() != null && !classNode.equals(field.getDeclaringClass())) { + if (field.getDeclaringClass() != null && classNode != field.getDeclaringClass()) { continue } Expression initial = field.getInitialExpression() @@ -439,7 +439,7 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { * it are worth the same check as the ones written in an expression. */ private void validateMarkupTagCall(MethodCallExpression call) { - if (!page || !MARKUP_TAG_CALL.equals(call.getMethodAsString()) || + if (!page || MARKUP_TAG_CALL != call.getMethodAsString() || !(call.getArguments() instanceof TupleExpression)) { return } @@ -493,8 +493,8 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { // over code that is correct. return } - String message = "No such tag [$tagName] in namespace [$namespace]. Known tags: " + - String.join(', ', index.getTagNames(namespace)) + String message = "No such tag [$tagName] in namespace [$namespace]. " + + "Known tags: ${String.join(', ', index.getTagNames(namespace))}" // Collected rather than fatal, so that every misspelling in a file is reported at once instead // of one per build. GrailsASTUtils.error(sourceUnit, call, message, false) @@ -567,11 +567,11 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { * return type is boolean, from {@code isX()} as well, so both forms claim the name. */ private boolean hasGetter(String namespace) { - String capitalised = String.valueOf(Character.toUpperCase(namespace.charAt(0))) + namespace.substring(1) - if (!classNode.getMethods('get' + capitalised).isEmpty()) { + String capitalised = "${Character.toUpperCase(namespace.charAt(0))}${namespace.substring(1)}" + if (!classNode.getMethods("get$capitalised").isEmpty()) { return true } - for (MethodNode candidate in classNode.getMethods('is' + capitalised)) { + for (MethodNode candidate in classNode.getMethods("is$capitalised")) { ClassNode returnType = candidate.getReturnType() if (returnType != null && (ClassHelper.isPrimitiveBoolean(returnType) || ClassHelper.isWrapperBoolean(returnType))) { @@ -607,7 +607,7 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { private static boolean isGroovyPage(ClassNode classNode) { for (ClassNode current = classNode.getSuperClass(); current != null; current = current.getSuperClass()) { - if (GROOVY_PAGE_TYPE.equals(current.getName())) { + if (GROOVY_PAGE_TYPE == current.getName()) { return true } } @@ -621,7 +621,7 @@ class CompiledTagCallRewriter extends ClassCodeExpressionTransformer { private static boolean isCompileStatic(ClassNode classNode) { for (AnnotationNode annotation in classNode.getAnnotations()) { String name = annotation.getClassNode().getName() - if (COMPILE_STATIC_TYPE.equals(name) || GRAILS_COMPILE_STATIC_TYPE.equals(name)) { + if (name == COMPILE_STATIC_TYPE || name == GRAILS_COMPILE_STATIC_TYPE) { return true } } diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/LocalNameCollector.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/LocalNameCollector.groovy index b3e7b81bab..097fb09446 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/LocalNameCollector.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/LocalNameCollector.groovy @@ -50,7 +50,7 @@ final class LocalNameCollector extends CodeVisitorSupport { */ private static final String IMPLICIT_CLOSURE_PARAMETER = 'it' - private final Set<String> names = new HashSet<>() + private final Set<String> names = [] as Set private LocalNameCollector() { } @@ -84,8 +84,7 @@ final class LocalNameCollector extends CodeVisitorSupport { TupleExpression tuple = expression.getTupleExpression() for (Expression declared in tuple.getExpressions()) { if (declared instanceof VariableExpression) { - VariableExpression variable = (VariableExpression) declared - names.add(variable.getName()) + names.add(declared.getName()) } } } diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/PageBindingCollector.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/PageBindingCollector.groovy index af67c49501..afc99c6eee 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/PageBindingCollector.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/PageBindingCollector.groovy @@ -47,7 +47,7 @@ final class PageBindingCollector extends CodeVisitorSupport { private static final String SET_TAG = 'set' private static final String VAR_ATTRIBUTE = 'var' - private final Set<String> names = new HashSet<>() + private final Set<String> names = [] as Set private PageBindingCollector() { } diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/TagLibArtefactTypeAstTransformation.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/TagLibArtefactTypeAstTransformation.groovy index 3e3ddd162f..3fbc184d0f 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/TagLibArtefactTypeAstTransformation.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/grails/gsp/taglib/compiler/TagLibArtefactTypeAstTransformation.groovy @@ -68,9 +68,7 @@ class TagLibArtefactTypeAstTransformation extends ArtefactTypeAstTransformation // tags that nothing answers to at runtime. return } - File targetDirectory = sourceUnit.getConfiguration() != null ? - sourceUnit.getConfiguration().getTargetDirectory() : - null + File targetDirectory = sourceUnit.getConfiguration()?.getTargetDirectory() if (targetDirectory == null) { // In-memory compilation, as used by GSP unit tests and the shell, has nowhere to put the // descriptor; those callers resolve tags at runtime. @@ -145,9 +143,9 @@ class TagLibArtefactTypeAstTransformation extends ArtefactTypeAstTransformation if (field.isStatic()) { continue } - if (field.getType() != null && CLOSURE_TYPE.equals(field.getType())) { - String message = "Closure-based tag definition [${field.getName()}] in TagLib [" + - "${classNode.getName()}] is deprecated and is not resolved when a page is " + + if (field.getType() != null && CLOSURE_TYPE == field.getType()) { + String message = "Closure-based tag definition [${field.getName()}] in TagLib " + + "[${classNode.getName()}] is deprecated and is not resolved when a page is " + 'compiled, so calls to it stay dynamic. Define the tag as a method instead: ' + "def ${field.getName()}(Map attrs) { ... }" GrailsASTUtils.warning(sourceUnit, field, message) diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/compiler/web/taglib/TagLibraryTransformer.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/compiler/web/taglib/TagLibraryTransformer.groovy index 47f5c80520..62d2e6cd33 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/compiler/web/taglib/TagLibraryTransformer.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/compiler/web/taglib/TagLibraryTransformer.groovy @@ -206,9 +206,9 @@ class TagLibraryTransformer implements GrailsArtefactClassInjector, AnnotatedCla } private List<PropertyNode> findTags(ClassNode classNode) { - List<PropertyNode> tags = new ArrayList<>() + List<PropertyNode> tags = [] List<PropertyNode> properties = classNode.getProperties() - List<PropertyNode> potentialAliases = new ArrayList<>() + List<PropertyNode> potentialAliases = [] for (PropertyNode property in properties) { if (property.isPublic()) { Expression initialExpression = property.getInitialExpression() @@ -233,7 +233,7 @@ class TagLibraryTransformer implements GrailsArtefactClassInjector, AnnotatedCla String propertyName = pe.getName() PropertyNode property = classNode.getProperty(propertyName) - if (property != null && tags.contains(property)) { + if (property != null && property in tags) { potentialAlias.setType(CLOSURE_CLASS_NODE) tags.add(potentialAlias) } diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/LayoutWriterStack.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/LayoutWriterStack.groovy index d879575d13..61fa0300d9 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/LayoutWriterStack.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/LayoutWriterStack.groovy @@ -62,10 +62,10 @@ class LayoutWriterStack { static Writer currentWriter(String name) { Map<String, Object> writers = currentStack().stack.peek() if (writers != null) { - Writer result = (Writer) writers.get(name) + Writer result = (Writer) writers[name] if (result == null) { result = new StringWriter() - writers.put(name, result) + writers[name] = result } return result } @@ -89,15 +89,15 @@ class LayoutWriterStack { static Map<String, Object> writeParts(Closure<?> body) { LayoutWriterStack stack = LayoutWriterStack.currentStack() stack.push() - Map<String, Object> result = new HashMap<>() - result.put('body', body.call()) + Map<String, Object> result = [:] + result['body'] = body.call() result.putAll(stack.pop()) return result } private static LayoutWriterStack currentStack() { RequestAttributes attributes = RequestContextHolder.currentRequestAttributes() - if (attributes != null) { + if (attributes) { LayoutWriterStack stack = (LayoutWriterStack) attributes.getAttribute(ATTRIBUTE_NAME_WRITER_STACK, RequestAttributes.SCOPE_REQUEST) if (stack == null) { stack = new LayoutWriterStack() @@ -109,7 +109,7 @@ class LayoutWriterStack { } private void push() { - stack.push(new HashMap<>()) + stack.push([:]) } private Map<String, Object> pop() { diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/WebRequestTemplateVariableBinding.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/WebRequestTemplateVariableBinding.groovy index d3a5d1a949..2461f6b0c5 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/WebRequestTemplateVariableBinding.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/WebRequestTemplateVariableBinding.groovy @@ -38,79 +38,79 @@ class WebRequestTemplateVariableBinding extends AbstractTemplateVariableBinding private static Log log = LogFactory.getLog(WebRequestTemplateVariableBinding) private GrailsWebRequest webRequest private boolean developmentMode = Environment.isDevelopmentMode() - private Set<String> requestAttributeVariables = new HashSet<>() + private Set<String> requestAttributeVariables = [] as Set - private static Map<String, LazyRequestBasedValue> lazyRequestBasedValuesMap = new HashMap<>() + private static Map<String, LazyRequestBasedValue> lazyRequestBasedValuesMap = [:] static { Map<String, LazyRequestBasedValue> m = lazyRequestBasedValuesMap - m.put('webRequest', new LazyRequestBasedValue() { + m['webRequest'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest } - }) - m.put('request', new LazyRequestBasedValue() { + } + m['request'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getRequest() } - }) - m.put('response', new LazyRequestBasedValue() { + } + m['response'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getCurrentResponse() } - }) - m.put('flash', new LazyRequestBasedValue() { + } + m['flash'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getFlashScope() } - }) - m.put('application', new LazyRequestBasedValue() { + } + m['application'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getServletContext() } - }) + } // The same object as `application`, under the name the servlet API calls it. A page reading // servletContext got nothing at all before, since nothing bound the name. - m.put('servletContext', new LazyRequestBasedValue() { + m['servletContext'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getServletContext() } - }) - m.put('applicationContext', new LazyRequestBasedValue() { + } + m['applicationContext'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getAttributes().getApplicationContext() } - }) - m.put('grailsApplication', new LazyRequestBasedValue() { + } + m['grailsApplication'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getAttributes().getGrailsApplication() } - }) - m.put('session', new LazyRequestBasedValue() { + } + m['session'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getSession() } - }) - m.put('params', new LazyRequestBasedValue() { + } + m['params'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getParams() } - }) - m.put('actionName', new LazyRequestBasedValue() { + } + m['actionName'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getActionName() } - }) - m.put('namespace', new LazyRequestBasedValue() { + } + m['namespace'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getControllerNamespace() } - }) - m.put('controllerName', new LazyRequestBasedValue() { + } + m['controllerName'] = new LazyRequestBasedValue() { Object evaluate(GrailsWebRequest webRequest) { return webRequest.getControllerName() } - }) + } } WebRequestTemplateVariableBinding(GrailsWebRequest webRequest) { @@ -121,18 +121,18 @@ class WebRequestTemplateVariableBinding extends AbstractTemplateVariableBinding Binding binding = super.findBindingForVariable(name) if (binding == null) { if (webRequest.getRequest().getAttribute(name) != null) { - requestAttributeVariables.add(name) + requestAttributeVariables << name binding = this } } - if (binding == null && lazyRequestBasedValuesMap.containsKey(name)) { + if (binding == null && name in lazyRequestBasedValuesMap) { binding = this } return binding } boolean isRequestAttributeVariable(String name) { - return requestAttributeVariables.contains(name) + return name in requestAttributeVariables } boolean isVariableCachingAllowed(String name) { @@ -141,14 +141,14 @@ class WebRequestTemplateVariableBinding extends AbstractTemplateVariableBinding @Override Object getVariable(String name) { - Object val = getVariablesMap().get(name) - if (val == null && !getVariablesMap().containsKey(name) && webRequest != null) { + Object val = getVariablesMap()[name] + if (val == null && !(name in getVariablesMap()) && webRequest != null) { val = webRequest.getRequest().getAttribute(name) if (val != null) { - requestAttributeVariables.add(name) + requestAttributeVariables << name } else { - LazyRequestBasedValue lazyValue = lazyRequestBasedValuesMap.get(name) + LazyRequestBasedValue lazyValue = lazyRequestBasedValuesMap[name] if (lazyValue != null) { val = lazyValue.evaluate(webRequest) } diff --git a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/encoder/WebOutputContextLookup.groovy b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/encoder/WebOutputContextLookup.groovy index 3489322652..f46d5e8b1d 100644 --- a/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/encoder/WebOutputContextLookup.groovy +++ b/grails-gsp/grails-web-taglib/src/main/groovy/org/grails/web/taglib/encoder/WebOutputContextLookup.groovy @@ -59,28 +59,17 @@ class WebOutputContextLookup implements OutputContextLookup, Ordered { @Override EncodingStateRegistry getEncodingStateRegistry() { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - return grailsWebRequest.getEncodingStateRegistry() - } - return null + return lookupWebRequest()?.getEncodingStateRegistry() } @Override void setCurrentOutputEncodingStack(OutputEncodingStack outputEncodingStack) { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - grailsWebRequest.setAttribute(ATTRIBUTE_NAME_OUTPUT_STACK, outputEncodingStack, RequestAttributes.SCOPE_REQUEST) - } + lookupWebRequest()?.setAttribute(ATTRIBUTE_NAME_OUTPUT_STACK, outputEncodingStack, RequestAttributes.SCOPE_REQUEST) } @Override OutputEncodingStack getCurrentOutputEncodingStack() { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - return (OutputEncodingStack) grailsWebRequest.getAttribute(ATTRIBUTE_NAME_OUTPUT_STACK, RequestAttributes.SCOPE_REQUEST) - } - return null + return (OutputEncodingStack) lookupWebRequest()?.getAttribute(ATTRIBUTE_NAME_OUTPUT_STACK, RequestAttributes.SCOPE_REQUEST) } @Override @@ -90,10 +79,7 @@ class WebOutputContextLookup implements OutputContextLookup, Ordered { @Override void setCurrentWriter(Writer currentWriter) { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - grailsWebRequest.setOut(currentWriter) - } + lookupWebRequest()?.setOut(currentWriter) } @Override @@ -106,19 +92,12 @@ class WebOutputContextLookup implements OutputContextLookup, Ordered { @Override AbstractTemplateVariableBinding getBinding() { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest == null) { - return null - } - return (AbstractTemplateVariableBinding) grailsWebRequest.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE, RequestAttributes.SCOPE_REQUEST) + return (AbstractTemplateVariableBinding) lookupWebRequest()?.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE, RequestAttributes.SCOPE_REQUEST) } @Override void setBinding(AbstractTemplateVariableBinding binding) { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - grailsWebRequest.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, binding, RequestAttributes.SCOPE_REQUEST) - } + lookupWebRequest()?.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, binding, RequestAttributes.SCOPE_REQUEST) } @Override @@ -132,10 +111,7 @@ class WebOutputContextLookup implements OutputContextLookup, Ordered { @Override void setContentType(String contentType) { - HttpServletResponse httpServletResponse = lookupResponse() - if (httpServletResponse != null) { - httpServletResponse.setContentType(contentType) - } + lookupResponse()?.setContentType(contentType) } @Override @@ -150,17 +126,7 @@ class WebOutputContextLookup implements OutputContextLookup, Ordered { } protected HttpServletResponse lookupResponse() { - HttpServletResponse wrapped = WrappedResponseHolder.getWrappedResponse() - if (wrapped != null) { - return wrapped - } - else { - GrailsWebRequest grailsWebRequest = lookupWebRequest() - if (grailsWebRequest != null) { - return grailsWebRequest.getCurrentResponse() - } - } - return null + return WrappedResponseHolder.getWrappedResponse() ?: lookupWebRequest()?.getCurrentResponse() } } } diff --git a/grails-web-databinding/src/main/groovy/grails/web/databinding/DataBindingUtils.groovy b/grails-web-databinding/src/main/groovy/grails/web/databinding/DataBindingUtils.groovy index 0393ee9ee7..c8533c7fa9 100644 --- a/grails-web-databinding/src/main/groovy/grails/web/databinding/DataBindingUtils.groovy +++ b/grails-web-databinding/src/main/groovy/grails/web/databinding/DataBindingUtils.groovy @@ -99,9 +99,9 @@ class DataBindingUtils { } PersistentProperty prop = persistentEntity.getPropertyByName(propertyName) - if (prop != null && prop instanceof OneToOne && ((OneToOne) prop).isBidirectional()) { - Object val = source.get(key) - PersistentProperty otherSide = ((OneToOne) prop).getInverseSide() + if (prop != null && prop instanceof OneToOne && prop.isBidirectional()) { + Object val = source[key] + PersistentProperty otherSide = prop.getInverseSide() if (val != null && otherSide != null) { MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(val.getClass()) try { @@ -137,11 +137,11 @@ class DataBindingUtils { */ private static Class bindingType(final Object object) { final GrailsApplication application = Holders.findApplication() - if (application != null) { + if (application) { try { final MappingContext mappingContext = application.getMappingContext() - final ProxyHandler proxyHandler = mappingContext != null ? mappingContext.getProxyHandler() : null - if (proxyHandler != null && proxyHandler.isProxy(object)) { + final ProxyHandler proxyHandler = mappingContext?.getProxyHandler() + if (proxyHandler && proxyHandler.isProxy(object)) { final Class proxiedClass = proxyHandler.getProxiedClass(object) if (proxiedClass != null) { return proxiedClass @@ -200,21 +200,21 @@ class DataBindingUtils { try { Object constrainedProperties = metaClass.getProperty(object, 'constraintsMap') if (constrainedProperties instanceof Map) { - return (Map) constrainedProperties + return constrainedProperties } } catch (Exception ignored) { } try { Object constrainedProperties = metaClass.invokeMethod(object, 'getConstraintsMap', new Object[0]) if (constrainedProperties instanceof Map) { - return (Map) constrainedProperties + return constrainedProperties } } catch (Exception ignored) { } try { Object constrainedProperties = metaClass.getProperty(object, 'constraints') if (constrainedProperties instanceof Map) { - return (Map) constrainedProperties + return constrainedProperties } } catch (Exception ignored) { } @@ -304,12 +304,12 @@ class DataBindingUtils { newObject = targetType.getDeclaredConstructor().newInstance() } catch (NoSuchMethodException | InvocationTargetException ex) { throw new InstantiationException( - 'Could not instantiate class [' + targetType.getName() + ']: ' + ex.getMessage() + "Could not instantiate class [${targetType.getName()}]: ${ex.getMessage()}" ) } bindObjectToDomainInstance(entity, newObject, dataBindingSource, getBindingIncludeList(newObject), Collections.emptyList(), null, false, application) - collectionToPopulate.add(newObject) + collectionToPopulate << newObject } } @@ -320,7 +320,7 @@ class DataBindingUtils { } private static PersistentEntity findPersistentEntity(final GrailsApplication application, final String className) { - if (application != null) { + if (application) { try { return application.getMappingContext().getPersistentEntity(className) } catch (GrailsConfigurationException ignored) { @@ -457,7 +457,7 @@ class DataBindingUtils { if (targetMetaClass.hasProperty(object, 'errors') != null) { Object existingErrors = targetMetaClass.getProperty(object, 'errors') if (existingErrors instanceof BindingResult) { - clearMissingResult.addAllErrors((BindingResult) existingErrors) + clearMissingResult.addAllErrors(existingErrors) } } MissingPropertyClearer.clearMissingIncludedProperties( @@ -482,8 +482,8 @@ class DataBindingUtils { BindingResult newResult = new ValidationErrors(object) for (Object error in bindingResult.getAllErrors()) { if (error instanceof FieldError) { - FieldError fieldError = (FieldError) error - final boolean isBlank = BLANK.equals(fieldError.getRejectedValue()) + FieldError fieldError = error + final boolean isBlank = BLANK == fieldError.getRejectedValue() if (!isBlank) { newResult.addError(fieldError) } @@ -517,16 +517,14 @@ class DataBindingUtils { protected static String[] getMessageCodes(String messageCode, Class objectType) { - String[] codes = [objectType.getName() + '.' + messageCode, messageCode] as String[] + String[] codes = ["${objectType.getName()}.$messageCode", messageCode] as String[] return codes } static DataBindingSourceRegistry getDataBindingSourceRegistry(GrailsApplication grailsApplication) { final ContextBoundBeans beans = getContextBoundBeans(grailsApplication) - DataBindingSourceRegistry registry = beans == null ? null : beans.getDataBindingSourceRegistry() - if (registry == null) { - registry = new DefaultDataBindingSourceRegistry() - } + DataBindingSourceRegistry registry = beans?.getDataBindingSourceRegistry() + registry ?= new DefaultDataBindingSourceRegistry() return registry } @@ -552,7 +550,7 @@ class DataBindingUtils { static MimeTypeResolver getMimeTypeResolver( GrailsApplication grailsApplication) { final ContextBoundBeans beans = getContextBoundBeans(grailsApplication) - return beans == null ? null : beans.getMimeTypeResolver() + return beans?.getMimeTypeResolver() } static MimeType resolveMimeType(Object bindingSource, MimeTypeResolver mimeTypeResolver) { @@ -561,12 +559,10 @@ class DataBindingUtils { private static DataBinder getGrailsWebDataBinder(final GrailsApplication grailsApplication) { final ContextBoundBeans beans = getContextBoundBeans(grailsApplication) - DataBinder dataBinder = beans == null ? null : beans.getDataBinder() - if (dataBinder == null) { - // this should really never happen in the running app as the binder - // should always be found in the context - dataBinder = new GrailsWebDataBinder(grailsApplication) - } + DataBinder dataBinder = beans?.getDataBinder() + // this should really never happen in the running app as the binder + // should always be found in the context + dataBinder ?= new GrailsWebDataBinder(grailsApplication) return dataBinder } @@ -575,11 +571,11 @@ class DataBindingUtils { * @return the cached beans of the application's main context or null if there is no context to look beans up in */ private static ContextBoundBeans getContextBoundBeans(final GrailsApplication grailsApplication) { - if (grailsApplication == null) { + if (!grailsApplication) { return null } final ApplicationContext context = grailsApplication.getMainContext() - if (context == null) { + if (!context) { return null } ContextBoundBeans beans = contextBoundBeans @@ -592,10 +588,8 @@ class DataBindingUtils { @SuppressWarnings('unchecked') static Map convertPotentialGStrings(Map<Object, Object> args) { - Map newArgs = new HashMap(args.size()) - for (Map.Entry<Object, Object> entry : args.entrySet()) { - newArgs.put(unwrapGString(entry.getKey()), unwrapGString(entry.getValue())) - } + Map newArgs = [:] + args.each { key, value -> newArgs[unwrapGString(key)] = unwrapGString(value) } return newArgs } diff --git a/grails-web-databinding/src/main/groovy/grails/web/databinding/GrailsWebDataBinder.groovy b/grails-web-databinding/src/main/groovy/grails/web/databinding/GrailsWebDataBinder.groovy index 393b1566b2..e2f08e9c2d 100644 --- a/grails-web-databinding/src/main/groovy/grails/web/databinding/GrailsWebDataBinder.groovy +++ b/grails-web-databinding/src/main/groovy/grails/web/databinding/GrailsWebDataBinder.groovy @@ -83,7 +83,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { private static final Logger LOG = LoggerFactory.getLogger(GrailsWebDataBinder) private static final int MAX_WARNED_BINDING_SHAPES = 1024 - private static final Set<String> WARNED_BINDING_SHAPES = new LinkedHashSet<>() + private static final Set<String> WARNED_BINDING_SHAPES = [] as Set protected GrailsApplication grailsApplication protected MessageSource messageSource boolean trimStrings = true @@ -166,7 +166,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { } def target = object != null ? object.getClass().simpleName : 'unknown' def observation = Observation.createNotStarted('grails.databinding', observationRegistry) - .contextualName('grails.databinding ' + target) + .contextualName("grails.databinding $target") .lowCardinalityKeyValue('grails.databinding.target', target) .start() def observationScope = observation.openScope() @@ -184,7 +184,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { } private ObservationRegistry resolveObservationRegistry() { - def registry = this.observationRegistry + def registry = observationRegistry if (registry == null) { def ctx = grailsApplication?.mainContext if (ctx == null) { @@ -193,7 +193,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { return ObservationRegistry.NOOP } registry = ctx.getBeanProvider(ObservationRegistry).getIfAvailable({ -> ObservationRegistry.NOOP }) - this.observationRegistry = registry + observationRegistry = registry } return registry } @@ -248,7 +248,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { boolean allowed = super.isOkToBind(property, whiteList, blackList) if (!allowed && DataBindingUtils.isGeneratedBindingIncludeList(whiteList) && super.isOkToBind(property, null, blackList) && - !FrameworkPropertyNames.FRAMEWORK_MANAGED_PROPERTIES.contains(property.name)) { + !(property.name in FrameworkPropertyNames.FRAMEWORK_MANAGED_PROPERTIES)) { warnAboutIgnoredBindingProperty(bindingTargetType.get(), property.name) } allowed @@ -258,7 +258,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (!isBindingWarningEnabled() || targetType == null) { return } - String warningKey = targetType.name + '#' + propertyName + String warningKey = "${targetType.name}#${propertyName}" if (markBindingShapeWarned(warningKey)) { logBindingWarning(ignoredBindingPropertyMessage(targetType, propertyName)) } @@ -282,7 +282,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { private static boolean markBindingShapeWarned(String warningKey) { synchronized (WARNED_BINDING_SHAPES) { - if (WARNED_BINDING_SHAPES.contains(warningKey) || WARNED_BINDING_SHAPES.size() >= MAX_WARNED_BINDING_SHAPES) { + if (warningKey in WARNED_BINDING_SHAPES || WARNED_BINDING_SHAPES.size() >= MAX_WARNED_BINDING_SHAPES) { return false } WARNED_BINDING_SHAPES.add(warningKey) @@ -299,17 +299,17 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (domain != null && bindingResult != null) { def newResult = new ValidationErrors(obj) - for (Object error : bindingResult.getAllErrors()) { + for (Object error in bindingResult.getAllErrors()) { if (error instanceof FieldError) { - def fieldError = (FieldError) error - final boolean isBlank = ''.equals(fieldError.getRejectedValue()) + def fieldError = error + final boolean isBlank = '' == fieldError.rejectedValue if (!isBlank) { newResult.addError(fieldError) } else { - PersistentProperty prop = domain.getPropertyByName(fieldError.getField()) + PersistentProperty prop = domain.getPropertyByName(fieldError.field) if (prop != null) { - final boolean isOptional = prop.isNullable() + final boolean isOptional = prop.nullable if (!isOptional) { newResult.addError(fieldError) } @@ -343,15 +343,15 @@ class GrailsWebDataBinder extends SimpleDataBinder { def domainProperty = dc.getPropertyByName(name) if (domainProperty != null) { if (domainProperty instanceof Association) { - Association association = ((Association) domainProperty) - PersistentEntity entity = association.getAssociatedEntity() + Association association = domainProperty + PersistentEntity entity = association.associatedEntity if (entity != null) { - referencedType = entity.getJavaClass() - } else if (association.isBasic()) { - referencedType = ((Basic) association).getComponentType() + referencedType = entity.javaClass + } else if (association.basic) { + referencedType = ((Basic) association).componentType } } else if (domainProperty instanceof Simple) { - referencedType = domainProperty.getType() + referencedType = domainProperty.type } } } @@ -408,11 +408,11 @@ class GrailsWebDataBinder extends SimpleDataBinder { protected getIdentifierValueFrom(source) { def idValue = null - if (source instanceof DataBindingSource && ((DataBindingSource) source).hasIdentifier()) { - idValue = source.getIdentifierValue() + if (source instanceof DataBindingSource && source.hasIdentifier()) { + idValue = source.identifierValue } else if (source instanceof CharSequence) { idValue = source - } else if (source instanceof Map && ((Map) source).containsKey('id')) { + } else if (source instanceof Map && 'id' in source) { idValue = source['id'] } else if (source instanceof Number) { idValue = source.toString() @@ -450,10 +450,10 @@ class GrailsWebDataBinder extends SimpleDataBinder { boolean shouldBindNull = false if (val instanceof DataBindingSource) { // bind null if this binding source does contain an identifier - shouldBindNull = ((DataBindingSource) val).hasIdentifier() + shouldBindNull = val.hasIdentifier() } else if (val instanceof Map) { // bind null if this Map does contain an id - shouldBindNull = ((Map) val).containsKey('id') + shouldBindNull = 'id' in val } else if (idValue instanceof CharSequence) { // bind null if idValue is a CharSequence because it would have // to be 'null' or '' in order for control to be in this else block @@ -465,18 +465,18 @@ class GrailsWebDataBinder extends SimpleDataBinder { } } } else if (metaProperty.type.isArray() && val instanceof Collection && - !isBasicType(metaProperty.type.componentType) && ((Collection) val).any { + !isBasicType(metaProperty.type.componentType) && val.any { it instanceof Map || it instanceof DataBindingSource }) { needsBinding = false Class<?> componentType = metaProperty.type.componentType List boundItems = [] - ((Collection) val).each { item -> + val.each { item -> if (item == null || componentType.isAssignableFrom(item.getClass())) { boundItems << item } else if (item instanceof Map || item instanceof DataBindingSource) { DataBindingSource itemBindingSource = item instanceof DataBindingSource ? - (DataBindingSource) item : new SimpleMapDataBindingSource((Map) item) + item : new SimpleMapDataBindingSource((Map) item) def instance if (isDomainClass(componentType)) { def idValue = getIdentifierValueFrom(item) @@ -507,12 +507,12 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (referencedType) { List listValue if (val instanceof List) { - listValue = (List) val - } else if (val instanceof GPathResultMap && ((GPathResultMap) val).size() == 1) { - def mapValue = (GPathResultMap) val + listValue = val + } else if (val instanceof GPathResultMap && val.size() == 1) { + def mapValue = val def valueInMap = mapValue[mapValue.keySet()[0]] if (valueInMap instanceof List) { - listValue = (List) valueInMap + listValue = valueInMap } else { listValue = [valueInMap] } @@ -534,7 +534,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (persistentInstance != null) { DataBindingSource newBindingSource if (item instanceof DataBindingSource) { - newBindingSource = (DataBindingSource) item + newBindingSource = item } else { newBindingSource = new SimpleMapDataBindingSource((Map) item) } @@ -562,7 +562,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { itemsWhichNeedBinding << item } else if (item instanceof Map || item instanceof DataBindingSource) { DataBindingSource itemBindingSource = item instanceof DataBindingSource ? - (DataBindingSource) item : new SimpleMapDataBindingSource((Map) item) + item : new SimpleMapDataBindingSource((Map) item) def instance = instantiateAndBindNestedOrUseMapConstructor( referencedType, item, itemBindingSource, nestedIncludeList, listener) if (instance != null) { @@ -589,8 +589,8 @@ class GrailsWebDataBinder extends SimpleDataBinder { // target map in place (supports getter-only Map properties). if (listener == null || listener.beforeBinding(obj, propName, val, errors) != false) { try { - Map boundMap = new LinkedHashMap() - ((Map) val).each { key, item -> + Map boundMap = [:] + val.each { key, item -> if (item == null || referencedType.isAssignableFrom(item.getClass())) { boundMap[key] = item } else if (item instanceof Map || item instanceof DataBindingSource) { @@ -602,7 +602,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { } } DataBindingSource itemBindingSource = item instanceof DataBindingSource ? - (DataBindingSource) item : new SimpleMapDataBindingSource((Map) item) + item : new SimpleMapDataBindingSource((Map) item) if (instance == null) { instance = instantiateAndBindNestedOrUseMapConstructor( referencedType, item, itemBindingSource, nestedIncludeList, listener) @@ -631,8 +631,8 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (domainClass != null) { def property = domainClass.getPropertyByName(metaProperty.name) if (property != null && property instanceof Association) { - Association association = (Association) property - if (association.isBidirectional()) { + Association association = property + if (association.bidirectional) { def otherSide = association.inverseSide if (otherSide instanceof OneToOne) { val[otherSide.name] = obj @@ -657,7 +657,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (isBindAllIncludeList(includeList) || !DataBindingUtils.isDenyByDefaultEnabled()) { return newInstanceFromMapArguments(referencedType, - filterUnbindableMapConstructorArguments(referencedType, (Map) value)) + filterUnbindableMapConstructorArguments(referencedType, value)) } if (DataBindingUtils.isGeneratedBindingIncludeList(bindingIncludeList.get())) { warnAboutMissingNoArgConstructor(referencedType) @@ -691,7 +691,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (!isBindingWarningEnabled()) { return } - String warningKey = targetType.name + '#no-arg-constructor' + String warningKey = "${targetType.name}#no-arg-constructor" if (markBindingShapeWarned(warningKey)) { logBindingWarning(missingNoArgConstructorMessage(targetType)) } @@ -799,7 +799,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { map = initializeMap(obj, propName) def persistedInstance = getPersistentInstance(referencedType, idValue) if (persistedInstance != null) { - if (map.size() < autoGrowCollectionLimit || map.containsKey(indexedPropertyReferenceDescriptor.index)) { + if (map.size() < autoGrowCollectionLimit || indexedPropertyReferenceDescriptor.index in map) { map[indexedPropertyReferenceDescriptor.index] = persistedInstance if (val instanceof Map) { bind(persistedInstance, new SimpleMapDataBindingSource(val), listener) @@ -835,8 +835,8 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (domainClass != null) { def property = domainClass.getPropertyByName(propertyName) if (property != null && property instanceof Association) { - Association association = (Association) property - if (association.isBidirectional()) { + Association association = property + if (association.bidirectional) { def otherSide = association.inverseSide if (otherSide instanceof ManyToOne) { val[otherSide.name] = obj @@ -853,14 +853,14 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (metaProp != null) { Object constrainedPropsObj = getMetaPropertyValue(metaProp, object) if (constrainedPropsObj instanceof Map) { - constrainedProperties = (Map) constrainedPropsObj + constrainedProperties = constrainedPropsObj } } constrainedProperties } private getMetaPropertyValue(MetaProperty metaProperty, delegate) { if (metaProperty instanceof ThreadManagedMetaBeanProperty) { - return ((ThreadManagedMetaBeanProperty) metaProperty).getGetter().invoke(delegate, MetaClassHelper.EMPTY_ARRAY) + return metaProperty.getter.invoke(delegate, MetaClassHelper.EMPTY_ARRAY) } return metaProperty.getProperty(delegate) @@ -900,7 +900,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { isSet = addElementToCollection(obj, propName, property, propertyValue, true) } else if (propertyValue instanceof String[]) { if (property instanceof Association) { - Association association = (Association) property + Association association = property if (association.associatedEntity != null) { propertyValue.each { val -> boolean clearCollection = !isSet @@ -913,17 +913,17 @@ class GrailsWebDataBinder extends SimpleDataBinder { } PersistentProperty otherSide if (property instanceof Association) { - if (((Association) property).bidirectional) { - otherSide = ((Association) property).inverseSide + if (property.bidirectional) { + otherSide = property.inverseSide } } - if (otherSide != null && List.isAssignableFrom(otherSide.getType())) { + if (otherSide != null && List.isAssignableFrom(otherSide.type)) { DeferredBindingActions.addBindingAction(new Runnable() { void run() { if (obj[propName] != null && otherSide instanceof OneToMany) { Collection collection = GrailsMetaClassUtils.getPropertyIfExists(obj[propName], otherSide.name, Collection) - if (collection == null || !collection.contains(obj)) { - def methodName = 'addTo' + GrailsNameUtils.getClassName(otherSide.name) + if (collection == null || !(obj in collection)) { + def methodName = "addTo${GrailsNameUtils.getClassName(otherSide.name)}" GrailsMetaClassUtils.invokeMethodIfExists(obj[propName], methodName, [obj] as Object[]) } } @@ -983,8 +983,8 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (nestedIncludeList) { return generatedIncludeList ? DataBindingUtils.asGeneratedBindingIncludeList(nestedIncludeList) : nestedIncludeList } - if (generatedIncludeList && !includeList.contains(propertyName + '.*') && - !includeList.contains(propertyName + '_*')) { + if (generatedIncludeList && !(propertyName + '.*' in includeList) && + !(propertyName + '_*' in includeList)) { return DataBindingUtils.asGeneratedBindingIncludeList( [DefaultASTDatabindingHelper.NO_BINDABLE_PROPERTIES]) } @@ -1008,7 +1008,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (trimStrings) { stringValue = stringValue.trim() } - if (convertEmptyStringsToNull && ''.equals(stringValue)) { + if (convertEmptyStringsToNull && '' == stringValue) { stringValue = null } return stringValue @@ -1024,7 +1024,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { if (domainClass != null) { def property = domainClass.getPropertyByName(propName) if (property != null && property instanceof Association) { - Association association = ((Association) property) + Association association = property if (association.bidirectional) { def otherSide = association.inverseSide if (otherSide instanceof ManyToOne) { @@ -1074,7 +1074,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { @Autowired(required=false) void setDataBindingListeners(DataBindingListener[] listeners) { - this.listeners.addAll(Arrays.asList(listeners)) + this.listeners.addAll(listeners.toList()) } @Override @@ -1103,7 +1103,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { assert annotation instanceof BindingFormat def code if (annotation instanceof BindingFormat) { - code = ((BindingFormat) annotation).code() + code = annotation.code() } def formatString if (code) { @@ -1118,7 +1118,7 @@ class GrailsWebDataBinder extends SimpleDataBinder { protected Locale getLocale() { def request = GrailsWebRequest.lookup() - request ? request.getLocale() : Locale.getDefault() + request ? request.locale : Locale.getDefault() } private PersistentEntity getPersistentEntity(Class clazz) { diff --git a/grails-web-databinding/src/main/groovy/grails/web/databinding/MissingPropertyClearer.groovy b/grails-web-databinding/src/main/groovy/grails/web/databinding/MissingPropertyClearer.groovy index 552ce52b1e..3c58be2f5e 100644 --- a/grails-web-databinding/src/main/groovy/grails/web/databinding/MissingPropertyClearer.groovy +++ b/grails-web-databinding/src/main/groovy/grails/web/databinding/MissingPropertyClearer.groovy @@ -78,7 +78,7 @@ final class MissingPropertyClearer { } private static List expandWildcardIncludes(Object object, List include) { - List expandedInclude = new ArrayList() + List expandedInclude = [] for (Object includedProperty in include) { if (!(includedProperty instanceof CharSequence)) { expandedInclude.add(includedProperty) @@ -102,13 +102,13 @@ final class MissingPropertyClearer { Object nestedObject = getPropertyValue(object, propertyPath) if (nestedObject instanceof Collection) { int index = 0 - for (Object item in (Collection) nestedObject) { + for (Object item in nestedObject) { expandObjectProperties(item, propertyPath + '[' + index + ']', expandedInclude) index++ } } else if (nestedObject instanceof Map) { - for (Object entryObject in ((Map) nestedObject).entrySet()) { + for (Object entryObject in nestedObject.entrySet()) { Map.Entry entry = (Map.Entry) entryObject expandObjectProperties(entry.getValue(), propertyPath + '[' + entry.getKey() + ']', expandedInclude) } @@ -162,7 +162,7 @@ final class MissingPropertyClearer { Object nestedObject = getPropertyValue(object, propertyName.substring(0, separator)) String nestedPropertyName = propertyName.substring(separator + 1) if (nestedObject instanceof Collection) { - for (Object item in (Collection) nestedObject) { + for (Object item in nestedObject) { if (item != null && !isClearMissingPropertyBindable(item, nestedPropertyName, getNestedIncludeList(include, propertyName), null)) { return false } @@ -170,7 +170,7 @@ final class MissingPropertyClearer { return true } if (nestedObject instanceof Map) { - for (Object value in ((Map) nestedObject).values()) { + for (Object value in nestedObject.values()) { if (value != null && !isClearMissingPropertyBindable(value, nestedPropertyName, getNestedIncludeList(include, propertyName), null)) { return false } @@ -188,7 +188,7 @@ final class MissingPropertyClearer { if (propertyNames == null) { return Collections.emptyList() } - List normalizedPropertyNames = new ArrayList(propertyNames.size()) + List normalizedPropertyNames = [] for (Object propertyName in propertyNames) { normalizedPropertyNames.add(propertyName instanceof CharSequence ? removePropertyIndexes(propertyName.toString()) : propertyName) } @@ -205,12 +205,12 @@ final class MissingPropertyClearer { return Collections.emptyList() } String rootPropertyName = normalizedPropertyName.substring(0, separator) - List nestedIncludeList = new ArrayList() + List nestedIncludeList = [] for (Object includedProperty in include) { if (includedProperty instanceof CharSequence) { String includedPropertyName = removePropertyIndexes(includedProperty.toString()) int includedPropertySeparator = propertyPathSeparator(includedPropertyName) - if (includedPropertySeparator != -1 && rootPropertyName.equals(includedPropertyName.substring(0, includedPropertySeparator))) { + if (includedPropertySeparator != -1 && rootPropertyName == includedPropertyName.substring(0, includedPropertySeparator)) { nestedIncludeList.add(includedPropertyName.substring(includedPropertySeparator + 1)) } } @@ -223,8 +223,8 @@ final class MissingPropertyClearer { return false } for (Object item in excludeList) { - String excludeName = item == null ? null : item.toString() - if (excludeName != null && (excludeName.equals(propertyName) || propertyName.startsWith(excludeName + '.') || + String excludeName = item?.toString() + if (excludeName != null && (excludeName == propertyName || propertyName.startsWith(excludeName + '.') || (excludeName.endsWith('.*') && propertyName.startsWith(excludeName.substring(0, excludeName.length() - 1))) || (excludeName.endsWith('_*') && propertyName.startsWith(excludeName.substring(0, excludeName.length() - 1))))) { return true @@ -244,7 +244,7 @@ final class MissingPropertyClearer { private static boolean isIntrinsicRuntimeProperty(String propertyName) { int separator = propertyPathSeparator(propertyName) String rootPropertyName = separator == -1 ? propertyName : propertyName.substring(0, separator) - return FrameworkPropertyNames.INTRINSIC_RUNTIME_PROPERTIES.contains(rootPropertyName) + return rootPropertyName in FrameworkPropertyNames.INTRINSIC_RUNTIME_PROPERTIES } private static boolean isClearMissingPropertyIncluded(String propertyName, List includeList) { @@ -254,7 +254,7 @@ final class MissingPropertyClearer { for (Object includedProperty in includeList) { if (includedProperty instanceof CharSequence) { String includedPropertyName = removePropertyIndexes(includedProperty.toString()) - if (includedPropertyName.equals(propertyName)) { + if (includedPropertyName == propertyName) { return true } if (includedPropertyName.endsWith('.*')) { @@ -306,11 +306,11 @@ final class MissingPropertyClearer { if (containsSourceProperty(source, sourceRootPropertyName)) { Object nestedSource = getSourcePropertyValue(source, sourceRootPropertyName) if (nestedSource instanceof Collection) { - return assignNullToMissingCollectionProperties(object, (Collection) nestedSource, targetPathPrefix, targetRootPropertyName, nestedSourcePropertyName, nestedTargetPropertyName) + return assignNullToMissingCollectionProperties(object, nestedSource, targetPathPrefix, targetRootPropertyName, nestedSourcePropertyName, nestedTargetPropertyName) } Object targetObject = getTargetObject(object, targetPathPrefix) - if (nestedSource instanceof Map && hasNestedSourceEntries((Map) nestedSource) && shouldExpandMapEntries(targetObject, targetObject == null ? null : targetObject.getClass(), targetRootPropertyName)) { - return assignNullToMissingMapProperties(object, (Map) nestedSource, targetPathPrefix, targetRootPropertyName, nestedSourcePropertyName, nestedTargetPropertyName) + if (nestedSource instanceof Map && hasNestedSourceEntries(nestedSource) && shouldExpandMapEntries(targetObject, targetObject == null ? null : targetObject.getClass(), targetRootPropertyName)) { + return assignNullToMissingMapProperties(object, nestedSource, targetPathPrefix, targetRootPropertyName, nestedSourcePropertyName, nestedTargetPropertyName) } } @@ -499,7 +499,7 @@ final class MissingPropertyClearer { } private static Set<String> getIndexedSourcePropertyNames(Object source, String indexedSourcePropertyPrefix) { - Set<String> indexedSourcePropertyNames = new LinkedHashSet<>() + Set<String> indexedSourcePropertyNames = [] as Set for (String propertyName in getSourcePropertyNames(source)) { if (propertyName.startsWith(indexedSourcePropertyPrefix)) { int closingIndex = propertyName.indexOf(']', indexedSourcePropertyPrefix.length()) @@ -513,21 +513,21 @@ final class MissingPropertyClearer { private static boolean containsSourceProperty(Object source, String propertyName) { if (source instanceof DataBindingSource) { - return ((DataBindingSource) source).containsProperty(propertyName) + return source.containsProperty(propertyName) } if (source instanceof Map) { - return ((Map) source).containsKey(propertyName) + return propertyName in source } return false } private static Set<String> getSourcePropertyNames(Object source) { - Set<String> propertyNames = new LinkedHashSet<>() + Set<String> propertyNames = [] as Set if (source instanceof DataBindingSource) { - propertyNames.addAll(((DataBindingSource) source).getPropertyNames()) + propertyNames.addAll(source.getPropertyNames()) } else if (source instanceof Map) { - for (Object key in ((Map) source).keySet()) { + for (Object key in source.keySet()) { propertyNames.add(key.toString()) } } @@ -536,9 +536,9 @@ final class MissingPropertyClearer { private static Object getSourcePropertyValue(Object source, String propertyName) { if (source instanceof DataBindingSource) { - return ((DataBindingSource) source).getPropertyValue(propertyName) + return source.getPropertyValue(propertyName) } - return ((Map) source).get(propertyName) + return ((Map) source)[propertyName] } private static String checkboxMarkerPropertyName(String propertyName) { @@ -587,7 +587,7 @@ final class MissingPropertyClearer { !Enum.isAssignableFrom(valueType) && !Map.isAssignableFrom(valueType) && !Collection.isAssignableFrom(valueType) && - !Object.equals(valueType) + valueType != Object } private static Class getMapValueType(Object target, Class targetType, String propertyName) { @@ -614,16 +614,16 @@ final class MissingPropertyClearer { return null } - Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments() + Type[] typeArguments = type.getActualTypeArguments() if (typeArguments.length < 2) { return null } Type valueType = typeArguments[1] if (valueType instanceof Class) { - return (Class) valueType + return valueType } - if (valueType instanceof ParameterizedType && ((ParameterizedType) valueType).getRawType() instanceof Class) { - return (Class) ((ParameterizedType) valueType).getRawType() + if (valueType instanceof ParameterizedType && valueType.getRawType() instanceof Class) { + return (Class) valueType.getRawType() } return null } @@ -642,7 +642,7 @@ final class MissingPropertyClearer { } private static Object getTargetObject(Object object, String targetPathPrefix) { - if (targetPathPrefix == null || targetPathPrefix.length() == 0) { + if (targetPathPrefix == null || targetPathPrefix.isEmpty()) { return object } @@ -671,7 +671,7 @@ final class MissingPropertyClearer { } private static String appendPropertyPath(String parentPath, String propertyName) { - if (parentPath == null || parentPath.length() == 0) { + if (parentPath == null || parentPath.isEmpty()) { return propertyName } return parentPath + '.' + propertyName @@ -720,12 +720,12 @@ final class MissingPropertyClearer { private static Object getIndexedValue(Object indexedProperty, String index) { if (indexedProperty instanceof List) { - List list = (List) indexedProperty + List list = indexedProperty Integer parsedIndex = parseIndex(index) - return parsedIndex != null && parsedIndex >= 0 && parsedIndex < list.size() ? list.get(parsedIndex) : null + return parsedIndex != null && parsedIndex >= 0 && parsedIndex < list.size() ? list[parsedIndex] : null } if (indexedProperty instanceof Map) { - return ((Map) indexedProperty).get(index) + return indexedProperty[index] } return null } @@ -736,7 +736,7 @@ final class MissingPropertyClearer { if (bracket == -1) { MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()) MetaProperty metaProperty = mc.hasProperty(object, propertyName) - if (metaProperty != null) { + if (metaProperty) { mc.setProperty(object, propertyName, metaProperty.getType().isPrimitive() ? primitiveDefault(metaProperty.getType()) : null) } @@ -747,14 +747,14 @@ final class MissingPropertyClearer { Object indexedProperty = mc.getProperty(object, propertyName.substring(0, bracket)) String index = propertyName.substring(bracket + 1, propertyName.indexOf(']', bracket)) if (indexedProperty instanceof List) { - List list = (List) indexedProperty + List list = indexedProperty Integer parsedIndex = parseIndex(index) if (parsedIndex != null && parsedIndex >= 0 && parsedIndex < list.size()) { - list.set(parsedIndex, null) + list[parsedIndex] = null } } else if (indexedProperty instanceof Map) { - ((Map) indexedProperty).put(index, null) + indexedProperty[index] = null } } catch (RuntimeException e) { @@ -775,28 +775,28 @@ final class MissingPropertyClearer { } private static Object primitiveDefault(Class primitiveType) { - if (Boolean.TYPE.equals(primitiveType)) { + if (Boolean.TYPE == primitiveType) { return false } - if (Character.TYPE.equals(primitiveType)) { + if (Character.TYPE == primitiveType) { return Character.valueOf('\0'.charAt(0)) } - if (Byte.TYPE.equals(primitiveType)) { + if (Byte.TYPE == primitiveType) { return Byte.valueOf((byte) 0) } - if (Short.TYPE.equals(primitiveType)) { + if (Short.TYPE == primitiveType) { return Short.valueOf((short) 0) } - if (Integer.TYPE.equals(primitiveType)) { + if (Integer.TYPE == primitiveType) { return Integer.valueOf(0) } - if (Long.TYPE.equals(primitiveType)) { + if (Long.TYPE == primitiveType) { return Long.valueOf(0L) } - if (Float.TYPE.equals(primitiveType)) { + if (Float.TYPE == primitiveType) { return Float.valueOf(0F) } - if (Double.TYPE.equals(primitiveType)) { + if (Double.TYPE == primitiveType) { return Double.valueOf(0D) } return null diff --git a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/BindingIncludeLists.groovy b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/BindingIncludeLists.groovy index 10b0eacd12..549d885229 100644 --- a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/BindingIncludeLists.groovy +++ b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/BindingIncludeLists.groovy @@ -65,7 +65,7 @@ final class BindingIncludeLists { // getter a superclass declares answers for the instance, so its map is the one to bind with. final Traits.TraitBridge traitBridge = accessor.getAnnotation(Traits.TraitBridge) return accessor.getDeclaringClass() != type && Modifier.isStatic(accessor.getModifiers()) && - traitBridge != null && 'grails.validation.Validateable'.equals(traitBridge.traitClass().getName()) + traitBridge != null && traitBridge.traitClass().getName() == 'grails.validation.Validateable' } catch (NoSuchMethodException | SecurityException ignored) { return false } @@ -102,7 +102,7 @@ final class BindingIncludeLists { List includeList = null try { if (includeListCache.containsKey(type)) { - includeList = includeListCache.get(type) + includeList = includeListCache[type] if (includeList == NO_BINDING_INCLUDE_LIST) { includeList = null } @@ -125,7 +125,7 @@ final class BindingIncludeLists { } } else if (defaultWhiteListField != null) { final List generatedIncludeList = getStaticListFieldValue(defaultWhiteListField) - final Collection combinedIncludeList = new LinkedHashSet() + final Collection combinedIncludeList = [] as Set if (generatedIncludeList != null) { combinedIncludeList.addAll(generatedIncludeList) } @@ -138,7 +138,7 @@ final class BindingIncludeLists { includeList = asGenerated(includeList) } if (!Environment.getCurrent().isReloadEnabled()) { - includeListCache.put(type, includeList == null ? NO_BINDING_INCLUDE_LIST : includeList) + includeListCache[type] = includeList == null ? NO_BINDING_INCLUDE_LIST : includeList } } } catch (Exception ignored) { @@ -160,9 +160,9 @@ final class BindingIncludeLists { if (includeList == null) { return null } - final List<String> names = new ArrayList<>() + final List<String> names = [] for (Object name in includeList) { - if (name != null && !DefaultASTDatabindingHelper.NO_BINDABLE_PROPERTIES.equals(name)) { + if (name != null && name != DefaultASTDatabindingHelper.NO_BINDABLE_PROPERTIES) { names.add(name.toString()) } } @@ -178,7 +178,7 @@ final class BindingIncludeLists { return resolveDenyByDefault( application.getConfig().getProperty(Settings.DATABINDING_DENY_BY_DEFAULT, Object, null)) } - return resolveDenyByDefault(Holders.getFlatConfig().get(Settings.DATABINDING_DENY_BY_DEFAULT)) + return resolveDenyByDefault(Holders.getFlatConfig()[Settings.DATABINDING_DENY_BY_DEFAULT]) } /** @@ -250,7 +250,7 @@ final class BindingIncludeLists { * explicit include list naming them. */ static List<String> unbindablePropertyNames(final Class type) { - final List<String> names = new ArrayList<>() + final List<String> names = [] for (Object name in propertyNamesWithBindableValue(constrainedProperties(type), Boolean.FALSE)) { names.add(name.toString()) } @@ -261,13 +261,13 @@ final class BindingIncludeLists { if (constrainedProperties == null || constrainedProperties.isEmpty()) { return Collections.emptyList() } - final List propertyNames = new ArrayList() + final List propertyNames = [] for (Object entryObject in constrainedProperties.entrySet()) { Map.Entry entry = (Map.Entry) entryObject - if (bindableValue.equals(bindableConstraintValue(entry.getValue()))) { + if (bindableValue == bindableConstraintValue(entry.getValue())) { String propertyName = String.valueOf(entry.getKey()) propertyNames.add(propertyName) - if (Boolean.TRUE.equals(bindableValue) && !isSimpleType(constrainedPropertyType(entry.getValue()))) { + if (Boolean.TRUE == bindableValue && !isSimpleType(constrainedPropertyType(entry.getValue()))) { propertyNames.add(propertyName + '_*') propertyNames.add(propertyName + '.*') } @@ -348,7 +348,7 @@ final class BindingIncludeLists { try { Object metaConstraints = metaClass.getProperty(constrainedProperty, 'metaConstraints') if (metaConstraints instanceof Map) { - return ((Map) metaConstraints).get(DefaultASTDatabindingHelper.BINDABLE_CONSTRAINT_NAME) + return metaConstraints[DefaultASTDatabindingHelper.BINDABLE_CONSTRAINT_NAME] } } catch (Exception ignored) { } diff --git a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DataBindingLazyMetaPropertyMap.groovy b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DataBindingLazyMetaPropertyMap.groovy index faddee31d8..49da5649b7 100644 --- a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DataBindingLazyMetaPropertyMap.groovy +++ b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DataBindingLazyMetaPropertyMap.groovy @@ -45,17 +45,17 @@ class DataBindingLazyMetaPropertyMap extends LazyMetaPropertyMap { @Override Object put(Object propertyName, Object propertyValue) { if (propertyName instanceof List) { - DataBindingUtils.bindObjectToInstance(getInstance(), propertyValue, (List) propertyName, null, null) + DataBindingUtils.bindObjectToInstance(getInstance(), propertyValue, propertyName, null, null) } else { final Map bindingSource if (propertyValue instanceof Map) { - bindingSource = (Map) propertyValue + bindingSource = propertyValue } else { - bindingSource = new HashMap() - bindingSource.put(propertyName, propertyValue) + bindingSource = [:] + bindingSource[propertyName] = propertyValue } - List propertyNames = new ArrayList() - propertyNames.add(propertyName) + List propertyNames = [] + propertyNames << propertyName DataBindingUtils.bindObjectToInstance(getInstance(), bindingSource, propertyNames, null, null) } return null diff --git a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DefaultASTDatabindingHelper.groovy b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DefaultASTDatabindingHelper.groovy index 8be09e90c2..c1e74a8667 100644 --- a/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DefaultASTDatabindingHelper.groovy +++ b/grails-web-databinding/src/main/groovy/org/grails/web/databinding/DefaultASTDatabindingHelper.groovy @@ -45,11 +45,11 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { public static final String DEFAULT_DATABINDING_WHITELIST = '\$defaultDatabindingWhiteList' public static final String LEGACY_DATABINDING_WHITELIST = '\$legacyDatabindingWhiteList' public static final String NO_BINDABLE_PROPERTIES = '\$_NO_BINDABLE_PROPERTIES_\$' - private static Map<ClassNode, Set<String>> CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES = new HashMap<>() + private static Map<ClassNode, Set<String>> CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES = [:] - private static Map<ClassNode, Set<String>> CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES = new HashMap<>() + private static Map<ClassNode, Set<String>> CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES = [:] - private static Map<ClassNode, Set<String>> CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES = new HashMap<>() + private static Map<ClassNode, Set<String>> CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES = [:] private static final List<ClassNode> SIMPLE_TYPES = [ new ClassNode(Boolean), @@ -96,7 +96,7 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { private void addWhitelistField(final ClassNode classNode, final String fieldName, final Set<String> propertyNamesToIncludeInWhiteList, final boolean denyWhenEmpty) { final ListExpression listExpression = new ListExpression() - if (propertyNamesToIncludeInWhiteList.size() > 0) { + if (!propertyNamesToIncludeInWhiteList.isEmpty()) { for (String propertyName in propertyNamesToIncludeInWhiteList) { listExpression.addExpression(new ConstantExpression(propertyName)) @@ -105,7 +105,7 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { if (declaredField != null) { final ClassNode type = declaredField.getType() if (type != null) { - isSimpleType = SIMPLE_TYPES.contains(type) + isSimpleType = type in SIMPLE_TYPES } } if (!isSimpleType) { @@ -125,7 +125,7 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { private FieldNode getDeclaredFieldInInheritanceHierarchy(final ClassNode classNode, String propertyName) { FieldNode fieldNode = classNode.getDeclaredField(propertyName) if (fieldNode == null) { - if (!classNode.getSuperClass().equals(new ClassNode(Object))) { + if (classNode.getSuperClass() != new ClassNode(Object)) { return getDeclaredFieldInInheritanceHierarchy(classNode.getSuperClass(), propertyName) } } @@ -135,7 +135,7 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { private Set<String> getPropertyNamesToIncludeInWhiteListForParentClass(final SourceUnit sourceUnit, final ClassNode parentClassNode) { final Set<String> propertyNames if (CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES.containsKey(parentClassNode)) { - propertyNames = CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES.get(parentClassNode) + propertyNames = CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES[parentClassNode] } else { propertyNames = getPropertyNamesToIncludeInWhiteList(sourceUnit, parentClassNode) } @@ -146,22 +146,22 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { if (!CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES.containsKey(parentClassNode)) { getPropertyNamesToIncludeInWhiteList(sourceUnit, parentClassNode) } - final Set<String> explicitlyBindable = CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES.get(parentClassNode) - return explicitlyBindable != null ? explicitlyBindable : new HashSet<>() + final Set<String> explicitlyBindable = CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES[parentClassNode] + return explicitlyBindable != null ? explicitlyBindable : ([] as Set) } private Set<String> getPropertyNamesToIncludeInWhiteList(final SourceUnit sourceUnit, final ClassNode classNode) { - final Set<String> propertyNamesToIncludeInWhiteList = new HashSet<>() - final Set<String> unbindablePropertyNames = new HashSet<>() - final Set<String> bindablePropertyNames = new HashSet<>() + final Set<String> propertyNamesToIncludeInWhiteList = [] as Set + final Set<String> unbindablePropertyNames = [] as Set + final Set<String> bindablePropertyNames = [] as Set // Special properties (id/version/dateCreated/lastUpdated) made bindable via an explicit constraint // somewhere in the class hierarchy. These are tracked separately so the inherited-whitelist filter // below can tell an explicit bindable: true from a special property that merely landed in a non-domain // parent's whitelist by default (for example id/version injected onto a @DirtyCheck base class). - final Set<String> explicitlyBindableSpecialPropertyNames = new HashSet<>() + final Set<String> explicitlyBindableSpecialPropertyNames = [] as Set final boolean isDomainClass = GrailsASTUtils.isDomainClass(classNode, sourceUnit) - if (!classNode.getSuperClass().equals(new ClassNode(Object))) { + if (classNode.getSuperClass() != new ClassNode(Object)) { final Set<String> parentClassPropertyNames = getPropertyNamesToIncludeInWhiteListForParentClass(sourceUnit, classNode.getSuperClass()) final Set<String> parentExplicitlyBindableSpecialPropertyNames = getExplicitlyBindableSpecialPropertyNamesForParentClass(sourceUnit, classNode.getSuperClass()) explicitlyBindableSpecialPropertyNames.addAll(parentExplicitlyBindableSpecialPropertyNames) @@ -169,8 +169,8 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { // A domain class never binds its special properties (id/version/dateCreated/lastUpdated) by // default, so don't inherit them from a non-domain parent such as a @DirtyCheck base class. // An explicit bindable: true constraint declared up the hierarchy is honoured, however. - if (isDomainClass && DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(parentPropertyName) && - !parentExplicitlyBindableSpecialPropertyNames.contains(parentPropertyName)) { + if (isDomainClass && parentPropertyName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT && + !(parentPropertyName in parentExplicitlyBindableSpecialPropertyNames)) { continue } bindablePropertyNames.add(parentPropertyName) @@ -189,20 +189,20 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { final Map<String, Expression> mapEntryExpressions = constraintConfig.getValue() for (Map.Entry<String, Expression> entry in mapEntryExpressions.entrySet()) { final String constraintName = entry.getKey() - if (BINDABLE_CONSTRAINT_NAME.equals(constraintName)) { + if (constraintName == BINDABLE_CONSTRAINT_NAME) { final Expression valueExpression = entry.getValue() Boolean bindableValue = null if (valueExpression instanceof ConstantExpression) { - final Object constantValue = ((ConstantExpression) valueExpression).getValue() + final Object constantValue = valueExpression.getValue() if (constantValue instanceof Boolean) { - bindableValue = (Boolean) constantValue + bindableValue = constantValue } } if (bindableValue != null) { - if (Boolean.TRUE.equals(bindableValue)) { + if (Boolean.TRUE == bindableValue) { unbindablePropertyNames.remove(propertyName) bindablePropertyNames.add(propertyName) - if (DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(propertyName)) { + if (propertyName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT) { explicitlyBindableSpecialPropertyNames.add(propertyName) } } else { @@ -211,9 +211,10 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { explicitlyBindableSpecialPropertyNames.remove(propertyName) } } else { - GrailsASTUtils.warning(sourceUnit, valueExpression, 'The bindable constraint for property [' + - propertyName + '] in class [' + classNode.getName() + - '] has a value which is not a boolean literal and will be ignored.') + GrailsASTUtils.warning(sourceUnit, valueExpression, + "The bindable constraint for property [$propertyName] in class " + + "[${classNode.getName()}] has a value which is not a boolean " + + 'literal and will be ignored.') } } } @@ -222,15 +223,15 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { } propertyNamesToIncludeInWhiteList.addAll(bindablePropertyNames) - CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES.put(classNode, propertyNamesToIncludeInWhiteList) - CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES.put(classNode, explicitlyBindableSpecialPropertyNames) + CLASS_NODE_TO_WHITE_LIST_PROPERTY_NAMES[classNode] = propertyNamesToIncludeInWhiteList + CLASS_NODE_TO_EXPLICITLY_BINDABLE_SPECIAL_PROPERTY_NAMES[classNode] = explicitlyBindableSpecialPropertyNames return propertyNamesToIncludeInWhiteList } private Set<String> getLegacyPropertyNamesToIncludeInWhiteListForParentClass(final SourceUnit sourceUnit, final ClassNode parentClassNode) { final Set<String> propertyNames if (CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES.containsKey(parentClassNode)) { - propertyNames = CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES.get(parentClassNode) + propertyNames = CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES[parentClassNode] } else { propertyNames = getLegacyPropertyNamesToIncludeInWhiteList(sourceUnit, parentClassNode) } @@ -238,19 +239,19 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { } private Set<String> getLegacyPropertyNamesToIncludeInWhiteList(final SourceUnit sourceUnit, final ClassNode classNode) { - final Set<String> propertyNamesToIncludeInWhiteList = new HashSet<>() - final Set<String> unbindablePropertyNames = new HashSet<>() - final Set<String> bindablePropertyNames = new HashSet<>() + final Set<String> propertyNamesToIncludeInWhiteList = [] as Set + final Set<String> unbindablePropertyNames = [] as Set + final Set<String> bindablePropertyNames = [] as Set - final Set<String> explicitlyBindableSpecialPropertyNames = new HashSet<>() + final Set<String> explicitlyBindableSpecialPropertyNames = [] as Set final boolean isDomainClass = GrailsASTUtils.isDomainClass(classNode, sourceUnit) - if (!classNode.getSuperClass().equals(new ClassNode(Object))) { + if (classNode.getSuperClass() != new ClassNode(Object)) { final Set<String> parentClassPropertyNames = getLegacyPropertyNamesToIncludeInWhiteListForParentClass(sourceUnit, classNode.getSuperClass()) final Set<String> parentExplicitlyBindableSpecialPropertyNames = getExplicitlyBindableSpecialPropertyNamesForParentClass(sourceUnit, classNode.getSuperClass()) explicitlyBindableSpecialPropertyNames.addAll(parentExplicitlyBindableSpecialPropertyNames) for (final String parentPropertyName in parentClassPropertyNames) { - if (isDomainClass && DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(parentPropertyName) && - !parentExplicitlyBindableSpecialPropertyNames.contains(parentPropertyName)) { + if (isDomainClass && parentPropertyName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT && + !(parentPropertyName in parentExplicitlyBindableSpecialPropertyNames)) { continue } bindablePropertyNames.add(parentPropertyName) @@ -269,20 +270,20 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { final Map<String, Expression> mapEntryExpressions = constraintConfig.getValue() for (Map.Entry<String, Expression> entry in mapEntryExpressions.entrySet()) { final String constraintName = entry.getKey() - if (BINDABLE_CONSTRAINT_NAME.equals(constraintName)) { + if (constraintName == BINDABLE_CONSTRAINT_NAME) { final Expression valueExpression = entry.getValue() Boolean bindableValue = null if (valueExpression instanceof ConstantExpression) { - final Object constantValue = ((ConstantExpression) valueExpression).getValue() + final Object constantValue = valueExpression.getValue() if (constantValue instanceof Boolean) { - bindableValue = (Boolean) constantValue + bindableValue = constantValue } } if (bindableValue != null) { - if (Boolean.TRUE.equals(bindableValue)) { + if (Boolean.TRUE == bindableValue) { unbindablePropertyNames.remove(propertyName) bindablePropertyNames.add(propertyName) - if (DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(propertyName)) { + if (propertyName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT) { explicitlyBindableSpecialPropertyNames.add(propertyName) } } else { @@ -291,9 +292,10 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { explicitlyBindableSpecialPropertyNames.remove(propertyName) } } else { - GrailsASTUtils.warning(sourceUnit, valueExpression, 'The bindable constraint for property [' + - propertyName + '] in class [' + classNode.getName() + - '] has a value which is not a boolean literal and will be ignored.') + GrailsASTUtils.warning(sourceUnit, valueExpression, + "The bindable constraint for property [$propertyName] in class " + + "[${classNode.getName()}] has a value which is not a boolean " + + 'literal and will be ignored.') } } } @@ -307,8 +309,8 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { final List<FieldNode> fields = classNode.getFields() for (FieldNode fieldNode in fields) { final String fieldName = fieldNode.getName() - if ((!unbindablePropertyNames.contains(fieldName)) && - (bindablePropertyNames.contains(fieldName) || shouldFieldBeInWhiteList(fieldNode, fieldsInTransientsList, isDomainClass))) { + if (!(fieldName in unbindablePropertyNames) && + (fieldName in bindablePropertyNames || shouldFieldBeInWhiteList(fieldNode, fieldsInTransientsList, isDomainClass))) { propertyNamesToIncludeInWhiteList.add(fieldName) } } @@ -316,18 +318,18 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { final Map<String, MethodNode> declaredMethodsMap = classNode.getDeclaredMethodsMap() for (Map.Entry<String, MethodNode> methodEntry in declaredMethodsMap.entrySet()) { final MethodNode value = methodEntry.getValue() - if (classNode.equals(value.getDeclaringClass())) { + if (classNode == value.getDeclaringClass()) { Parameter[] parameters = value.getParameters() if (parameters != null && parameters.length == 1) { final String methodName = value.getName() if (methodName.startsWith('set')) { final Parameter parameter = parameters[0] final ClassNode paramType = parameter.getType() - if (!paramType.equals(new ClassNode(Object))) { + if (paramType != new ClassNode(Object)) { final String restOfMethodName = methodName.substring(3) final String propertyName = GrailsNameUtils.getPropertyName(restOfMethodName) - if (!unbindablePropertyNames.contains(propertyName) && - (!isDomainClass || !DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(propertyName))) { + if (!(propertyName in unbindablePropertyNames) && + (!isDomainClass || !(propertyName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT))) { propertyNamesToIncludeInWhiteList.add(propertyName) } } @@ -335,10 +337,10 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { } } } - CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES.put(classNode, propertyNamesToIncludeInWhiteList) + CLASS_NODE_TO_LEGACY_WHITE_LIST_PROPERTY_NAMES[classNode] = propertyNamesToIncludeInWhiteList Map<String, ClassNode> allAssociationMap = GrailsASTUtils.getAllAssociationMap(classNode) for (String associationName in allAssociationMap.keySet()) { - if (!propertyNamesToIncludeInWhiteList.contains(associationName) && !unbindablePropertyNames.contains(associationName)) { + if (!(associationName in propertyNamesToIncludeInWhiteList) && !(associationName in unbindablePropertyNames)) { propertyNamesToIncludeInWhiteList.add(associationName) } } @@ -351,11 +353,11 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { final String fieldName = fieldNode.getName() if ((modifiers & Modifier.STATIC) != 0 || (modifiers & Modifier.TRANSIENT) != 0 || - fieldsInTransientsList.contains(fieldName) || - (fieldNode.getType().equals(new ClassNode(Object)) && !fieldNode.getType().isUsingGenerics())) { + fieldName in fieldsInTransientsList || + (fieldNode.getType() == new ClassNode(Object) && !fieldNode.getType().isUsingGenerics())) { shouldInclude = false } else if (isDomainClass) { - if (DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT.contains(fieldName)) { + if (fieldName in DOMAIN_CLASS_PROPERTIES_TO_EXCLUDE_BY_DEFAULT) { shouldInclude = false } } @@ -363,19 +365,19 @@ class DefaultASTDatabindingHelper implements ASTDatabindingHelper { } private Set<String> getPropertyNamesExpressedInTransientsList(final ClassNode classNode) { - final Set<String> transientFields = new HashSet<>() + final Set<String> transientFields = [] as Set final FieldNode transientsField = classNode.getField('transients') if (transientsField != null && transientsField.isStatic()) { final Expression initialValueExpression = transientsField.getInitialValueExpression() if (initialValueExpression instanceof ListExpression) { - final ListExpression le = (ListExpression) initialValueExpression + final ListExpression le = initialValueExpression final List<Expression> expressions = le.getExpressions() for (Expression expr in expressions) { if (expr instanceof ConstantExpression) { - final ConstantExpression ce = (ConstantExpression) expr + final ConstantExpression ce = expr final Object contantValue = ce.getValue() if (contantValue instanceof String) { - transientFields.add((String) contantValue) + transientFields.add(contantValue) } } }
