This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch groovyism/grails-bootstrap in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit b0e28701cf86e0fa21aca70060863995ec0f5f7f Author: Walter Duque de Estrada <[email protected]> AuthorDate: Fri Oct 16 08:32:47 2026 -0500 refactor(bootstrap): make the converted grails-bootstrap sources idiomatic Groovy Idiomatic-Groovy cleanup of the Java-to-Groovy conversion output for grails-bootstrap. No behaviour or public API change. Applied: - Property syntax for trivial getters/setters (safe receivers only): Throwable.cause/stackTrace, File.name/absolutePath/canonicalPath, Resource.URL/file/filename, StackTraceElement.className/fileName/lineNumber, JarURLConnection.jarFile/jarFileURL/jarEntry, URI.schemeSpecificPart, BuildEvent.target/priority/message, Target.name, Thread.contextClassLoader, Ant BuildLogger/Project setters. - Safe navigation / Elvis for null-guard-then-call and ternary-with-null-check patterns (GrailsConsole, FileSystemResourceLoader, ResourceLocator, CandidateListCompletionHandler). - Collection literals ([], [:], [] as Set) replacing no-arg ArrayList/LinkedHashMap/HashSet constructors; sized/copy-constructor forms left untouched. - list.add/Set.add -> <<, map.get -> map[k] (bracket reads resolve statically); map.put deliberately kept as .put(k, v) - see "left unchanged" below. - .equals( ) -> == for Strings; str.length() == 0 / ''.equals(x) -> isEmpty(). - in for Collection.contains and Map.containsKey. - any{}/every{} replacing classic break-and-flag / early-return boolean loops (MetaClassRegistryCleaner.createAndRegister, DefaultStackTraceFilterer .isApplicationClass, CandidateListCompletionHandler.startsWith). - Sentinel identity checks (NO_CUSTOM_METACLASS, NULL_RESOURCE) converted to SENTINEL.is(x) per the equals/identity audit. - Dropped a redundant instanceof-guarded cast (PathMatchingResourcePatternResolver .doFindPathMatchingJarResources) relying on STC flow typing. - SAM coercion for an anonymous FileFilter (ResourceLocator). - join(';') replacing an index loop that built a separator-joined string (ConsoleAnsi.flushStyles). - Misc: Arrays.asList(single) -> list literal, new String[]{..} -> as String[], list.toArray(new T[size]) -> as T[], list.get(i)/list[i]. Left unchanged (Tier B/C exclusions): - map[k] = v (putAt) kept as .put(k, v): javap showed Groovy's bracket-assignment on Map compiles to a dynamic ScriptBytecodeAdapter.invokeMethodN under @CompileStatic in this toolchain, even though bracket-read (getAt) resolves statically - the exact dynamic-fallback regression the groovyisms skill's javap audit step exists to catch. Reverted every map[k] = v back to .put across MetaClassRegistryCleaner, ResourceLocator, the two WatchService watchers, PollingDirectoryWatcher and AntPathMatcher; kept the (confirmed static) bracket reads. - getResourceLoader()/getPathMatcher()/getDefaultResourceLoader() self-calls (PathMatchingResourcePatternResolver, ResourceLocator) left as explicit method calls: these are overridable public/protected getters on non-final classes with real subclasses elsewhere in the repo, so collapsing them to bare property access risks losing virtual dispatch. - Resource.getURL() left alone where chained purely for GrailsResourceUtils argument passing is already minimal; getFile()/getURL() were converted only where Resource's interface (grails-gradle's copy) confirmed no isFile()/isURL() pairing risk. - AntPathMatcher.doMatch's indexed "all elements are '**'" loops: these fit the any/every idiom, but rewriting them to `(start..end).every {}` is unsafe in general (a descending Groovy IntRange iterates rather than being empty) and verifying the specific invariant that makes it safe here is not worth the risk in a hand-ported path-matching algorithm; left as indexed for loops, only the inner .equals -> == was applied. - Side-effect-only for-loops with no early exit were left as for-loops rather than converted to .each{}, to keep the diff to idiom substitutions rather than control-flow rewrites. - GrailsEclipseConsole, ConsoleLogger, GrailsConsoleBuildListener, GrailsConsolePrintStream/GrailsConsoleErrorPrintStream, the plugin metadata annotations/interfaces/exceptions, and MetaClassRegistryCleanerSpec: no leftover Java shapes to convert. Verification: compileGroovy/compileCliGroovy clean; :grails-bootstrap:test 197/0 (0 skipped); codenarcMain/codenarcCli 0 violations (codenarcTest/ codenarcTestCli skipped, no ruleset); javap dynamic-dispatch audit on every changed class (including the cli sourceset and anonymous inner classes) shows zero invokeMethodN/getGroovyObjectProperty/setGroovyObjectProperty. Co-Authored-By: Claude Sonnet 5 <[email protected]> --- .../grails/build/logging/GrailsConsole.groovy | 12 +++--- .../CandidateListCompletionHandler.groovy | 16 ++------ .../org/grails/build/logging/ConsoleAnsi.groovy | 9 +---- .../build/logging/GrailsConsoleAntBuilder.groovy | 24 +++++------ .../build/support/MetaClassRegistryCleaner.groovy | 34 +++++++--------- .../reporting/DefaultStackTraceFilterer.groovy | 31 +++++++------- .../org/grails/io/support/AntPathMatcher.groovy | 38 ++++++++--------- .../io/support/FileSystemResourceLoader.groovy | 2 +- .../PathMatchingResourcePatternResolver.groovy | 42 +++++++++---------- .../org/grails/io/support/ResourceLocator.groovy | 47 ++++++++++------------ .../grails/io/support/StaticResourceLoader.groovy | 2 +- .../io/watch/AbstractDirectoryWatcher.groovy | 18 ++++----- .../org/grails/io/watch/DirectoryWatcher.groovy | 12 +++--- .../watch/MacOsWatchServiceDirectoryWatcher.groovy | 12 +++--- .../grails/io/watch/PollingDirectoryWatcher.groovy | 14 +++---- .../io/watch/WatchServiceDirectoryWatcher.groovy | 14 +++---- 16 files changed, 150 insertions(+), 177 deletions(-) diff --git a/grails-bootstrap/src/cli/groovy/grails/build/logging/GrailsConsole.groovy b/grails-bootstrap/src/cli/groovy/grails/build/logging/GrailsConsole.groovy index ad54eafae2..ff9d54d62e 100644 --- a/grails-bootstrap/src/cli/groovy/grails/build/logging/GrailsConsole.groovy +++ b/grails-bootstrap/src/cli/groovy/grails/build/logging/GrailsConsole.groovy @@ -133,7 +133,7 @@ class GrailsConsole implements ConsoleLogger { /** * List of completers to be aggregated for tab completion */ - private final List<Completer> completers = new java.util.ArrayList<>() + private final List<Completer> completers = [] /** * The category of the current output @@ -240,10 +240,10 @@ class GrailsConsole implements ConsoleLogger { private PrintStream unwrapPrintStream(PrintStream printStream) { if (printStream instanceof GrailsConsolePrintStream) { - return ((GrailsConsolePrintStream) printStream).getTargetOut() + return printStream.targetOut } if (printStream instanceof GrailsConsoleErrorPrintStream) { - return ((GrailsConsoleErrorPrintStream) printStream).getTargetOut() + return printStream.targetOut } return printStream } @@ -542,7 +542,7 @@ class GrailsConsole implements ConsoleLogger { verifySystemOut() progressIndicatorActive = true if (isAnsiEnabled()) { - if (lastMessage != null && lastMessage.length() > 0) { + if (lastMessage) { if (!lastMessage.contains(maxIndicatorString)) { updateStatus(lastMessage + indicator) } @@ -628,7 +628,7 @@ class GrailsConsole implements ConsoleLogger { private void outputMessage(String msg, int replaceCount) { verifySystemOut() - if (msg == null || msg.trim().length() == 0) return + if (msg == null || msg.trim().isEmpty()) return try { if (isAnsiEnabled()) { if (replaceCount > 0) { @@ -641,7 +641,7 @@ class GrailsConsole implements ConsoleLogger { cursorMove = replaceCount } } else { - if (lastMessage != null && lastMessage.equals(msg)) return + if (lastMessage == msg) return if (progressIndicatorActive) { out.println() diff --git a/grails-bootstrap/src/cli/groovy/org/grails/build/interactive/CandidateListCompletionHandler.groovy b/grails-bootstrap/src/cli/groovy/org/grails/build/interactive/CandidateListCompletionHandler.groovy index fa6933493f..d179ea8c6e 100644 --- a/grails-bootstrap/src/cli/groovy/org/grails/build/interactive/CandidateListCompletionHandler.groovy +++ b/grails-bootstrap/src/cli/groovy/org/grails/build/interactive/CandidateListCompletionHandler.groovy @@ -47,9 +47,7 @@ class CandidateListCompletionHandler implements Completer { @Override void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { - if (delegate != null) { - delegate.complete(reader, line, candidates) - } + delegate?.complete(reader, line, candidates) } /** @@ -60,14 +58,14 @@ class CandidateListCompletionHandler implements Completer { * method will return <i>foob</i>. */ static String getUnambiguousCompletions(final List<Candidate> candidates) { - if (candidates == null || candidates.isEmpty()) { + if (!candidates) { return null } // convert to an array for speed String[] strings = new String[candidates.size()] for (int i = 0; i < candidates.size(); i++) { - strings[i] = candidates.get(i).value() + strings[i] = candidates[i].value() } String first = strings[0] @@ -89,13 +87,7 @@ class CandidateListCompletionHandler implements Completer { * start with <i>starts</i> */ private static boolean startsWith(final String starts, final String[] candidates) { - for (int i = 0; i < candidates.length; i++) { - if (!candidates[i].startsWith(starts)) { - return false - } - } - - return true + return candidates.every { it.startsWith(starts) } } } diff --git a/grails-bootstrap/src/cli/groovy/org/grails/build/logging/ConsoleAnsi.groovy b/grails-bootstrap/src/cli/groovy/org/grails/build/logging/ConsoleAnsi.groovy index 08f7667768..28645d1c2a 100644 --- a/grails-bootstrap/src/cli/groovy/org/grails/build/logging/ConsoleAnsi.groovy +++ b/grails-bootstrap/src/cli/groovy/org/grails/build/logging/ConsoleAnsi.groovy @@ -127,14 +127,7 @@ final class ConsoleAnsi { if (this.pendingStyles.isEmpty()) { return } - this.sb.append(CSI) - for (int i = 0; i < this.pendingStyles.size(); i++) { - if (i > 0) { - this.sb.append(';') - } - this.sb.append(this.pendingStyles.get(i)) - } - this.sb.append('m') + this.sb.append(CSI).append(this.pendingStyles.join(';')).append('m') this.pendingStyles.clear() } diff --git a/grails-bootstrap/src/cli/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.groovy b/grails-bootstrap/src/cli/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.groovy index 64aaac99cc..bf947c8d38 100644 --- a/grails-bootstrap/src/cli/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.groovy +++ b/grails-bootstrap/src/cli/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.groovy @@ -56,21 +56,21 @@ class GrailsConsoleAntBuilder extends AntBuilder { final ProjectHelper helper = ProjectHelper.getProjectHelper() project.addReference(MagicNames.REFID_PROJECT_HELPER, helper) - helper.getImportStack().addElement('AntBuilder') // import checks that stack is not empty + helper.importStack.addElement('AntBuilder') // import checks that stack is not empty addGrailsConsoleBuildListener(project) project.init() - project.getBaseDir() + project.baseDir return project } static void addGrailsConsoleBuildListener(Project project) { final BuildLogger logger = new GrailsConsoleLogger() - logger.setMessageOutputLevel(Project.MSG_INFO) - logger.setOutputPrintStream(System.out) - logger.setErrorPrintStream(System.err) + logger.messageOutputLevel = Project.MSG_INFO + logger.outputPrintStream = System.out + logger.errorPrintStream = System.err project.addBuildListener(logger) @@ -78,9 +78,9 @@ class GrailsConsoleAntBuilder extends AntBuilder { project.addBuildListener(new GrailsConsoleBuildListener(instance)) if (!instance.isVerbose()) { - for (Object buildListener in project.getBuildListeners()) { + for (Object buildListener in project.buildListeners) { if (buildListener instanceof BuildLogger) { - ((BuildLogger) buildListener).setMessageOutputLevel(LogLevel.ERR.getLevel()) + buildListener.messageOutputLevel = LogLevel.ERR.level } } } @@ -106,7 +106,7 @@ class GrailsConsoleAntBuilder extends AntBuilder { */ @Override void targetStarted(BuildEvent event) { - targetName = event.getTarget().getName() + targetName = event.target.name } /** @@ -130,13 +130,13 @@ class GrailsConsoleAntBuilder extends AntBuilder { */ @Override void messageLogged(BuildEvent event) { - if (event.getPriority() > msgOutputLevel || - null == event.getMessage() || - ''.equals(event.getMessage().trim())) { + if (event.priority > msgOutputLevel || + event.message == null || + event.message.trim().isEmpty()) { return } - if (null != targetName) { + if (targetName != null) { console.verbose(System.lineSeparator() + targetName + ':') targetName = null } diff --git a/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.groovy b/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.groovy index cde8c0e9be..83ac537ef3 100644 --- a/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.groovy +++ b/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.groovy @@ -46,14 +46,8 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { static MetaClassRegistryCleaner createAndRegister() { MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry() - MetaClassRegistryChangeEventListener[] listeners = metaClassRegistry.getMetaClassRegistryChangeEventListeners() - boolean registered = false - for (MetaClassRegistryChangeEventListener listener in listeners) { - if (listener == INSTANCE) { - registered = true; break - } - } - if (!registered) { + MetaClassRegistryChangeEventListener[] listeners = metaClassRegistry.metaClassRegistryChangeEventListeners + if (!listeners.any { INSTANCE.is(it) }) { GroovySystem.getMetaClassRegistry().addMetaClassRegistryChangeEventListener(INSTANCE) } return INSTANCE @@ -70,10 +64,10 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { void updateConstantMetaClass(MetaClassRegistryChangeEvent cmcu) { if (!cleaning) { - MetaClass oldMetaClass = cmcu.getOldMetaClass() - Class classToUpdate = cmcu.getClassToUpdate() - Object instanceToUpdate = cmcu.getInstance() - if (instanceToUpdate == null && (cmcu.getNewMetaClass() instanceof ExpandoMetaClass)) { + MetaClass oldMetaClass = cmcu.oldMetaClass + Class classToUpdate = cmcu.classToUpdate + Object instanceToUpdate = cmcu.instance + if (instanceToUpdate == null && (cmcu.newMetaClass instanceof ExpandoMetaClass)) { updateMetaClassOfClass(oldMetaClass, classToUpdate) } else if (instanceToUpdate != null) { updateMetaClassOfInstance(oldMetaClass, instanceToUpdate) @@ -84,8 +78,8 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { private void updateMetaClassOfInstance(MetaClass oldMetaClass, Object instanceToUpdate) { IdentityWeakReference key = new IdentityWeakReference(instanceToUpdate) if (oldMetaClass != null) { - Object current = alteredInstances.get(key) - if (current == null || current == NO_CUSTOM_METACLASS) { + Object current = alteredInstances[key] + if (current == null || NO_CUSTOM_METACLASS.is(current)) { alteredInstances.put(key, oldMetaClass) } } else { @@ -94,8 +88,8 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { } private void updateMetaClassOfClass(MetaClass oldMetaClass, Class classToUpdate) { - if (oldMetaClass != null && !(oldMetaClass.getClass().getName().equals('groovy.mock.interceptor.MockProxyMetaClass'))) { - Object current = alteredClasses.get(classToUpdate) + if (oldMetaClass != null && oldMetaClass.getClass().name != 'groovy.mock.interceptor.MockProxyMetaClass') { + Object current = alteredClasses[classToUpdate] if (current == null) { alteredClasses.put(classToUpdate, oldMetaClass) } @@ -121,8 +115,8 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { for (IdentityWeakReference key in keys) { Object instance = key.get() if (instance != null) { - Object alteredMetaClass = alteredInstances.get(key) - if (alteredMetaClass == NO_CUSTOM_METACLASS) { + Object alteredMetaClass = alteredInstances[key] + if (NO_CUSTOM_METACLASS.is(alteredMetaClass)) { alteredMetaClass = null } registry.setMetaClass(instance, (MetaClass) alteredMetaClass) @@ -134,8 +128,8 @@ class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener { private void cleanMetaClassOfClass(MetaClassRegistryImpl registry) { Set<Class> classes = new HashSet<>(alteredClasses.keySet()) for (Class aClass in classes) { - Object alteredMetaClass = alteredClasses.get(aClass) - if (alteredMetaClass == NO_CUSTOM_METACLASS) { + Object alteredMetaClass = alteredClasses[aClass] + if (NO_CUSTOM_METACLASS.is(alteredMetaClass)) { registry.removeMetaClass(aClass) } else { diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.groovy b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.groovy index a14d96a865..2ba22e0277 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.groovy @@ -43,7 +43,7 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { */ public static final Log STACK_LOG = LogFactory.getLog(STACK_LOG_NAME) - private static final String[] DEFAULT_INTERNAL_PACKAGES = new String[] { + private static final String[] DEFAULT_INTERNAL_PACKAGES = [ 'org.codehaus.groovy.runtime.', 'org.codehaus.groovy.reflection.', 'org.codehaus.groovy.ast.', @@ -61,9 +61,9 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { 'org.springsource.loaded.', 'com.opensymphony.', 'jakarta.servlet.' - } + ] as String[] - private List<String> packagesToFilter = new ArrayList<>() + private List<String> packagesToFilter = [] private boolean shouldFilter private String cutOffPackage = null private boolean logFullStackTraceOnFilter = true @@ -74,7 +74,7 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { DefaultStackTraceFilterer(boolean shouldFilter) { this.shouldFilter = shouldFilter - packagesToFilter.addAll(Arrays.asList(DEFAULT_INTERNAL_PACKAGES)) + packagesToFilter.addAll(DEFAULT_INTERNAL_PACKAGES) } void addInternalPackage(String name) { @@ -100,9 +100,9 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { Throwable filter(Throwable source, boolean recursive) { if (recursive) { Throwable current = source - while (current != null) { + while (current) { filter(current) - current = current.getCause() + current = current.cause } return source } @@ -113,7 +113,7 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { if (!shouldFilter) { return source } - StackTraceElement[] trace = source.getStackTrace() + StackTraceElement[] trace = source.stackTrace List<StackTraceElement> newTrace = filterTraceWithCutOff(trace, cutOffPackage) if (newTrace.isEmpty()) { @@ -131,24 +131,24 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { } StackTraceElement[] clean = new StackTraceElement[newTrace.size()] newTrace.toArray(clean) - source.setStackTrace(clean) + source.stackTrace = clean } return source } private List<StackTraceElement> filterTraceWithCutOff(StackTraceElement[] trace, String endPackage) { - List<StackTraceElement> newTrace = new ArrayList<>() + List<StackTraceElement> newTrace = [] boolean foundGroovy = false for (StackTraceElement stackTraceElement in trace) { - String className = stackTraceElement.getClassName() - String fileName = stackTraceElement.getFileName() + String className = stackTraceElement.className + String fileName = stackTraceElement.fileName if (!foundGroovy && fileName != null && fileName.endsWith('.groovy')) { foundGroovy = true } if (endPackage != null && className.startsWith(endPackage) && foundGroovy) break if (isApplicationClass(className)) { - if (stackTraceElement.getLineNumber() > -1) { - newTrace.add(stackTraceElement) + if (stackTraceElement.lineNumber > -1) { + newTrace << stackTraceElement } } } @@ -161,10 +161,7 @@ class DefaultStackTraceFilterer implements StackTraceFilterer { * @return true if is internal */ protected boolean isApplicationClass(String className) { - for (String packageName in packagesToFilter) { - if (className.startsWith(packageName)) return false - } - return true + return !packagesToFilter.any { className.startsWith(it) } } void setShouldFilter(boolean shouldFilter) { diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.groovy index 4441c17e57..c04f9e5640 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.groovy @@ -99,7 +99,7 @@ class AntPathMatcher { // Match all elements up to the first ** while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String patDir = pattDirs[pattIdxStart] - if ('**'.equals(patDir)) { + if (patDir == '**') { break } if (!matchStrings(patDir, pathDirs[pathIdxStart], uriTemplateVariables)) { @@ -118,11 +118,11 @@ class AntPathMatcher { if (!fullMatch) { return true } - if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals('*') && path.endsWith(pathSeparator)) { + if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart] == '*' && path.endsWith(pathSeparator)) { return true } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals('**')) { + if (pattDirs[i] != '**') { return false } } @@ -132,7 +132,7 @@ class AntPathMatcher { // String not exhausted, but pattern is. Failure. return false } - else if (!fullMatch && '**'.equals(pattDirs[pattIdxStart])) { + else if (!fullMatch && pattDirs[pattIdxStart] == '**') { // Path start definitely matches due to "**" part in pattern. return true } @@ -140,7 +140,7 @@ class AntPathMatcher { // up to last '**' while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String patDir = pattDirs[pattIdxEnd] - if (patDir.equals('**')) { + if (patDir == '**') { break } if (!matchStrings(patDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { @@ -152,7 +152,7 @@ class AntPathMatcher { if (pathIdxStart > pathIdxEnd) { // String is exhausted for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals('**')) { + if (pattDirs[i] != '**') { return false } } @@ -162,7 +162,7 @@ class AntPathMatcher { while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { int patIdxTmp = -1 for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { - if (pattDirs[i].equals('**')) { + if (pattDirs[i] == '**') { patIdxTmp = i break } @@ -200,7 +200,7 @@ class AntPathMatcher { } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals('**')) { + if (pattDirs[i] != '**') { return false } } @@ -210,7 +210,7 @@ class AntPathMatcher { private String[] tokenize(String pattern) { List<String> list = StringGroovyMethods.tokenize((CharSequence) pattern, (CharSequence) pathSeparator) - return list.toArray(new String[list.size()]) + return list as String[] } /** @@ -269,7 +269,7 @@ class AntPathMatcher { } Map<String, String> extractUriTemplateVariables(String pattern, String path) { - Map<String, String> variables = new LinkedHashMap<>() + Map<String, String> variables = [:] doMatch(pattern, path, true, variables) return variables } @@ -350,7 +350,7 @@ class AntPathMatcher { } private boolean hasText(String txt) { - return txt != null && txt.length() > 0 + return txt } /** @@ -387,8 +387,8 @@ class AntPathMatcher { else if (pattern2 == null) { return -1 } - boolean pattern1EqualsPath = pattern1.equals(path) - boolean pattern2EqualsPath = pattern2.equals(path) + boolean pattern1EqualsPath = pattern1 == path + boolean pattern2EqualsPath = pattern2 == path if (pattern1EqualsPath && pattern2EqualsPath) { return 0 } @@ -490,17 +490,17 @@ class AntPathMatcher { while (m.find()) { patternBuilder.append(quote(p, end, m.start())) String match = m.group() - if ('?'.equals(match)) { + if (match == '?') { patternBuilder.append('.') } - else if ('*'.equals(match)) { + else if (match == '*') { patternBuilder.append('.*') } else if (match.startsWith('{') && match.endsWith('}')) { int colonIdx = match.indexOf(':') if (colonIdx == -1) { patternBuilder.append(DEFAULT_VARIABLE_PATTERN) - variableNames.add(m.group(1)) + variableNames << m.group(1) } else { String variablePattern = match.substring(colonIdx + 1, match.length() - 1) @@ -508,7 +508,7 @@ class AntPathMatcher { patternBuilder.append(variablePattern) patternBuilder.append(')') String variableName = match.substring(1, colonIdx) - variableNames.add(variableName) + variableNames << variableName } } end = m.end() @@ -536,7 +536,7 @@ class AntPathMatcher { } if (uriTemplateVariables != null) { for (int i = 1, count = matcher.groupCount(); i <= count; i++) { - String name = variableNames.get(i - 1) + String name = variableNames[i - 1] String value = matcher.group(i) uriTemplateVariables.put(name, value) } @@ -551,7 +551,7 @@ class AntPathMatcher { * @param sub string to search for. Return 0 if this is null. */ static int countOccurrencesOf(String str, String sub) { - if (str == null || sub == null || str.length() == 0 || sub.length() == 0) { + if (str == null || sub == null || str.isEmpty() || sub.isEmpty()) { return 0 } int count = 0 diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.groovy index 9fbb190ccf..758df3c592 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.groovy @@ -50,7 +50,7 @@ class FileSystemResourceLoader extends DefaultResourceLoader { */ @Override protected Resource getResourceByPath(String path) { - if (path != null && path.startsWith('/')) { + if (path?.startsWith('/')) { path = path.substring(1) } return new FileSystemResource(path) diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.groovy index a9d9e3838d..4b47a6a0ff 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.groovy @@ -185,7 +185,7 @@ class PathMatchingResourcePatternResolver { * (never <code>null</code>). */ ClassLoader getClassLoader() { - return getResourceLoader().getClassLoader() + return getResourceLoader().classLoader } /** @@ -245,9 +245,9 @@ class PathMatchingResourcePatternResolver { Set<Resource> result = new LinkedHashSet<>(16) while (resourceUrls.hasMoreElements()) { URL url = resourceUrls.nextElement() - result.add(convertClassLoaderURL(url)) + result << convertClassLoaderURL(url) } - return result.toArray(new Resource[result.size()]) + return result as Resource[] } /** @@ -285,7 +285,7 @@ class PathMatchingResourcePatternResolver { result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern)) } } - return result.toArray(new Resource[result.size()]) + return result as Resource[] } /** @@ -336,7 +336,7 @@ class PathMatchingResourcePatternResolver { * @see #doFindPathMatchingJarResources */ protected boolean isJarResource(Resource resource) throws IOException { - return GrailsResourceUtils.isJarURL(resource.getURL()) + return GrailsResourceUtils.isJarURL(resource.URL) } /** @@ -351,7 +351,7 @@ class PathMatchingResourcePatternResolver { protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException { - URLConnection con = rootDirResource.getURL().openConnection() + URLConnection con = rootDirResource.URL.openConnection() JarFile jarFile String jarFileUrl String rootEntryPath @@ -359,19 +359,19 @@ class PathMatchingResourcePatternResolver { if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. - JarURLConnection jarCon = (JarURLConnection) con + JarURLConnection jarCon = con GrailsResourceUtils.useCachesIfNecessary(jarCon) - jarFile = jarCon.getJarFile() - jarFileUrl = jarCon.getJarFileURL().toExternalForm() - JarEntry jarEntry = jarCon.getJarEntry() - rootEntryPath = (jarEntry != null ? jarEntry.getName() : '') + jarFile = jarCon.jarFile + jarFileUrl = jarCon.jarFileURL.toExternalForm() + JarEntry jarEntry = jarCon.jarEntry + rootEntryPath = jarEntry != null ? jarEntry.name : '' } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" prefix. - String urlFile = rootDirResource.getURL().getFile() + String urlFile = rootDirResource.URL.file int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR) if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex) @@ -387,7 +387,7 @@ class PathMatchingResourcePatternResolver { } try { - if (!''.equals(rootEntryPath) && !rootEntryPath.endsWith('/')) { + if (!rootEntryPath.isEmpty() && !rootEntryPath.endsWith('/')) { // Root entry path must end with slash to allow for proper matching. // The Sun JRE does not return a slash here, but BEA JRockit does. rootEntryPath = rootEntryPath + '/' @@ -395,11 +395,11 @@ class PathMatchingResourcePatternResolver { Set<Resource> result = new LinkedHashSet<>(8) for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement() - String entryPath = entry.getName() + String entryPath = entry.name if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()) if (getPathMatcher().match(subPattern, relativePath)) { - result.add(rootDirResource.createRelative(relativePath)) + result << rootDirResource.createRelative(relativePath) } } } @@ -420,7 +420,7 @@ class PathMatchingResourcePatternResolver { protected JarFile getJarFile(String jarFileUrl) throws IOException { if (jarFileUrl.startsWith(GrailsResourceUtils.FILE_URL_PREFIX)) { try { - return new JarFile(GrailsResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart()) + return new JarFile(GrailsResourceUtils.toURI(jarFileUrl).schemeSpecificPart) } catch (URISyntaxException ex) { // Fallback for URLs that are not valid URIs (should hardly ever happen). @@ -444,7 +444,7 @@ class PathMatchingResourcePatternResolver { File rootDir try { - rootDir = rootDirResource.getFile().getAbsoluteFile() + rootDir = rootDirResource.file.absoluteFile } catch (IOException ex) { return Collections.emptySet() @@ -465,7 +465,7 @@ class PathMatchingResourcePatternResolver { Set<File> matchingFiles = retrieveMatchingFiles(rootDir, subPattern) Set<Resource> result = new LinkedHashSet<>(matchingFiles.size()) for (File file in matchingFiles) { - result.add(new FileSystemResource(file)) + result << new FileSystemResource(file) } return result } @@ -491,7 +491,7 @@ class PathMatchingResourcePatternResolver { if (!rootDir.canRead()) { return Collections.emptySet() } - String fullPattern = rootDir.getAbsolutePath().replace(File.separator, '/') + String fullPattern = rootDir.absolutePath.replace(File.separator, '/') if (!pattern.startsWith('/')) { fullPattern += '/' } @@ -516,14 +516,14 @@ class PathMatchingResourcePatternResolver { return } for (File content in dirContents) { - String currPath = content.getAbsolutePath().replace(File.separator, '/') + String currPath = content.absolutePath.replace(File.separator, '/') if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + '/')) { if (content.canRead()) { doRetrieveMatchingFiles(fullPattern, content, result) } } if (getPathMatcher().match(fullPattern, currPath)) { - result.add(content) + result << content } } } diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.groovy index 7c0a504e45..d0d1afc0be 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.groovy @@ -41,8 +41,8 @@ class ResourceLocator { protected static final Resource NULL_RESOURCE = new ByteArrayResource('null'.getBytes()) protected PathMatchingResourcePatternResolver patchMatchingResolver - protected List<String> classSearchDirectories = new ArrayList<>() - protected List<String> resourceSearchDirectories = new ArrayList<>() + protected List<String> classSearchDirectories = [] + protected List<String> resourceSearchDirectories = [] protected Map<String, Resource> classNameToResourceCache = new ConcurrentHashMap<>() protected Map<String, Resource> uriToResourceCache = new ConcurrentHashMap<>() protected ResourceLoader defaultResourceLoader = new FileSystemResourceLoader() @@ -68,33 +68,30 @@ class ResourceLocator { private void initializeForSearchLocation(String searchLocation) { String searchLocationPlusSlash = searchLocation.endsWith('/') ? searchLocation : searchLocation + FILE_SEPARATOR try { - File[] directories = new File(searchLocationPlusSlash + GrailsResourceUtils.GRAILS_APP_DIR).listFiles(new FileFilter() { - boolean accept(File file) { - return file.isDirectory() && !file.isHidden() - } - }) + File[] directories = new File(searchLocationPlusSlash + GrailsResourceUtils.GRAILS_APP_DIR).listFiles( + { File file -> file.isDirectory() && !file.isHidden() } as FileFilter) if (directories != null) { for (File directory in directories) { - classSearchDirectories.add(directory.getCanonicalPath()) + classSearchDirectories << directory.canonicalPath } } } catch (IOException ignored) { // ignore } - classSearchDirectories.add(searchLocationPlusSlash + 'src/main/java') - classSearchDirectories.add(searchLocationPlusSlash + 'src/main/groovy') - resourceSearchDirectories.add(searchLocationPlusSlash) + classSearchDirectories << (searchLocationPlusSlash + 'src/main/java') + classSearchDirectories << (searchLocationPlusSlash + 'src/main/groovy') + resourceSearchDirectories << searchLocationPlusSlash } Resource findResourceForURI(String uri) { - Resource resource = uriToResourceCache.get(uri) + Resource resource = uriToResourceCache[uri] if (resource == null) { PluginResourceInfo info = inferPluginNameFromURI(uri) if (warDeployed) { Resource defaultResource = defaultResourceLoader.getResource(uri) - if (defaultResource != null && defaultResource.exists()) { + if (defaultResource?.exists()) { resource = defaultResource } } @@ -109,8 +106,8 @@ class ResourceLocator { else if (!warDeployed) { Resource dir = resolveExceptionSafe(resourceSearchDirectory) if (dir.exists() && info != null) { - String filename = dir.getFilename() - if (filename != null && filename.equals(info.pluginName)) { + String filename = dir.filename + if (filename == info.pluginName) { Resource pluginFile = dir.createRelative(WEB_APP_DIR + info.uri) if (pluginFile.exists()) { resource = pluginFile @@ -122,8 +119,8 @@ class ResourceLocator { } if (resource == null || !resource.exists()) { - Resource tmp = defaultResourceLoader != null ? defaultResourceLoader.getResource(uri) : null - if (tmp != null && tmp.exists()) { + Resource tmp = defaultResourceLoader?.getResource(uri) + if (tmp?.exists()) { resource = tmp } } @@ -135,7 +132,7 @@ class ResourceLocator { uriToResourceCache.put(uri, NULL_RESOURCE) } } - return resource == NULL_RESOURCE ? null : resource + return NULL_RESOURCE.is(resource) ? null : resource } private PluginResourceInfo inferPluginNameFromURI(String uri) { @@ -157,12 +154,12 @@ class ResourceLocator { if (className.contains(CLOSURE_MARKER)) { className = className.substring(0, className.indexOf(CLOSURE_MARKER)) } - Resource resource = classNameToResourceCache.get(className) + Resource resource = classNameToResourceCache[className] if (resource == null) { String classNameWithPathSeparator = className.replace('.', FILE_SEPARATOR) for (String pathPattern in getSearchPatternForExtension(classNameWithPathSeparator, '.groovy', '.java')) { resource = resolveExceptionSafe(pathPattern) - if (resource != null && resource.exists()) { + if (resource?.exists()) { classNameToResourceCache.put(className, resource) break } @@ -170,23 +167,23 @@ class ResourceLocator { if (resource == null || !resource.exists()) { for (String ext in ['.groovy', '.java'] as String[]) { resource = resolveExceptionSafe(GrailsResourceUtils.DOMAIN_DIR_PATH + '**/' + className + ext) - if (resource != null && resource.exists()) { + if (resource?.exists()) { classNameToResourceCache.put(className, resource) break } } } } - return resource != null && resource.exists() ? resource : null + return resource?.exists() ? resource : null } private List<String> getSearchPatternForExtension(String classNameWithPathSeparator, String... extensions) { - List<String> searchPatterns = new ArrayList<>() + List<String> searchPatterns = [] for (String extension in extensions) { String filename = classNameWithPathSeparator + extension for (String classSearchDirectory in classSearchDirectories) { - searchPatterns.add(classSearchDirectory + FILE_SEPARATOR + filename) + searchPatterns << (classSearchDirectory + FILE_SEPARATOR + filename) } } @@ -196,7 +193,7 @@ class ResourceLocator { private Resource resolveExceptionSafe(String pathPattern) { try { Resource[] resources = patchMatchingResolver.getResources('file:' + pathPattern) - if (resources != null && resources.length > 0) { + if (resources) { return resources[0] } } catch (IOException e) { diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.groovy index 210978da02..59b6957405 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.groovy @@ -40,7 +40,7 @@ class StaticResourceLoader implements ResourceLoader { } ClassLoader getClassLoader() { - return Thread.currentThread().getContextClassLoader() + return Thread.currentThread().contextClassLoader } } diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.groovy index 8e732b640c..bfb2aafb34 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.groovy @@ -32,7 +32,7 @@ import groovy.transform.CompileStatic @CompileStatic abstract class AbstractDirectoryWatcher implements Runnable { - private List<DirectoryWatcher.FileChangeListener> listeners = new ArrayList<>() + private List<DirectoryWatcher.FileChangeListener> listeners = [] volatile protected boolean active = true //must be volatile as it's read by multiple threads and the value should be reflected in all of them protected long sleepTime = 1000 @@ -60,7 +60,7 @@ abstract class AbstractDirectoryWatcher implements Runnable { * @param listener The file listener */ void addListener(DirectoryWatcher.FileChangeListener listener) { - listeners.add(listener) + listeners << listener } /** @@ -89,30 +89,30 @@ abstract class AbstractDirectoryWatcher implements Runnable { abstract void addWatchDirectory(File dir, List<String> fileExtensions) protected void fireOnChange(File file) { - for (DirectoryWatcher.FileChangeListener listener : listeners) { + for (DirectoryWatcher.FileChangeListener listener in listeners) { listener.onChange(file) } } protected void fireOnNew(File file) { - for (DirectoryWatcher.FileChangeListener listener : listeners) { + for (DirectoryWatcher.FileChangeListener listener in listeners) { listener.onNew(file) } } protected boolean isValidDirectoryToMonitor(File file) { - return file.isDirectory() && !file.isHidden() && !file.getName().startsWith('.') + return file.isDirectory() && !file.isHidden() && !file.name.startsWith('.') } protected boolean isValidFileToMonitor(File file, Collection<String> fileExtensions) { - String name = file.getName() - String path = file.getAbsolutePath() + String name = file.name + String path = file.absolutePath boolean isSvnFile = path.indexOf(File.separator + DirectoryWatcher.SVN_DIR_NAME + File.separator) > 0 return !isSvnFile && !file.isDirectory() && !file.isHidden() && - !file.getName().startsWith('.') && - (fileExtensions.contains('*') || fileExtensions.contains(getFilenameExtension(name))) + !file.name.startsWith('.') && + ('*' in fileExtensions || getFilenameExtension(name) in fileExtensions) } /** diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.groovy index b9d4584b34..7d0d383b3c 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.groovy @@ -56,7 +56,7 @@ class DirectoryWatcher extends Thread { * @return the watcher to delegate to */ private static AbstractDirectoryWatcher createDelegate() { - if (System.getProperty('os.name').equals('Mac OS X')) { + if (System.getProperty('os.name') == 'Mac OS X') { AbstractDirectoryWatcher macOsWatcher = createMacOsWatcher() if (macOsWatcher != null) { return macOsWatcher @@ -153,7 +153,7 @@ class DirectoryWatcher extends Thread { void addWatchDirectory(File dir, List<String> fileExtensions) { List<String> fileExtensionsWithoutDot = new ArrayList<>(fileExtensions.size()) for (String fileExtension in fileExtensions) { - fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension)) + fileExtensionsWithoutDot << removeStartingDotIfPresent(fileExtension) } directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions) } @@ -175,16 +175,16 @@ class DirectoryWatcher extends Thread { */ void addWatchDirectory(File dir, String extension) { extension = removeStartingDotIfPresent(extension) - List<String> fileExtensions = new ArrayList<>() - if (extension != null && extension.length() > 0) { + List<String> fileExtensions = [] + if (extension) { int i = extension.lastIndexOf('.') if (i > -1) { extension = extension.substring(i + 1) } - fileExtensions.add(extension) + fileExtensions << extension } else { - fileExtensions.add('*') + fileExtensions << '*' } addWatchDirectory(dir, fileExtensions) } diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.groovy index 67e57bcae5..8ec13904cd 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.groovy @@ -50,7 +50,7 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { private static final Logger LOG = LoggerFactory.getLogger(MacOsWatchServiceDirectoryWatcher) private Map<WatchKey, List<String>> watchKeyToExtensionsMap = new ConcurrentHashMap<>() - private Set<Path> individualWatchedFiles = new HashSet<>() + private Set<Path> individualWatchedFiles = [] as Set private final WatchService watchService @@ -87,7 +87,7 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { WatchEvent<Path> pathWatchEvent = cast(watchEvent) Path child = pathWatchEvent.context() File childFile = child.toFile() - if (individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())) { + if (child in individualWatchedFiles || child.normalize() in individualWatchedFiles) { if (kind == StandardWatchEventKinds.ENTRY_CREATE) { fireOnNew(childFile) } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { @@ -96,7 +96,7 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { // do nothing... there's no way to communicate deletions } } else { - List<String> fileExtensions = watchKeyToExtensionsMap.get(watchKey) + List<String> fileExtensions = watchKeyToExtensionsMap[watchKey] if (fileExtensions == null) { // this event didn't match a file in individualWatchedFiles so it's a not an individual file we're interested in // this event also didn't match a directory that we're interested in (if it did, fileExtentions wouldn't be null) @@ -150,11 +150,11 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { @Override void addWatchFile(File fileToWatch) { - if (!isValidFileToMonitor(fileToWatch, Arrays.asList('*'))) return + if (!isValidFileToMonitor(fileToWatch, ['*'])) return try { if (!fileToWatch.exists()) return Path pathToWatch = fileToWatch.toPath().toAbsolutePath() - individualWatchedFiles.add(pathToWatch) + individualWatchedFiles << pathToWatch WatchablePath watchPath = new WatchablePath(pathToWatch) Kind[] events = [StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY] as Kind[] watchPath.register(watchService, events) @@ -185,7 +185,7 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { WatchablePath watchPath = new WatchablePath(subDir) Kind[] events = [StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY] as Kind[] WatchKey watchKey = watchPath.register(watchService, events) - final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey) + final List<String> originalFileExtensions = watchKeyToExtensionsMap[watchKey] if (originalFileExtensions == null) { watchKeyToExtensionsMap.put(watchKey, fileExtensions) } else { diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.groovy index 16f8407e6d..868180ceab 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.groovy @@ -48,7 +48,7 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher { Set<File> files = lastModifiedMap.keySet() for (File file in files) { long currentLastModified = file.lastModified() - Long cachedTime = lastModifiedMap.get(file) + Long cachedTime = lastModifiedMap[file] if (currentLastModified > cachedTime) { lastModifiedMap.put(file, currentLastModified) fireOnChange(file) @@ -82,7 +82,7 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher { } private void trackDirectoryExtensions(File dir, List<String> fileExtensions) { - Collection<String> existingExtensions = directoryToExtensionsMap.get(dir) + Collection<String> existingExtensions = directoryToExtensionsMap[dir] if (existingExtensions == null) { directoryToExtensionsMap.put(dir, new ArrayList<>(fileExtensions)) } @@ -93,10 +93,10 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher { private void checkForNewFiles() { for (File directory in directoryWatch.keySet()) { - final Long currentTimestamp = directoryWatch.get(directory) + final Long currentTimestamp = directoryWatch[directory] if (currentTimestamp < directory.lastModified()) { - Collection<String> extensions = directoryToExtensionsMap.get(directory) + Collection<String> extensions = directoryToExtensionsMap[directory] if (extensions == null) { extensions = this.extensions } @@ -119,7 +119,7 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher { cacheFilesForDirectory(file, fileExtensions, fireEvent) } else if (isValidFileToMonitor(file, fileExtensions)) { - if (!lastModifiedMap.containsKey(file) && fireEvent) { + if (!(file in lastModifiedMap) && fireEvent) { fireOnNew(file) } lastModifiedMap.put(file, file.lastModified()) @@ -130,8 +130,8 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher { private void addExtensions(Collection<String> toAdd) { for (String extension in toAdd) { extension = removeStartingDotIfPresent(extension) - if (!extensions.contains(extension)) { - extensions.add(extension) + if (!(extension in extensions)) { + extensions << extension } } } diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.groovy index 99854d4a67..26b00fa85d 100644 --- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.groovy +++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.groovy @@ -50,7 +50,7 @@ class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { private static final Logger LOG = LoggerFactory.getLogger(WatchServiceDirectoryWatcher) private Map<WatchKey, List<String>> watchKeyToExtensionsMap = new ConcurrentHashMap<>() - private Set<Path> individualWatchedFiles = new HashSet<>() + private Set<Path> individualWatchedFiles = [] as Set private final WatchService watchService @@ -86,7 +86,7 @@ class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { Path dir = (Path) watchKey.watchable() Path child = dir.resolve(name).toAbsolutePath() File childFile = child.toFile() - if (individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())) { + if (child in individualWatchedFiles || child.normalize() in individualWatchedFiles) { if (kind == StandardWatchEventKinds.ENTRY_CREATE) { fireOnNew(childFile) } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { @@ -95,7 +95,7 @@ class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { // do nothing... there's no way to communicate deletions } } else { - List<String> fileExtensions = watchKeyToExtensionsMap.get(watchKey) + List<String> fileExtensions = watchKeyToExtensionsMap[watchKey] if (fileExtensions == null) { // this event didn't match a file in individualWatchedFiles so it's a not an individual file we're interested in // this event also didn't match a directory that we're interested in (if it did, fileExtentions wouldn't be null) @@ -149,12 +149,12 @@ class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { @Override void addWatchFile(File fileToWatch) { - if (!isValidFileToMonitor(fileToWatch, Arrays.asList('*'))) return + if (!isValidFileToMonitor(fileToWatch, ['*'])) return try { if (!fileToWatch.exists()) return Path pathToWatch = fileToWatch.toPath().toAbsolutePath() - individualWatchedFiles.add(pathToWatch) - pathToWatch.getParent().register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY) + individualWatchedFiles << pathToWatch + pathToWatch.parent.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY) } catch (IOException e) { throw new RuntimeException(e) } @@ -180,7 +180,7 @@ class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher { return FileVisitResult.SKIP_SUBTREE } WatchKey watchKey = subDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY) - final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey) + final List<String> originalFileExtensions = watchKeyToExtensionsMap[watchKey] if (originalFileExtensions == null) { watchKeyToExtensionsMap.put(watchKey, fileExtensions) } else {
