You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by jd...@apache.org on 2025/07/14 03:43:59 UTC
(grails-core) 02/02: style: reformat grails-core per styling rules
This is an automated email from the ASF dual-hosted git repository.
jdaugherty pushed a commit to branch style-enforcement
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit e3a6ad2e8dc60ff6fbf3f8feafada9a60b033b05
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Sun Jul 13 22:19:23 2025 -0400
style: reformat grails-core per styling rules
---
etc/config/checkstyle/checkstyle.xml | 11 +-
etc/config/checkstyle/suppressions.xml | 26 +
gradle/style-enforcement-config.gradle | 3 +-
grails-async/core/build.gradle | 1 +
.../main/groovy/grails/async/DelegateAsync.groovy | 3 +-
.../main/groovy/grails/async/PromiseFactory.groovy | 12 +-
.../main/groovy/grails/async/PromiseList.groovy | 2 +-
.../src/main/groovy/grails/async/PromiseMap.groovy | 32 +-
.../src/main/groovy/grails/async/Promises.groovy | 48 +-
.../async/factory/AbstractPromiseFactory.groovy | 24 +-
.../org/grails/async/factory/BoundPromise.groovy | 3 +-
.../async/factory/PromiseFactoryBuilder.groovy | 6 +-
.../grails/async/factory/SynchronousPromise.groovy | 23 +-
.../async/factory/SynchronousPromiseFactory.groovy | 9 +-
.../future/CachedThreadPoolPromiseFactory.groovy | 15 +-
.../factory/future/ExecutorPromiseFactory.groovy | 1 -
.../factory/future/FutureTaskChildPromise.groovy | 15 +-
.../async/factory/future/FutureTaskPromise.groovy | 7 +-
...elegateAsyncTransactionalMethodTransformer.java | 1 +
.../internal/DelegateAsyncTransformation.java | 42 +-
.../transform/internal/DelegateAsyncUtils.groovy | 4 +-
grails-async/gpars/build.gradle | 1 +
.../grails/async/factory/gpars/GparsPromise.groovy | 6 +-
.../async/factory/gpars/GparsPromiseFactory.groovy | 26 +-
.../async/factory/gpars/LoggingPoolFactory.groovy | 9 +-
grails-async/plugin/build.gradle | 1 +
.../PersistenceContextPromiseDecorator.groovy | 3 +-
.../services/TransactionalPromiseDecorator.groovy | 5 +-
.../groovy/grails/async/web/AsyncController.groovy | 3 +-
.../grails/async/web/AsyncGrailsWebRequest.groovy | 14 +-
.../groovy/grails/async/web/WebPromises.groovy | 47 +-
...egateAsyncTransactionalMethodTransformer.groovy | 65 +-
.../async/TransactionalAsyncTransformUtils.groovy | 1 -
.../async/AsyncWebRequestPromiseDecorator.groovy | 31 +-
...WebRequestPromiseDecoratorLookupStrategy.groovy | 1 +
.../web/async/ControllersAsyncGrailsPlugin.groovy | 12 +-
.../plugins/web/async/GrailsAsyncContext.groovy | 9 +-
.../async/mvc/AsyncActionResultTransformer.groovy | 10 +-
.../web/async/spring/PromiseFactoryBean.groovy | 2 +-
grails-async/rxjava/build.gradle | 1 +
.../grails/async/factory/rxjava/RxPromise.groovy | 29 +-
.../async/factory/rxjava/RxPromiseFactory.groovy | 23 +-
.../factory/rxjava/RxJavaPromiseListSpec.groovy | 1 -
.../factory/rxjava/RxJavaPromiseMapSpec.groovy | 1 -
.../async/factory/rxjava/RxJavaPromiseSpec.groovy | 1 -
grails-async/rxjava2/build.gradle | 1 +
.../grails/async/factory/rxjava2/RxPromise.groovy | 22 +-
.../async/factory/rxjava2/RxPromiseFactory.groovy | 25 +-
.../async/factory/rxjava2/RxPromiseSpec.groovy | 1 -
grails-async/rxjava3/build.gradle | 1 +
.../grails/async/factory/rxjava3/RxPromise.groovy | 22 +-
.../async/factory/rxjava3/RxPromiseFactory.groovy | 25 +-
.../async/factory/rxjava3/RxPromiseSpec.groovy | 1 -
grails-bom/build.gradle | 1 +
grails-bootstrap/build.gradle | 1 +
.../groovy/grails/build/logging/ConsoleLogger.java | 7 +-
.../groovy/grails/build/logging/GrailsConsole.java | 92 +-
.../grails/build/logging/GrailsEclipseConsole.java | 3 +-
.../proxy/SystemPropertiesAuthenticator.groovy | 3 +-
.../build/support/MetaClassRegistryCleaner.java | 21 +-
.../main/groovy/grails/codegen/model/Model.groovy | 1 -
.../grails/codegen/model/ModelBuilder.groovy | 14 +-
.../src/main/groovy/grails/io/ResourceUtils.groovy | 21 +-
.../grails/io/support/SystemOutErrCapturer.groovy | 28 +-
.../io/support/SystemStreamsRedirector.groovy | 29 +-
.../groovy/grails/plugins/GrailsPluginInfo.java | 3 +
.../grails/plugins/GrailsVersionUtils.groovy | 12 +-
.../groovy/grails/plugins/VersionComparator.groovy | 13 +-
.../grails/plugins/metadata/GrailsPlugin.java | 2 +
.../grails/plugins/metadata/PluginSource.java | 1 +
.../groovy/grails/util/CosineSimilarity.groovy | 6 +-
.../src/main/groovy/grails/util/Described.groovy | 2 -
.../CandidateListCompletionHandler.java | 7 +-
.../build/logging/GrailsConsoleAntBuilder.java | 3 +-
.../build/logging/GrailsConsoleBuildListener.java | 16 +-
.../logging/GrailsConsoleErrorPrintStream.java | 2 +-
.../build/logging/GrailsConsolePrintStream.java | 2 +-
.../grails/build/parsing/ScriptNameResolver.groovy | 2 +-
.../groovy/org/grails/config/CodeGenConfig.groovy | 118 +-
.../groovy/org/grails/config/NavigableMap.groovy | 229 ++--
.../org/grails/exceptions/ExceptionUtils.groovy | 6 +-
.../reporting/DefaultStackTraceFilterer.java | 52 +-
.../reporting/DefaultStackTracePrinter.groovy | 8 +-
.../exceptions/reporting/SourceCodeAware.java | 1 +
.../exceptions/reporting/StackTraceFilterer.java | 7 +-
.../org/grails/io/support/AntPathMatcher.java | 234 ++--
.../grails/io/support/DevNullPrintStream.groovy | 1 -
.../io/support/FileSystemResourceLoader.java | 5 +-
.../PathMatchingResourcePatternResolver.java | 65 +-
.../org/grails/io/support/ResourceLocator.java | 18 +-
.../grails/io/support/StaticResourceLoader.java | 1 -
.../grails/io/watch/AbstractDirectoryWatcher.java | 21 +-
.../org/grails/io/watch/DirectoryWatcher.java | 89 +-
.../watch/FileExtensionFileChangeListener.groovy | 5 +-
.../watch/MacOsWatchServiceDirectoryWatcher.java | 189 ++--
.../grails/io/watch/PollingDirectoryWatcher.java | 40 +-
.../io/watch/WatchServiceDirectoryWatcher.java | 273 ++---
grails-cache/build.gradle | 1 +
.../taglib/grails/plugin/cache/CacheTagLib.groovy | 1 -
.../plugin/cache/CustomCacheKeyGenerator.groovy | 1 -
.../compiler/AbstractCacheTransformation.groovy | 1 -
.../cache/compiler/CachePutTransformation.groovy | 1 -
.../cache/compiler/CacheableTransformation.groovy | 1 -
.../grails/plugin/cache/CacheException.groovy | 1 -
.../grails/plugin/cache/CacheGrailsPlugin.groovy | 2 -
.../plugin/cache/CachePluginConfiguration.groovy | 1 -
.../groovy/grails/plugin/cache/GrailsCache.java | 2 +-
.../plugin/cache/GrailsCacheAdminService.groovy | 8 +-
.../cache/GrailsConcurrentLinkedMapCache.java | 269 ++---
.../GrailsConcurrentLinkedMapCacheManager.groovy | 64 +-
.../plugin/cache/GrailsConcurrentMapCache.java | 44 +-
.../cache/GrailsConcurrentMapCacheManager.groovy | 58 +-
.../grails/plugin/cache/GrailsValueWrapper.java | 16 +-
.../grails/plugin/cache/util/ClassUtils.java | 2 +-
.../grails/plugin/cache/CacheTagLibSpec.groovy | 1 -
.../grails/plugin/cache/CacheableParseSpec.groovy | 3 -
grails-codecs-core/build.gradle | 1 +
.../org/grails/plugins/codecs/DigestUtils.groovy | 6 +-
.../plugins/codecs/HexCodecExtensionMethods.groovy | 3 +-
.../codecs/MD5BytesCodecExtensionMethods.groovy | 2 +-
.../codecs/SHA1BytesCodecExtensionMethods.groovy | 2 +-
.../codecs/SHA1CodecExtensionMethods.groovy | 2 +-
.../codecs/SHA256BytesCodecExtensionMethods.groovy | 2 +-
.../codecs/SHA256CodecExtensionMethods.groovy | 2 +-
grails-codecs/build.gradle | 1 +
.../org/grails/commons/CodecArtefactHandler.java | 4 +-
.../grails/commons/DefaultGrailsCodecClass.java | 143 +--
.../org/grails/commons/GrailsCodecClass.java | 3 +-
.../plugins/codecs/CodecsGrailsPlugin.groovy | 1 +
.../grails/plugins/codecs/DefaultCodecLookup.java | 3 +-
.../org/grails/plugins/codecs/HTMLCodec.java | 15 +-
.../org/grails/plugins/codecs/URLCodec.groovy | 1 +
grails-common/build.gradle | 1 +
.../AbstractRecursiveAnnotationVisitor.java | 35 +-
.../AnnotationAttributesReadingVisitor.java | 36 +-
.../AnnotationMetadataReadingVisitor.java | 29 +-
.../annotation/AnnotationReadingVisitorUtils.java | 54 +-
.../annotation/ClassMetadataReadingVisitor.java | 34 +-
.../annotation/MethodMetadataReadingVisitor.java | 28 +-
.../RecursiveAnnotationArrayVisitor.java | 36 +-
.../RecursiveAnnotationAttributesVisitor.java | 30 +-
.../common/compiler/GroovyTransformOrder.groovy | 27 +-
.../compiler/asm/AnnotationMetadataReader.java | 48 +-
.../grails/common/compiler/asm/Attribute.java | 208 ++--
.../grails/common/compiler/asm/ByteVector.java | 100 +-
.../grails/common/compiler/asm/ClassReader.java | 427 +++-----
.../apache/grails/common/compiler/asm/Context.java | 43 +-
.../grails/common/compiler/asm/TypePath.java | 77 +-
.../common/properties/PropertyFileUtils.groovy | 26 +-
grails-console/build.gradle | 1 +
.../GrailsApplicationContextCommandRunner.groovy | 29 +-
.../grails/ui/console/GrailsSwingConsole.groovy | 14 +-
.../support/GroovyConsoleApplicationContext.groovy | 1 -
.../GroovyConsoleWebApplicationContext.groovy | 1 -
.../ui/script/GrailsApplicationScriptRunner.groovy | 3 +-
.../main/groovy/grails/ui/shell/GrailsShell.groovy | 13 +-
.../ui/support/DevelopmentGrailsApplication.groovy | 1 -
.../DevelopmentWebApplicationContext.groovy | 1 -
grails-controllers/build.gradle | 1 +
.../main/groovy/grails/artefact/Controller.groovy | 74 +-
.../controller/support/AllowedMethodsHelper.groovy | 6 +-
.../controller/support/RequestForwarder.groovy | 23 +-
.../controller/support/ResponseRedirector.groovy | 20 +-
.../controller/support/ResponseRenderer.groovy | 2 -
.../compiler/traits/ControllerTraitInjector.groovy | 2 +-
.../src/main/groovy/grails/web/Controller.groovy | 3 +-
.../compiler/web/ControllerActionTransformer.java | 374 +++----
.../web/ControllerArtefactTypeTransformation.java | 2 +-
.../compiler/web/ControllerDomainTransformer.java | 2 +-
.../ControllerExceptionHandlerMetaData.java | 3 +
.../controllers/ControllersAutoConfiguration.java | 13 +-
.../web/controllers/ControllersGrailsPlugin.groovy | 82 +-
...efaultControllerExceptionHandlerMetaData.groovy | 1 +
.../api/ControllersDomainBindingApi.java | 14 +-
.../controllers/metaclass/RenderDynamicMethod.java | 3 +-
.../servlet/context/BootStrapClassRunner.groovy | 14 +-
.../web/servlet/mvc/InvalidResponseHandler.groovy | 1 -
.../web/servlet/mvc/ValidResponseHandler.groovy | 1 -
.../controller/support/RequestForwarderSpec.groovy | 1 -
.../web/ControllerActionTransformerSpec.groovy | 4 -
grails-converters/build.gradle | 1 +
.../src/main/groovy/grails/converters/JSON.java | 162 ++-
.../src/main/groovy/grails/converters/XML.java | 77 +-
.../main/groovy/grails/encoders/JSONEncoder.java | 4 +-
.../main/groovy/grails/encoders/XMLEncoder.java | 6 +-
.../src/main/groovy/grails/web/JSONBuilder.groovy | 27 +-
.../converters/ConvertersDomainTransformer.java | 2 +-
.../web/converters/RenderConverterTrait.groovy | 3 +-
.../org/grails/plugins/codecs/JSONCodec.java | 2 +-
.../groovy/org/grails/plugins/codecs/XMLCodec.java | 2 +-
.../converters/ConvertersGrailsPlugin.groovy | 30 +-
.../plugins/converters/api/ConvertersApi.java | 6 +-
.../grails/web/converters/AbstractConverter.java | 4 +-
...AbstractParsingParameterCreationListener.groovy | 20 +-
.../web/converters/ConfigurableConverter.groovy | 2 +-
.../org/grails/web/converters/Converter.java | 4 +-
.../org/grails/web/converters/ConverterUtil.java | 24 +-
.../web/converters/ConvertersExtension.groovy | 22 +-
.../ChainedConverterConfiguration.java | 20 +-
.../configuration/ConverterConfiguration.java | 10 +-
.../ConvertersConfigurationHolder.java | 28 +-
.../ConvertersConfigurationInitializer.java | 53 +-
.../DefaultConverterConfiguration.java | 103 +-
.../web/converters/configuration/configtest.groovy | 19 +-
.../converters/exceptions/ConverterException.java | 1 -
.../marshaller/ByDatasourceDomainClassFetcher.java | 6 +-
.../ByGrailsApplicationDomainClassFetcher.java | 3 +-
.../marshaller/ClosureObjectMarshaller.java | 9 +-
.../converters/marshaller/DomainClassFetcher.java | 3 +-
.../IncludeExcludePropertyMarshaller.java | 4 +-
.../converters/marshaller/NameAwareMarshaller.java | 1 +
.../converters/marshaller/ObjectMarshaller.java | 5 +-
.../marshaller/ProxyUnwrappingMarshaller.java | 11 +-
.../converters/marshaller/json/DateMarshaller.java | 4 +-
.../marshaller/json/DomainClassMarshaller.java | 83 +-
.../converters/marshaller/json/EnumMarshaller.java | 13 +-
.../marshaller/json/GenericJavaBeanMarshaller.java | 27 +-
.../marshaller/json/GroovyBeanMarshaller.java | 27 +-
.../json/InstanceMethodBasedMarshaller.java | 11 +-
.../marshaller/json/JavascriptDateMarshaller.java | 4 +-
.../converters/marshaller/json/MapMarshaller.java | 4 +-
.../json/ValidationErrorsMarshaller.java | 12 +-
.../converters/marshaller/xml/ArrayMarshaller.java | 5 +-
.../marshaller/xml/Base64ByteArrayMarshaller.java | 10 +-
.../marshaller/xml/CollectionMarshaller.java | 3 +-
.../converters/marshaller/xml/DateMarshaller.java | 6 +-
.../marshaller/xml/DeepDomainClassMarshaller.java | 1 -
.../marshaller/xml/DomainClassMarshaller.java | 59 +-
.../converters/marshaller/xml/EnumMarshaller.java | 9 +-
.../marshaller/xml/GenericJavaBeanMarshaller.java | 6 +-
.../marshaller/xml/GroovyBeanMarshaller.java | 36 +-
.../xml/InstanceMethodBasedMarshaller.java | 11 +-
.../converters/marshaller/xml/MapMarshaller.java | 4 +-
.../marshaller/xml/ValidationErrorsMarshaller.java | 12 +-
.../json/DomainClassMarshallerSpec.groovy | 1 -
grails-core/build.gradle | 1 +
.../src/main/groovy/grails/artefact/Enhanced.java | 3 +
.../groovy/grails/beans/util/LazyBeanMap.groovy | 26 +-
.../grails/beans/util/LazyMetaPropertyMap.java | 32 +-
.../src/main/groovy/grails/boot/GrailsApp.groovy | 19 +-
.../groovy/grails/boot/GrailsAppBuilder.groovy | 2 +-
.../config/GrailsApplicationPostProcessor.groovy | 56 +-
.../boot/config/GrailsAutoConfiguration.groovy | 15 +-
.../boot/config/tools/ClassPathScanner.groovy | 27 +-
.../ProfilingGrailsApplicationPostProcessor.groovy | 6 +-
.../grails/boot/config/tools/SettingsFile.groovy | 2 -
.../groovy/grails/compiler/DelegatingMethod.groovy | 1 -
.../grails/compiler/GrailsCompileStatic.groovy | 14 +-
.../grails/compiler/GrailsTypeChecked.groovy | 14 +-
.../compiler/ast/AnnotatedClassInjector.java | 3 +-
.../groovy/grails/compiler/ast/AstTransformer.java | 3 +-
.../groovy/grails/compiler/ast/ClassInjector.java | 10 +-
.../grails/compiler/ast/GlobalClassInjector.groovy | 2 +-
.../compiler/ast/GlobalClassInjectorAdapter.groovy | 2 +-
.../compiler/ast/GrailsDomainClassInjector.java | 1 -
.../grails/compiler/ast/SupportsClassNode.java | 3 +-
.../grails/compiler/traits/TraitInjector.java | 3 +-
.../src/main/groovy/grails/config/Config.groovy | 2 +-
.../groovy/grails/config/ConfigProperties.groovy | 9 +-
.../src/main/groovy/grails/config/Settings.groovy | 2 +-
...ilteringMap.groovy => WriteFilteringMap.groovy} | 0
.../groovy/grails/core/ApplicationAttributes.java | 1 +
.../main/groovy/grails/core/ArtefactHandler.java | 12 +-
.../groovy/grails/core/ArtefactHandlerAdapter.java | 49 +-
.../src/main/groovy/grails/core/ArtefactInfo.java | 7 +-
.../groovy/grails/core/DefaultArtefactInfo.java | 16 +-
.../grails/core/DefaultGrailsApplication.java | 135 ++-
.../main/groovy/grails/core/GrailsApplication.java | 45 +-
.../grails/core/GrailsApplicationClass.groovy | 1 -
.../core/GrailsApplicationLifeCycleAdapter.groovy | 4 +-
.../src/main/groovy/grails/core/GrailsClass.java | 10 +-
.../groovy/grails/core/GrailsControllerClass.java | 8 +-
.../main/groovy/grails/core/GrailsDataSource.java | 2 +
.../main/groovy/grails/core/GrailsDomainClass.java | 3 +-
.../groovy/grails/core/GrailsServiceClass.java | 2 +
.../groovy/grails/core/GrailsUrlMappingsClass.java | 3 +-
.../core/events/ArtefactAdditionEvent.groovy | 4 +-
.../core/support/GrailsApplicationAware.java | 3 +-
.../core/support/GrailsConfigurationAware.java | 1 -
.../support/ParentApplicationContextAware.java | 3 +-
.../core/support/proxy/EntityProxyHandler.java | 2 +-
.../grails/core/support/proxy/ProxyHandler.java | 5 +-
.../grails/dev/commands/ApplicationCommand.groovy | 2 +-
.../ApplicationContextCommandRegistry.groovy | 2 +-
.../dev/commands/GrailsApplicationCommand.groovy | 6 +-
.../dev/commands/io/FileSystemInteraction.groovy | 6 +-
.../commands/io/FileSystemInteractionImpl.groovy | 40 +-
.../dev/commands/template/TemplateException.groovy | 1 -
.../dev/commands/template/TemplateRenderer.groovy | 7 +-
.../commands/template/TemplateRendererImpl.groovy | 4 +-
.../src/main/groovy/grails/persistence/Event.java | 8 +-
.../grails/persistence/PersistenceMethod.java | 1 +
.../support/NullPersistentContextInterceptor.java | 1 +
.../support/PersistenceContextInterceptor.java | 3 +-
.../PersistenceContextInterceptorExecutor.groovy | 2 -
.../grails/plugins/DefaultGrailsPluginManager.java | 19 +-
.../main/groovy/grails/plugins/GrailsPlugin.java | 18 +-
.../groovy/grails/plugins/GrailsPluginManager.java | 27 +-
.../src/main/groovy/grails/plugins/Plugin.groovy | 20 +-
.../main/groovy/grails/plugins/PluginFilter.java | 3 +-
.../groovy/grails/plugins/PluginManagerAware.java | 3 +-
.../grails/util/AbstractTypeConvertingMap.java | 116 +-
.../src/main/groovy/grails/util/CacheEntry.java | 103 +-
.../groovy/grails/util/ClosureToMapPopulator.java | 12 +-
.../src/main/groovy/grails/util/DomainBuilder.java | 24 +-
.../src/main/groovy/grails/util/ExtendedProxy.java | 9 +-
.../groovy/grails/util/GrailsArrayUtils.groovy | 33 +-
.../main/groovy/grails/util/GrailsClassUtils.java | 186 ++--
.../grails/util/GrailsMessageSourceUtils.groovy | 16 +-
.../groovy/grails/util/GrailsMetaClassUtils.java | 63 +-
.../groovy/grails/util/GrailsStringUtils.groovy | 40 +-
.../src/main/groovy/grails/util/GrailsUtil.java | 24 +-
.../src/main/groovy/grails/util/Holders.java | 34 +-
grails-core/src/main/groovy/grails/util/Mixin.java | 4 +-
.../groovy/grails/util/MixinTargetAware.groovy | 2 +-
grails-core/src/main/groovy/grails/util/Pair.java | 27 +-
.../src/main/groovy/grails/util/Triple.java | 34 +-
.../groovy/grails/util/TypeConvertingMap.groovy | 1 +
.../main/groovy/grails/validation/Constrained.java | 4 +-
.../grails/validation/ConstraintsEvaluator.java | 9 +-
.../grails/validation/DeferredBindingActions.java | 4 +-
.../grails/validation/ValidationException.java | 11 +-
grails-core/src/main/groovy/grails/web/Action.java | 1 +
.../groovy/grails/web/CamelCaseUrlConverter.java | 1 -
.../groovy/grails/web/HyphenatedUrlConverter.java | 1 -
.../src/main/groovy/grails/web/UrlConverter.java | 1 +
.../org/grails/beans/support/PropertiesEditor.java | 15 +-
.../boot/internal/EnableAutoConfiguration.java | 1 +
.../org/grails/boot/internal/JavaCompiler.groovy | 1 -
.../compiler/CriteriaTypeCheckingExtension.groovy | 28 +-
.../DomainMappingTypeCheckingExtension.groovy | 19 +-
.../DynamicFinderTypeCheckingExtension.groovy | 10 +-
.../HttpServletRequestTypeCheckingExtension.groovy | 7 +-
.../NamedQueryTypeCheckingExtension.groovy | 10 +-
...hipManagementMethodTypeCheckingExtension.groovy | 6 +-
.../ValidateableTypeCheckingExtension.groovy | 17 +-
.../WhereQueryTypeCheckingExtension.groovy | 28 +-
.../grails/compiler/injection/ASTErrorsHelper.java | 4 +-
.../injection/ASTValidationErrorsHelper.java | 3 +-
.../AbstractArtefactTypeAstTransformation.java | 12 +-
.../AbstractGrailsArtefactTransformer.java | 109 +-
.../injection/ApiDelegateTransformation.java | 5 +-
.../injection/ApplicationClassInjector.groovy | 16 +-
.../injection/ArtefactTypeAstTransformation.java | 60 +-
.../DefaultGrailsDomainClassInjector.java | 36 +-
.../injection/EnhancesTraitTransformation.groovy | 14 +-
.../injection/EntityASTTransformation.java | 11 +-
.../injection/GlobalImportTransformation.groovy | 3 +-
.../grails/compiler/injection/GrailsASTUtils.java | 414 +++----
.../compiler/injection/GrailsAwareClassLoader.java | 9 +-
.../injection/GrailsAwareInjectionOperation.java | 16 +-
.../GroovyEclipseCompilationHelper.groovy | 34 +-
.../compiler/injection/MixinTransformation.java | 23 +-
.../grails/compiler/injection/PluginAstReader.java | 39 +-
.../injection/TraitInjectionSupport.groovy | 8 +-
.../compiler/injection/TraitInjectionUtils.java | 33 +-
.../groovy/org/grails/config/CompositeConfig.java | 57 +-
.../config/EnvironmentAwarePropertySource.java | 28 +-
.../org/grails/config/NavigableMapConfig.java | 55 +-
.../config/NavigableMapPropertySource.groovy | 7 +-
.../groovy/org/grails/config/PrefixedConfig.java | 20 +-
.../grails/config/PrefixedMapPropertySource.groovy | 1 +
.../org/grails/config/PropertySourcesConfig.java | 26 +-
.../config/yaml/YamlPropertySourceLoader.java | 7 +-
.../org/grails/core/AbstractGrailsApplication.java | 1 +
.../org/grails/core/AbstractGrailsClass.java | 32 +-
.../grails/core/AbstractInjectableGrailsClass.java | 1 -
.../grails/core/DefaultGrailsControllerClass.java | 46 +-
.../org/grails/core/DefaultGrailsDomainClass.java | 22 +-
.../grails/core/DefaultGrailsUrlMappingsClass.java | 2 +-
.../core/artefact/ControllerArtefactHandler.java | 5 +-
.../core/artefact/DomainClassArtefactHandler.java | 28 +-
.../cfg/GroovyConfigPropertySourceLoader.groovy | 16 +-
.../core/exceptions/DefaultErrorsPrinter.groovy | 22 +-
...chingPathMatchingResourcePatternResolver.groovy | 3 +-
.../org/grails/core/io/DefaultResourceLocator.java | 14 +-
.../org/grails/core/io/GrailsResource.groovy | 2 +-
.../grails/core/io/MockStringResourceLoader.java | 4 +-
.../PluginPathAwareFileSystemResourceLoader.java | 4 +-
.../groovy/org/grails/core/io/ResourceLocator.java | 4 +-
.../groovy/org/grails/core/io/SpringResource.java | 3 +-
.../org/grails/core/io/StaticResourceLoader.java | 10 +-
.../org/grails/core/io/StaticResourceLocator.java | 5 +-
.../core/io/support/GrailsFactoriesLoader.groovy | 29 +-
.../grails/core/lifecycle/ShutdownOperations.java | 29 +-
.../org/grails/core/metaclass/BaseApiProvider.java | 28 +-
.../org/grails/core/support/ClassEditor.java | 9 +-
.../GrailsApplicationDiscoveryStrategy.groovy | 2 +-
.../internal/tools/ClassRelativeClassLoader.java | 20 +-
.../ClassRelativeResourcePatternResolver.java | 1 -
.../internal/tools/MetaClassChangeReporter.java | 5 +-
.../util/BeanCreationProfilingPostProcessor.java | 4 +-
.../groovy/org/grails/core/util/StopWatch.java | 31 +-
.../dev/support/DevelopmentShutdownHook.groovy | 2 +-
.../org/grails/plugins/AbstractGrailsPlugin.java | 77 +-
.../plugins/AbstractGrailsPluginManager.java | 87 +-
.../org/grails/plugins/BasePluginFilter.java | 26 +-
.../org/grails/plugins/BinaryGrailsPlugin.java | 57 +-
.../plugins/BinaryGrailsPluginDescriptor.java | 3 +-
.../org/grails/plugins/CoreGrailsPlugin.groovy | 122 +--
.../org/grails/plugins/CorePluginFinder.java | 21 +-
.../org/grails/plugins/DefaultGrailsPlugin.java | 224 ++--
.../org/grails/plugins/ExcludingPluginFilter.java | 4 +-
.../org/grails/plugins/IdentityPluginFilter.java | 2 +-
.../org/grails/plugins/IncludingPluginFilter.java | 2 +-
.../grails/plugins/MockGrailsPluginManager.java | 3 +-
.../org/grails/plugins/PluginFilterRetriever.java | 19 +-
.../plugins/ProfilingGrailsPluginManager.java | 7 +-
.../grails/plugins/core/CoreAutoConfiguration.java | 2 +-
.../grails/plugins/support/WatchPatternParser.java | 20 +-
.../spring/RuntimeSpringConfigUtilities.java | 29 +-
...vyAwareAspectJAwareAdvisorAutoProxyCreator.java | 6 -
.../beans/ClassLoaderAwareBeanPostProcessor.java | 2 +-
.../GrailsApplicationAwareBeanPostProcessor.java | 4 +-
.../beans/PluginManagerAwareBeanPostProcessor.java | 15 +-
.../beans/factory/GenericBeanFactoryAccessor.java | 4 +-
.../HotSwappableTargetSourceFactoryBean.groovy | 2 +-
.../spring/beans/factory/InstanceFactoryBean.java | 13 +-
.../context/ApplicationContextExtension.groovy | 7 +-
...sIgnoringComponentScanBeanDefinitionParser.java | 172 +--
.../spring/context/annotation/grails-context.xsd | 1 -
.../support/GrailsPlaceholderConfigurer.java | 11 +-
.../PluginAwareResourceBundleMessageSource.java | 57 +-
.../ReloadableResourceBundleMessageSource.java | 1143 ++++++++++----------
.../transaction/ChainedTransactionManager.java | 363 ++++---
.../ChainedTransactionManagerPostProcessor.java | 100 +-
.../transaction/GrailsTransactionAttribute.java | 26 +-
...GroovyAwareNamedTransactionAttributeSource.java | 8 +-
.../grails/transaction/MultiTransactionStatus.java | 340 +++---
.../SpringTransactionSynchronizationManager.java | 46 +-
.../grails/transaction/SynchronizationManager.java | 9 +-
.../TransactionManagerPostProcessor.java | 9 +-
.../grails/validation/ConstraintEvalUtils.groovy | 5 +-
.../groovy/grails/artefact/EnhancesSpec.groovy | 1 -
.../grails/config/PropertySourceConfigSpec.groovy | 1 -
.../ArtefactTypeAstTransformationSpec.groovy | 3 -
...balGrailsClassInjectorTransformationSpec.groovy | 1 -
.../config/NavigableMapNestedEqualitySpec.groovy | 1 -
.../org/grails/plugins/BinaryPluginSpec.groovy | 1 -
grails-data-hibernate5/boot-plugin/build.gradle | 1 +
.../HibernateGormAutoConfiguration.groovy | 25 +-
.../compiler/GormCompilerAutoConfiguration.groovy | 7 +-
grails-data-hibernate5/core/build.gradle | 1 +
.../grails/orm/HibernateCriteriaBuilder.java | 46 +-
.../main/groovy/grails/orm/PagedResultList.java | 4 +-
.../main/groovy/grails/orm/RlikeExpression.java | 8 +-
.../grails/orm/hibernate/HibernateEntity.groovy | 2 +-
.../orm/hibernate/annotation/ManagedEntity.java | 1 -
.../orm/hibernate/mapping/MappingBuilder.groovy | 3 +-
.../orm/hibernate/AbstractHibernateDatastore.java | 83 +-
.../AbstractHibernateGormInstanceApi.groovy | 37 +-
.../AbstractHibernateGormStaticApi.groovy | 210 ++--
.../AbstractHibernateGormValidationApi.groovy | 8 +-
.../orm/hibernate/AbstractHibernateSession.java | 11 +-
.../orm/hibernate/EventListenerIntegrator.java | 50 +-
.../orm/hibernate/GrailsHibernateTemplate.java | 341 +++---
.../GrailsHibernateTransactionManager.groovy | 13 +-
.../grails/orm/hibernate/GrailsSessionContext.java | 56 +-
.../grails/orm/hibernate/HibernateDatastore.java | 203 ++--
.../orm/hibernate/HibernateGormEnhancer.groovy | 1 +
.../orm/hibernate/HibernateGormInstanceApi.groovy | 18 +-
.../orm/hibernate/HibernateGormStaticApi.groovy | 40 +-
.../hibernate/HibernateGormValidationApi.groovy | 4 +-
.../HibernateMappingContextSessionFactoryBean.java | 75 +-
.../org/grails/orm/hibernate/HibernateSession.java | 69 +-
.../grails/orm/hibernate/SessionFactoryHolder.java | 2 +-
.../access/TraitPropertyAccessStrategy.java | 47 +-
.../hibernate/cfg/AbstractGrailsDomainBinder.java | 7 +-
.../grails/orm/hibernate/cfg/CacheConfig.groovy | 3 +-
.../grails/orm/hibernate/cfg/ColumnConfig.groovy | 1 +
.../orm/hibernate/cfg/CompositeIdentity.groovy | 1 +
.../orm/hibernate/cfg/DiscriminatorConfig.groovy | 1 +
.../orm/hibernate/cfg/GrailsDomainBinder.java | 1098 ++++++++-----------
.../orm/hibernate/cfg/GrailsHibernateUtil.java | 89 +-
.../cfg/GrailsIdentifierGeneratorFactory.java | 7 +-
.../hibernate/cfg/HibernateMappingBuilder.groovy | 121 +--
.../orm/hibernate/cfg/HibernateMappingContext.java | 71 +-
.../cfg/HibernateMappingContextConfiguration.java | 76 +-
.../hibernate/cfg/HibernatePersistentEntity.java | 11 +-
.../org/grails/orm/hibernate/cfg/Identity.groovy | 1 +
.../grails/orm/hibernate/cfg/IdentityEnumType.java | 33 +-
.../grails/orm/hibernate/cfg/InstanceProxy.groovy | 8 +-
.../org/grails/orm/hibernate/cfg/JoinTable.groovy | 1 +
.../org/grails/orm/hibernate/cfg/Mapping.groovy | 108 +-
.../org/grails/orm/hibernate/cfg/NaturalId.groovy | 1 +
.../cfg/PersistentEntityNamingStrategy.java | 1 -
.../grails/orm/hibernate/cfg/PropertyConfig.groovy | 85 +-
.../cfg/PropertyDefinitionDelegate.groovy | 8 +-
.../org/grails/orm/hibernate/cfg/Settings.java | 1 -
.../org/grails/orm/hibernate/cfg/SortConfig.groovy | 1 +
.../org/grails/orm/hibernate/cfg/Table.groovy | 1 +
.../compiler/HibernateEntityTransformation.groovy | 50 +-
.../AbstractHibernateConnectionSourceFactory.java | 42 +-
.../connections/HibernateConnectionSource.java | 5 +-
.../HibernateConnectionSourceFactory.java | 42 +-
.../HibernateConnectionSourceSettings.groovy | 44 +-
...HibernateConnectionSourceSettingsBuilder.groovy | 13 +-
.../datasource/MultipleDataSourceSupport.java | 1 +
.../dirty/GrailsEntityDirtinessStrategy.groovy | 35 +-
.../listener/AbstractHibernateEventListener.java | 3 +-
.../event/listener/HibernateEventListener.java | 41 +-
...CouldNotDetermineHibernateDialectException.java | 3 +-
.../GrailsHibernateConfigurationException.java | 2 +-
.../exceptions/GrailsHibernateException.java | 1 -
.../hibernate/exceptions/GrailsQueryException.java | 1 -
.../multitenancy/MultiTenantEventListener.java | 41 +-
.../orm/hibernate/proxy/HibernateProxyHandler.java | 20 +-
.../proxy/SimpleHibernateProxyHandler.java | 35 +-
.../query/AbstractHibernateCriteriaBuilder.java | 502 ++++-----
.../query/AbstractHibernateCriterionAdapter.java | 181 ++--
.../hibernate/query/AbstractHibernateQuery.java | 313 +++---
.../hibernate/query/GrailsHibernateQueryUtils.java | 16 +-
.../hibernate/query/HibernateCriterionAdapter.java | 2 -
.../orm/hibernate/query/HibernateHqlQuery.java | 7 +-
.../query/HibernateProjectionAdapter.java | 30 +-
.../grails/orm/hibernate/query/HibernateQuery.java | 3 -
.../hibernate/query/HibernateQueryConstants.java | 3 +-
.../orm/hibernate/query/PagedResultList.java | 3 +-
.../AbstractClosureEventTriggeringInterceptor.java | 11 +-
.../hibernate/support/ClosureEventListener.java | 61 +-
.../support/ClosureEventTriggeringInterceptor.java | 43 +-
.../hibernate/support/DataSourceFactoryBean.groovy | 2 +-
...rnateDatastoreConnectionSourcesRegistrar.groovy | 8 +-
.../support/HibernateDatastoreFactoryBean.groovy | 3 +-
.../HibernateDialectDetectorFactoryBean.java | 14 +-
.../hibernate/support/HibernateRuntimeUtils.groovy | 28 +-
.../hibernate/support/HibernateVersionSupport.java | 17 +-
.../org/grails/orm/hibernate/support/SoftKey.java | 6 +-
.../HibernateJtaTransactionManagerAdapter.java | 88 +-
.../PlatformTransactionManagerProxy.java | 4 +-
grails-forge/etc/checkstyle/suppressions.xml | 6 +-
.../gradle/style-enforcement-config.gradle | 3 +-
532 files changed, 8332 insertions(+), 8622 deletions(-)
diff --git a/etc/config/checkstyle/checkstyle.xml b/etc/config/checkstyle/checkstyle.xml
index 128659ad6c..9f58763322 100644
--- a/etc/config/checkstyle/checkstyle.xml
+++ b/etc/config/checkstyle/checkstyle.xml
@@ -97,12 +97,13 @@
<module name="SuppressWarningsFilter"/>
<!-- See http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter -->
-<!-- <module name="SuppressionFilter">-->
-<!-- <property name="file" value="${config_loc}/suppressions.xml"/>-->
-<!-- <property name="optional" value="false"/>-->
-<!-- </module>-->
+ <module name="SuppressionFilter">
+ <property name="file" value="${config_loc}/suppressions.xml"/>
+ <property name="optional" value="false"/>
+ </module>
<module name="TreeWalker">
+ <module name="AvoidStarImport"/>
<!-- Needed for SuppressWarningsFilter -->
<module name="SuppressWarningsHolder"/>
@@ -228,6 +229,8 @@
<module name="TodoComment">
<property name="severity" value="warning"/>
</module>
+
+ <module name="SuppressionCommentFilter"/>
</module>
</module>
diff --git a/etc/config/checkstyle/suppressions.xml b/etc/config/checkstyle/suppressions.xml
new file mode 100644
index 0000000000..ae2a63e6a2
--- /dev/null
+++ b/etc/config/checkstyle/suppressions.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ https://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions 1.1//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_1.dtd">
+<suppressions>
+ <suppress checks="FileLength"
+ files="GrailsDomainBinder.java|AbstractHibernateCriteriaBuilder.java"/>
+</suppressions>
diff --git a/gradle/style-enforcement-config.gradle b/gradle/style-enforcement-config.gradle
index e0a5d895a9..cd4363694f 100644
--- a/gradle/style-enforcement-config.gradle
+++ b/gradle/style-enforcement-config.gradle
@@ -37,7 +37,8 @@ spotless {
}
checkstyle {
- configFile = project.rootProject.file('etc/config/checkstyle/checkstyle.xml')
+ configFile = project.rootProject.layout.projectDirectory.file('etc/config/checkstyle/checkstyle.xml').asFile
+ configDirectory = project.rootProject.layout.projectDirectory.dir('etc/config/checkstyle').asFile
// Per submodule
maxErrors = 1
diff --git a/grails-async/core/build.gradle b/grails-async/core/build.gradle
index 6a4f2b9679..bdeb790cb0 100644
--- a/grails-async/core/build.gradle
+++ b/grails-async/core/build.gradle
@@ -50,4 +50,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/core/src/main/groovy/grails/async/DelegateAsync.groovy b/grails-async/core/src/main/groovy/grails/async/DelegateAsync.groovy
index 7fb5615fbe..67bd5ae6e8 100644
--- a/grails-async/core/src/main/groovy/grails/async/DelegateAsync.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/DelegateAsync.groovy
@@ -39,7 +39,7 @@ import org.codehaus.groovy.transform.GroovyASTTransformationClass
* If the annotation is applied to a new class:
*
* <pre><code>
- * @DelegateAsync(BookApi)
+ * @DelegateAsync (BookApi)
* class AsyncBookApi {}
* </code></pre>
*
@@ -65,5 +65,6 @@ import org.codehaus.groovy.transform.GroovyASTTransformationClass
@Target([ElementType.TYPE, ElementType.FIELD])
@GroovyASTTransformationClass("org.grails.async.transform.internal.DelegateAsyncTransformation")
@interface DelegateAsync {
+
Class value() default DelegateAsync
}
diff --git a/grails-async/core/src/main/groovy/grails/async/PromiseFactory.groovy b/grails-async/core/src/main/groovy/grails/async/PromiseFactory.groovy
index c6691ef95c..1e1dcb4bca 100644
--- a/grails-async/core/src/main/groovy/grails/async/PromiseFactory.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/PromiseFactory.groovy
@@ -50,7 +50,7 @@ interface PromiseFactory {
/**
* Creates a promise with a value pre-bound to it
* @param value The value
- * @param <T> The type of the value
+ * @param <T> The type of the value
* @return A Promise
*/
<T> Promise<T> createBoundPromise(T value)
@@ -58,7 +58,7 @@ interface PromiseFactory {
/**
* Creates an unfulfilled promise that returns the given type
* @param returnType The return type
- * @param <T> The type of the class
+ * @param <T> The type of the class
* @return The unfulfilled promise
*/
<T> Promise<T> createPromise(Class<T> returnType)
@@ -76,7 +76,7 @@ interface PromiseFactory {
* @param map The map
* @return A promise
*/
- <K,V> Promise<Map<K,V>> createPromise(Map<K, V> map)
+ <K, V> Promise<Map<K, V>> createPromise(Map<K, V> map)
/**
* Creates a promise from the given map where the values of the map are either closures or Promise instances
@@ -84,7 +84,7 @@ interface PromiseFactory {
* @param map The map
* @return A promise
*/
- <K,V> Promise<Map<K,V>> createPromise(Map<K, V> map, List<PromiseDecorator> decorators)
+ <K, V> Promise<Map<K, V>> createPromise(Map<K, V> map, List<PromiseDecorator> decorators)
/**
* Creates a promise from one or more other promises
@@ -92,7 +92,7 @@ interface PromiseFactory {
* @param promises The promises
* @return The promise
*/
- <T> Promise<List<T>> createPromise(Promise<T>...promises)
+ <T> Promise<List<T>> createPromise(Promise<T>... promises)
/**
* Creates a promise from one or many closures
@@ -132,7 +132,7 @@ interface PromiseFactory {
* @param promises The promises
* @return The list of bound values
*/
- <T> List<T> waitAll(Promise<T>...promises)
+ <T> List<T> waitAll(Promise<T>... promises)
/**
* Synchronously waits for all promises to complete returning a list of values
*
diff --git a/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy b/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy
index b19b1b2f8f..8db692eefa 100644
--- a/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy
@@ -138,7 +138,7 @@ class PromiseList<T> implements Promise<List<T>> {
@Override
boolean isDone() {
- return promises.every {promise -> promise.isDone() }
+ return promises.every { promise -> promise.isDone() }
}
@Override
diff --git a/grails-async/core/src/main/groovy/grails/async/PromiseMap.groovy b/grails-async/core/src/main/groovy/grails/async/PromiseMap.groovy
index f367d96128..9bd07cb910 100644
--- a/grails-async/core/src/main/groovy/grails/async/PromiseMap.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/PromiseMap.groovy
@@ -32,14 +32,14 @@ import java.util.concurrent.TimeUnit
*/
@AutoFinal
@CompileStatic
-class PromiseMap<K,V> implements Promise<Map<K,V>> {
+class PromiseMap<K, V> implements Promise<Map<K, V>> {
protected LinkedHashMap<K, Promise<V>> promises = [:]
protected LinkedHashMap<Promise<V>, K> promisesKeys = [:]
PromiseMap() {}
- PromiseMap(Map<K,V> values) {
+ PromiseMap(Map<K, V> values) {
accept(values)
}
@@ -55,11 +55,11 @@ class PromiseMap<K,V> implements Promise<Map<K,V>> {
@Override
boolean isDone() {
- return promisesKeys.keySet().every {it.isDone() }
+ return promisesKeys.keySet().every { it.isDone() }
}
@Override
- Promise<Map<K,V>> accept(Map<K,V> values) {
+ Promise<Map<K, V>> accept(Map<K, V> values) {
values.each { K key, Object value ->
if (value instanceof Promise) {
put(key, value as Promise<V>)
@@ -210,10 +210,10 @@ class PromiseMap<K,V> implements Promise<Map<K,V>> {
*
* @return A map where the values are obtained from the promises
*/
- Map<K,V> get() throws Throwable {
+ Map<K, V> get() throws Throwable {
def promises = promises.values()
- Map<K,V> resultMap = [:]
- for(Promise<V> promise : promises) {
+ Map<K, V> resultMap = [:]
+ for (Promise<V> promise : promises) {
V value = promise.get()
resultMap.put(promisesKeys.get(promise), value)
}
@@ -224,15 +224,15 @@ class PromiseMap<K,V> implements Promise<Map<K,V>> {
* Synchronously return the populated map with all values obtained from promises used
* inside the populated map
*
- * @param timeout The timeout period
+ * @param timeout The timeout period
* @param units The timeout units
* @return A map where the values are obtained from the promises
*/
- Map<K,V> get(long timeout, TimeUnit units) throws Throwable {
+ Map<K, V> get(long timeout, TimeUnit units) throws Throwable {
List<Promise<V>> promises = new ArrayList<Promise<V>>(promises.values())
Promises.waitAll(promises, timeout, units)
- Map<K,V> resultMap = [:]
- for(Promise<V> promise : promises) {
+ Map<K, V> resultMap = [:]
+ for (Promise<V> promise : promises) {
V value = promise.get()
resultMap.put(promisesKeys.get(promise), value)
}
@@ -240,12 +240,12 @@ class PromiseMap<K,V> implements Promise<Map<K,V>> {
}
@Override
- Promise<Map<K,V>> onComplete(Closure<Map<K,V>> callable) {
+ Promise<Map<K, V>> onComplete(Closure<Map<K, V>> callable) {
List<Promise<V>> promises = new ArrayList<Promise<V>>(promises.values())
Promises.onComplete(promises) { List<V> values ->
- Map<K,V> resultMap = [:]
+ Map<K, V> resultMap = [:]
int i = 0
- for(V value in values) {
+ for (V value in values) {
Promise<V> promise = promises[i]
K key = promisesKeys.get(promise)
resultMap.put(key, value)
@@ -258,13 +258,13 @@ class PromiseMap<K,V> implements Promise<Map<K,V>> {
}
@Override
- Promise<Map<K,V>> onError(Closure<Map<K,V>> callable) {
+ Promise<Map<K, V>> onError(Closure<Map<K, V>> callable) {
Promises.onError(new ArrayList<Promise<V>>(promises.values()), callable)
return this
}
@Override
- Promise<Map<K, V>> then(Closure<Map<K,V>> callable) {
+ Promise<Map<K, V>> then(Closure<Map<K, V>> callable) {
return onComplete(callable)
}
diff --git a/grails-async/core/src/main/groovy/grails/async/Promises.groovy b/grails-async/core/src/main/groovy/grails/async/Promises.groovy
index 6b3c209bf8..d5f125c68c 100644
--- a/grails-async/core/src/main/groovy/grails/async/Promises.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/Promises.groovy
@@ -51,79 +51,79 @@ class Promises {
}
/**
- * @see PromiseFactory#waitAll(grails.async.Promise[])
+ * @see PromiseFactory#waitAll(grails.async.Promise [ ])
*/
- static<T> List<T> waitAll(Promise<T>... promises) {
+ static <T> List<T> waitAll(Promise<T>... promises) {
return getPromiseFactory().waitAll(promises)
}
/**
* @see PromiseFactory#waitAll(java.util.List)
*/
- static<T> List<T> waitAll(List<Promise<T>> promises) {
+ static <T> List<T> waitAll(List<Promise<T>> promises) {
return getPromiseFactory().waitAll(promises)
}
/**
* @see PromiseFactory#waitAll(java.util.List)
*/
- static<T> List<T> waitAll(List<Promise<T>> promises, long timeout, TimeUnit units) {
+ static <T> List<T> waitAll(List<Promise<T>> promises, long timeout, TimeUnit units) {
return getPromiseFactory().waitAll(promises, timeout, units)
}
/**
* @see PromiseFactory#onComplete(java.util.List, groovy.lang.Closure)
*/
- static<T> Promise<List<T>> onComplete(List<Promise<T>> promises, Closure<T> callable) {
+ static <T> Promise<List<T>> onComplete(List<Promise<T>> promises, Closure<T> callable) {
return getPromiseFactory().onComplete(promises, callable)
}
/**
* @see PromiseFactory#onError(java.util.List, groovy.lang.Closure)
*/
- static<T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
+ static <T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
return getPromiseFactory().onError(promises, callable)
}
/**
* @see PromiseFactory#createPromise(java.util.Map)
*/
- static<K,V> Promise<Map<K,V>> createPromise(Map<K, V> map) {
+ static <K, V> Promise<Map<K, V>> createPromise(Map<K, V> map) {
return getPromiseFactory().createPromise(map)
}
/**
* @see PromiseFactory#createPromise(java.util.Map)
*/
- static<K,V> Promise<Map<K,V>> createPromise(Map<K, V> map, List<PromiseDecorator> decorators) {
+ static <K, V> Promise<Map<K, V>> createPromise(Map<K, V> map, List<PromiseDecorator> decorators) {
return getPromiseFactory().createPromise(map, decorators)
}
/**
- * @see PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<T> createPromise(Closure<T>... closures) {
+ static <T> Promise<T> createPromise(Closure<T>... closures) {
return getPromiseFactory().createPromise(closures)
}
/**
* @see PromiseFactory#createPromise(java.util.Map)
*/
- static<K,V> Promise<Map<K,V>> tasks(Map<K, V> map) {
+ static <K, V> Promise<Map<K, V>> tasks(Map<K, V> map) {
return getPromiseFactory().createPromise(map)
}
/**
- * @see PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<T> task(Closure<T> closure) {
+ static <T> Promise<T> task(Closure<T> closure) {
return getPromiseFactory().createPromise(closure)
}
/**
- * @see PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<T> tasks(Closure<T>... closures) {
+ static <T> Promise<T> tasks(Closure<T>... closures) {
return getPromiseFactory().createPromise(closures)
}
/**
- * @see PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<List<T>> tasks(List<Closure<T>> closures) {
+ static <T> Promise<List<T>> tasks(List<Closure<T>> closures) {
return getPromiseFactory().createPromise(closures)
}
@@ -137,33 +137,33 @@ class Promises {
/**
* @see grails.async.PromiseFactory#createPromise(Class)
*/
- static<T> Promise<T> createPromise(Class<T> returnType) {
+ static <T> Promise<T> createPromise(Class<T> returnType) {
return getPromiseFactory().createPromise(returnType)
}
/**
* @see PromiseFactory#createPromise(groovy.lang.Closure, java.util.List)
*/
- static<T> Promise<T> createPromise(Closure<T> closure, List<PromiseDecorator> decorators) {
+ static <T> Promise<T> createPromise(Closure<T> closure, List<PromiseDecorator> decorators) {
return getPromiseFactory().createPromise(closure, decorators)
}
/**
* @see PromiseFactory#createPromise(java.util.List, java.util.List)
*/
- static<T> Promise<List<T>> createPromise(List<Closure<T>> closures, List<PromiseDecorator> decorators) {
+ static <T> Promise<List<T>> createPromise(List<Closure<T>> closures, List<PromiseDecorator> decorators) {
return getPromiseFactory().createPromise(closures, decorators)
}
/**
- * @see PromiseFactory#createPromise(grails.async.Promise[])
+ * @see PromiseFactory#createPromise(grails.async.Promise [ ])
*/
- static <T> Promise<List<T>> createPromise(Promise<T>...promises) {
+ static <T> Promise<List<T>> createPromise(Promise<T>... promises) {
return getPromiseFactory().createPromise(promises)
}
/**
* @see PromiseFactory#createBoundPromise(java.lang.Object)
*/
- static<T> Promise<T> createBoundPromise(T value) {
- return getPromiseFactory().createBoundPromise(value)
+ static <T> Promise<T> createBoundPromise(T value) {
+ return getPromiseFactory().createBoundPromise(value)
}
}
diff --git a/grails-async/core/src/main/groovy/grails/async/factory/AbstractPromiseFactory.groovy b/grails-async/core/src/main/groovy/grails/async/factory/AbstractPromiseFactory.groovy
index bbd488348c..9b897b7941 100644
--- a/grails-async/core/src/main/groovy/grails/async/factory/AbstractPromiseFactory.groovy
+++ b/grails-async/core/src/main/groovy/grails/async/factory/AbstractPromiseFactory.groovy
@@ -59,13 +59,13 @@ abstract class AbstractPromiseFactory implements PromiseFactory {
}
<T> Closure<T> applyDecorators(Closure<T> closure, List<PromiseDecorator> decorators) {
- List<PromiseDecorator> allDecorators = decorators != null ? new ArrayList<PromiseDecorator>(decorators): new ArrayList<PromiseDecorator>()
+ List<PromiseDecorator> allDecorators = decorators != null ? new ArrayList<PromiseDecorator>(decorators) : new ArrayList<PromiseDecorator>()
for (PromiseDecoratorLookupStrategy lookupStrategy : lookupStrategies) {
allDecorators.addAll(lookupStrategy.findDecorators())
}
def decoratedClosure = closure
if (!allDecorators.empty) {
- for(PromiseDecorator decorator : allDecorators) {
+ for (PromiseDecorator decorator : allDecorators) {
decoratedClosure = decorator.decorate(decoratedClosure)
}
}
@@ -76,7 +76,7 @@ abstract class AbstractPromiseFactory implements PromiseFactory {
* @see PromiseFactory#createPromise(java.util.List)
*/
<T> Promise<List<T>> createPromise(List<Closure<T>> closures) {
- return createPromise(closures,null)
+ return createPromise(closures, null)
}
/**
@@ -95,11 +95,11 @@ abstract class AbstractPromiseFactory implements PromiseFactory {
}
/**
- * @see PromiseFactory#createPromise(grails.async.Promise[])
+ * @see PromiseFactory#createPromise(grails.async.Promise [ ])
*/
<T> Promise<List<T>> createPromise(Promise<T>... promises) {
PromiseList<T> promiseList = new PromiseList<>()
- for(Promise<T> promise : promises) {
+ for (Promise<T> promise : promises) {
promiseList.add(promise)
}
return promiseList
@@ -107,17 +107,15 @@ abstract class AbstractPromiseFactory implements PromiseFactory {
@Override
<K, V> Promise<Map<K, V>> createPromise(Map<K, V> map, List<PromiseDecorator> decorators) {
- PromiseMap<K,V> promiseMap = new PromiseMap<>()
+ PromiseMap<K, V> promiseMap = new PromiseMap<>()
map.forEach((K key, V value) -> {
if (value instanceof Promise) {
promiseMap.put(key, value as Promise<V>)
- }
- else if (value instanceof Closure) {
+ } else if (value instanceof Closure) {
Closure<V> closure = value as Closure<V>
applyDecorators(closure, decorators)
promiseMap.put(key, createPromiseInternal(closure))
- }
- else {
+ } else {
promiseMap.put(key, new BoundPromise<V>(value))
}
@@ -129,15 +127,15 @@ abstract class AbstractPromiseFactory implements PromiseFactory {
* @see PromiseFactory#createPromise(java.util.Map)
*/
<K, V> Promise<Map<K, V>> createPromise(Map<K, V> map) {
- return createPromise(map, Collections.<PromiseDecorator>emptyList())
+ return createPromise(map, Collections.<PromiseDecorator> emptyList())
}
protected <T> Promise<T> createPromiseInternal(Closure<T> closure) {
- return createPromise(closure)
+ return createPromise(closure)
}
/**
- * @see PromiseFactory#waitAll(grails.async.Promise[])
+ * @see PromiseFactory#waitAll(grails.async.Promise [ ])
*/
<T> List<T> waitAll(Promise<T>... promises) {
return waitAll(Arrays.asList(promises))
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/BoundPromise.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/BoundPromise.groovy
index e693655567..6759d6e9be 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/BoundPromise.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/BoundPromise.groovy
@@ -91,8 +91,7 @@ class BoundPromise<T> implements Promise<T> {
} catch (Throwable e) {
return new BoundPromise(e)
}
- }
- else {
+ } else {
return this
}
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/PromiseFactoryBuilder.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/PromiseFactoryBuilder.groovy
index 3ca1066012..3c5905fee8 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/PromiseFactoryBuilder.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/PromiseFactoryBuilder.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory
import grails.async.PromiseFactory
@@ -43,11 +42,10 @@ class PromiseFactoryBuilder {
List<PromiseFactory> promiseFactories = ServiceLoader.load(PromiseFactory).toList()
PromiseFactory promiseFactory
- if(promiseFactories.isEmpty()) {
+ if (promiseFactories.isEmpty()) {
log.debug 'No PromiseFactory implementation found. Using default ExecutorService promise factory.'
promiseFactory = new CachedThreadPoolPromiseFactory()
- }
- else {
+ } else {
promiseFactory = promiseFactories.first()
log.debug 'Found PromiseFactory implementation to use [{}]', promiseFactory
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromise.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromise.groovy
index fe1dd1a989..714fe0be40 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromise.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromise.groovy
@@ -58,8 +58,12 @@ class SynchronousPromise<T> implements Promise<T> {
T get() throws Throwable {
if (!executed) {
executed = true
- try { value = callable.call() }
- catch (e) { value = e }
+ try {
+ value = callable.call()
+ }
+ catch (e) {
+ value = e
+ }
}
if (value instanceof Throwable) {
throw value
@@ -78,14 +82,21 @@ class SynchronousPromise<T> implements Promise<T> {
}
Promise<T> onComplete(Closure<T> callable) {
- try { callable.call(get()) }
- catch (Throwable ignored) {}
+ try {
+ callable.call(get())
+ }
+ catch (Throwable ignored) {
+ }
return this
}
Promise<T> onError(Closure<T> callable) {
- try { get() }
- catch (Throwable e) { callable.call(e) }
+ try {
+ get()
+ }
+ catch (Throwable e) {
+ callable.call(e)
+ }
return this
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromiseFactory.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromiseFactory.groovy
index fe4d94e9ab..cc15554db1 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromiseFactory.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/SynchronousPromiseFactory.groovy
@@ -54,14 +54,17 @@ class SynchronousPromiseFactory extends AbstractPromiseFactory {
promise = new SynchronousPromise<T>(closures[0])
} else {
def promiseList = new PromiseList()
- for(p in closures) {
+ for (p in closures) {
promiseList << p
}
promise = promiseList
}
- try { promise.get() }
- catch (Throwable ignored) {}
+ try {
+ promise.get()
+ }
+ catch (Throwable ignored) {
+ }
return promise
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/future/CachedThreadPoolPromiseFactory.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/future/CachedThreadPoolPromiseFactory.groovy
index affba64fb2..cb77596aeb 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/future/CachedThreadPoolPromiseFactory.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/future/CachedThreadPoolPromiseFactory.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.future
import grails.async.Promise
@@ -39,15 +38,18 @@ import java.util.concurrent.*
@CompileStatic
class CachedThreadPoolPromiseFactory extends AbstractPromiseFactory implements Closeable, ExecutorPromiseFactory {
- final @Delegate ExecutorService executorService
+ @Delegate
+ final ExecutorService executorService
CachedThreadPoolPromiseFactory(int maxPoolSize = Integer.MAX_VALUE, long timeout = 60L, TimeUnit unit = TimeUnit.SECONDS) {
CachedThreadPoolPromiseFactory pf = this
this.executorService = new ThreadPoolExecutor(0, maxPoolSize, timeout, unit, new SynchronousQueue<Runnable>()) {
+
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTaskPromise<T>(pf, callable)
}
+
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTaskPromise<T>(pf, runnable, value)
@@ -71,8 +73,7 @@ class CachedThreadPoolPromiseFactory extends AbstractPromiseFactory implements C
def callable = closures[0]
def decoratedCallable = applyDecorators(callable, null)
return executorService.submit(decoratedCallable as Callable) as Promise<T>
- }
- else {
+ } else {
PromiseList<T> list = new PromiseList<>()
for (Closure<T> closure : closures) {
list.add(closure)
@@ -108,7 +109,11 @@ class CachedThreadPoolPromiseFactory extends AbstractPromiseFactory implements C
while (promises.every { Promise promise -> !promise.isDone() }) {
// wait (is this hogging the cpu?)
}
- try { for (Promise<T> promise : promises) { promise.get() } }
+ try {
+ for (Promise<T> promise : promises) {
+ promise.get()
+ }
+ }
catch (Throwable e) {
callable.call(e)
return e
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/future/ExecutorPromiseFactory.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/future/ExecutorPromiseFactory.groovy
index 7167d9e4ea..4172ada0f9 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/future/ExecutorPromiseFactory.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/future/ExecutorPromiseFactory.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.future
import grails.async.PromiseFactory
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskChildPromise.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskChildPromise.groovy
index d0ce580e97..47c07d05ee 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskChildPromise.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskChildPromise.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.future
import grails.async.Promise
@@ -54,7 +53,7 @@ class FutureTaskChildPromise<T> implements Promise<T> {
FutureTaskChildPromise(PromiseFactory promiseFactory, Promise<T> parent, Closure<T> callable) {
this.parent = parent
- this.callable = promiseFactory.applyDecorators(callable,null)
+ this.callable = promiseFactory.applyDecorators(callable, null)
this.promiseFactory = promiseFactory
}
@@ -113,8 +112,7 @@ class FutureTaskChildPromise<T> implements Promise<T> {
T get() throws InterruptedException, ExecutionException {
if (bound != null) {
return bound.get()
- }
- else {
+ } else {
if (parent instanceof FutureTaskPromise) {
def value = parent.get()
if (bound == null) {
@@ -122,8 +120,7 @@ class FutureTaskChildPromise<T> implements Promise<T> {
bound = new BoundPromise<>(v)
}
return bound.get()
- }
- else {
+ } else {
def v = callable.call(parent.get())
bound = new BoundPromise<>(v)
return v
@@ -135,8 +132,7 @@ class FutureTaskChildPromise<T> implements Promise<T> {
T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (bound != null) {
return bound.get()
- }
- else {
+ } else {
if (parent instanceof FutureTaskPromise) {
def value = parent.get(timeout, unit)
if (bound == null) {
@@ -144,8 +140,7 @@ class FutureTaskChildPromise<T> implements Promise<T> {
bound = new BoundPromise<>(v)
}
return bound.get()
- }
- else {
+ } else {
def v = callable.call(parent.get(timeout, unit))
bound = new BoundPromise<>(v)
return v
diff --git a/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskPromise.groovy b/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskPromise.groovy
index 90cde68202..466fad6e00 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskPromise.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/factory/future/FutureTaskPromise.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.future
import grails.async.Promise
@@ -110,8 +109,7 @@ class FutureTaskPromise<T> extends FutureTask<T> implements Promise<T> {
} catch (Throwable ignored) {
return this
}
- }
- else {
+ } else {
Promise<T> newPromise = new FutureTaskChildPromise(promiseFactory, this as Promise<T>, callable)
successCallbacks.add(newPromise)
return newPromise
@@ -129,8 +127,7 @@ class FutureTaskPromise<T> extends FutureTask<T> implements Promise<T> {
} catch (Throwable e) {
return new BoundPromise(callable.call(e))
}
- }
- else {
+ } else {
Promise<T> newPromise = new FutureTaskChildPromise(promiseFactory, this as Promise<T>, callable)
failureCallbacks.add(newPromise)
return newPromise
diff --git a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransactionalMethodTransformer.java b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransactionalMethodTransformer.java
index 63c9e10419..f01caf4057 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransactionalMethodTransformer.java
+++ b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransactionalMethodTransformer.java
@@ -29,5 +29,6 @@ import org.codehaus.groovy.ast.expr.ListExpression;
* @since 2.3
*/
public interface DelegateAsyncTransactionalMethodTransformer {
+
void transformTransactionalMethod(ClassNode classNode, ClassNode delegateClassNode, MethodNode methodNode, ListExpression promiseDecoratorLookupArguments);
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.java b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.java
index 74fd98d37d..936e086086 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.java
+++ b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncTransformation.java
@@ -67,10 +67,11 @@ import org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport;
*/
@GroovyASTTransformation
public class DelegateAsyncTransformation implements ASTTransformation, TransformWithPriority {
- private static final ArgumentListExpression NO_ARGS = new ArgumentListExpression();
- private static final String VOID = "void";
+
public static final ClassNode GROOVY_OBJECT_CLASS_NODE = new ClassNode(GroovyObjectSupport.class);
public static final ClassNode OBJECT_CLASS_NODE = new ClassNode(Object.class);
+ private static final ArgumentListExpression NO_ARGS = new ArgumentListExpression();
+ private static final String VOID = "void";
public void visit(ASTNode[] nodes, SourceUnit source) {
if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
@@ -84,7 +85,7 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
Expression value = annotationNode.getMember("value");
if (value instanceof ClassExpression) {
ClassNode targetApi = value.getType().getPlainNodeReference();
- ClassNode classNode = (ClassNode)parent;
+ ClassNode classNode = (ClassNode) parent;
final String fieldName = '$' + Introspector.decapitalize(targetApi.getNameWithoutPackage());
FieldNode fieldNode = classNode.getField(fieldName);
@@ -95,9 +96,8 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
applyDelegateAsyncTransform(classNode, targetApi, fieldName);
}
- }
- else if(parent instanceof FieldNode) {
- FieldNode fieldNode = (FieldNode)parent;
+ } else if (parent instanceof FieldNode) {
+ FieldNode fieldNode = (FieldNode) parent;
ClassNode targetApi = fieldNode.getType().getPlainNodeReference();
ClassNode classNode = fieldNode.getOwner();
applyDelegateAsyncTransform(classNode, targetApi, fieldNode.getName());
@@ -112,27 +112,26 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
MethodNode createPromiseMethodTargetWithDecorators = promisesClass.getDeclaredMethod("createPromise", new Parameter[]{new Parameter(new ClassNode(Closure.class), "c"), new Parameter(new ClassNode(List.class), "c")});
DelegateAsyncTransactionalMethodTransformer delegateAsyncTransactionalMethodTransformer = lookupAsyncTransactionalMethodTransformer();
- for(MethodNode m : methods) {
+ for (MethodNode m : methods) {
if (isCandidateMethod(m)) {
MethodNode existingMethod = classNode.getMethod(m.getName(), m.getParameters());
if (existingMethod == null) {
ClassNode promiseNode = ClassHelper.make(Promise.class).getPlainNodeReference();
ClassNode originalReturnType = m.getReturnType();
- if(!originalReturnType.getNameWithoutPackage().equals(VOID)) {
+ if (!originalReturnType.getNameWithoutPackage().equals(VOID)) {
ClassNode returnType;
- if(ClassHelper.isPrimitiveType(originalReturnType.redirect())) {
+ if (ClassHelper.isPrimitiveType(originalReturnType.redirect())) {
returnType = ClassHelper.getWrapper(originalReturnType.redirect());
} else {
returnType = alignReturnType(classNode, originalReturnType);
}
- if(!OBJECT_CLASS_NODE.equals(returnType)) {
+ if (!OBJECT_CLASS_NODE.equals(returnType)) {
promiseNode.setGenericsTypes(new GenericsType[]{new GenericsType(returnType)});
}
}
final BlockStatement methodBody = new BlockStatement();
final BlockStatement promiseBody = new BlockStatement();
-
final ClosureExpression closureExpression = new ClosureExpression(new Parameter[0], promiseBody);
VariableScope variableScope = new VariableScope();
closureExpression.setVariableScope(variableScope);
@@ -147,8 +146,8 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
MethodCallExpression getDecoratorsMethodCall = new MethodCallExpression(new ClassExpression(delegateAsyncUtilsClassNode), "getPromiseDecorators", getPromiseDecoratorsArguments);
getDecoratorsMethodCall.setMethodTarget(getPromiseDecoratorsMethodNode);
- MethodCallExpression createPromiseWithDecorators = new MethodCallExpression(new ClassExpression(promisesClass), "createPromise",new ArgumentListExpression( closureExpression, getDecoratorsMethodCall));
- if(createPromiseMethodTargetWithDecorators != null) {
+ MethodCallExpression createPromiseWithDecorators = new MethodCallExpression(new ClassExpression(promisesClass), "createPromise", new ArgumentListExpression(closureExpression, getDecoratorsMethodCall));
+ if (createPromiseMethodTargetWithDecorators != null) {
createPromiseWithDecorators.setMethodTarget(createPromiseMethodTargetWithDecorators);
}
methodBody.addStatement(new ExpressionStatement(createPromiseWithDecorators));
@@ -156,7 +155,7 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
final ArgumentListExpression arguments = new ArgumentListExpression();
Parameter[] parameters = copyParameters(StaticTypeCheckingSupport.parameterizeArguments(classNode, m));
- for(Parameter p : parameters) {
+ for (Parameter p : parameters) {
p.setClosureSharedVariable(true);
variableScope.putReferencedLocalVariable(p);
VariableExpression ve = new VariableExpression(p);
@@ -165,7 +164,7 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
}
MethodCallExpression delegateMethodCall = new MethodCallExpression(new VariableExpression(fieldName), m.getName(), arguments);
promiseBody.addStatement(new ExpressionStatement(delegateMethodCall));
- MethodNode newMethodNode = new MethodNode(m.getName(), Modifier.PUBLIC,promiseNode, parameters,null, methodBody);
+ MethodNode newMethodNode = new MethodNode(m.getName(), Modifier.PUBLIC, promiseNode, parameters, null, methodBody);
classNode.addMethod(newMethodNode);
}
}
@@ -183,7 +182,7 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
GenericsType[] redirectReceiverTypes = redirectTypes.toArray(new GenericsType[0]);
GenericsType[] receiverParameterizedTypes = receiver.getGenericsTypes();
- if (receiverParameterizedTypes==null) {
+ if (receiverParameterizedTypes == null) {
receiverParameterizedTypes = redirectReceiverTypes;
}
@@ -210,9 +209,9 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
private static boolean isCandidateMethod(MethodNode declaredMethod) {
String methodName = declaredMethod.getName();
return !declaredMethod.isSynthetic() &&
- !methodName.contains("$") &&
- Modifier.isPublic(declaredMethod.getModifiers()) &&
- !GROOVY_OBJECT_CLASS_NODE.hasMethod(declaredMethod.getName(), declaredMethod.getParameters());
+ !methodName.contains("$") &&
+ Modifier.isPublic(declaredMethod.getModifiers()) &&
+ !GROOVY_OBJECT_CLASS_NODE.hasMethod(declaredMethod.getName(), declaredMethod.getParameters());
}
private static Parameter[] copyParameters(Parameter[] parameterTypes) {
@@ -221,7 +220,7 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
Parameter parameterType = parameterTypes[i];
ClassNode parameterTypeCN = parameterType.getType();
ClassNode newParameterTypeCN = parameterTypeCN.getPlainNodeReference();
- if(parameterTypeCN.isUsingGenerics() && !parameterTypeCN.isGenericsPlaceHolder()) {
+ if (parameterTypeCN.isUsingGenerics() && !parameterTypeCN.isGenericsPlaceHolder()) {
newParameterTypeCN.setGenericsTypes(parameterTypeCN.getGenericsTypes());
}
Parameter newParameter = new Parameter(newParameterTypeCN, parameterType.getName(), parameterType.getInitialExpression());
@@ -237,7 +236,8 @@ public class DelegateAsyncTransformation implements ASTTransformation, Transform
}
private static class NoopDelegateAsyncTransactionalMethodTransformer implements DelegateAsyncTransactionalMethodTransformer {
- public void transformTransactionalMethod(ClassNode classNode,ClassNode delegateClassNode, MethodNode methodNode, ListExpression promiseDecoratorLookupArguments) {
+
+ public void transformTransactionalMethod(ClassNode classNode, ClassNode delegateClassNode, MethodNode methodNode, ListExpression promiseDecoratorLookupArguments) {
// noop
}
}
diff --git a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncUtils.groovy b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncUtils.groovy
index 7041c066f1..7cd33f80c2 100644
--- a/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncUtils.groovy
+++ b/grails-async/core/src/main/groovy/org/grails/async/transform/internal/DelegateAsyncUtils.groovy
@@ -37,10 +37,10 @@ class DelegateAsyncUtils {
* @param additional The additional
* @return The additional promise decorators
*/
- static Collection<PromiseDecorator> getPromiseDecorators(Object target, Collection<PromiseDecorator> additional ) {
+ static Collection<PromiseDecorator> getPromiseDecorators(Object target, Collection<PromiseDecorator> additional) {
Collection<PromiseDecorator> decorators = []
if (target instanceof PromiseDecoratorProvider) {
- decorators.addAll(((PromiseDecoratorProvider)target).getDecorators())
+ decorators.addAll(((PromiseDecoratorProvider) target).getDecorators())
}
if (additional) {
decorators.addAll(additional)
diff --git a/grails-async/gpars/build.gradle b/grails-async/gpars/build.gradle
index ab599f3da3..335871bda0 100644
--- a/grails-async/gpars/build.gradle
+++ b/grails-async/gpars/build.gradle
@@ -50,4 +50,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromise.groovy b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromise.groovy
index ed1731ea11..9d02d2e1b4 100644
--- a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromise.groovy
+++ b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromise.groovy
@@ -51,7 +51,7 @@ class GparsPromise<T> implements Promise<T> {
@Override
boolean cancel(boolean mayInterruptIfRunning) {
- if(isDone()) return false
+ if (isDone()) return false
throw new UnsupportedOperationException('Cancellation not supported')
}
@@ -77,7 +77,7 @@ class GparsPromise<T> implements Promise<T> {
@Override
Promise<T> accept(T value) {
- internalPromise = Dataflow.task({value})
+ internalPromise = Dataflow.task({ value })
return this
}
@@ -87,7 +87,7 @@ class GparsPromise<T> implements Promise<T> {
@Override
Promise<T> onComplete(Closure<T> callable) {
- def decoratedCallable= promiseFactory.applyDecorators(callable, null)
+ def decoratedCallable = promiseFactory.applyDecorators(callable, null)
internalPromise.whenBound { T value ->
if (!(value instanceof Throwable)) {
return decoratedCallable.call(value)
diff --git a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy
index 1782c75948..66d51c1f15 100644
--- a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy
+++ b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy
@@ -42,16 +42,24 @@ class GparsPromiseFactory extends AbstractPromiseFactory {
static final boolean GPARS_PRESENT
static {
- try { GPARS_PRESENT = Thread.currentThread().contextClassLoader.loadClass('groovyx.gpars.GParsConfig') }
- catch (Throwable ignore) { GPARS_PRESENT = false }
+ try {
+ GPARS_PRESENT = Thread.currentThread().contextClassLoader.loadClass('groovyx.gpars.GParsConfig')
+ }
+ catch (Throwable ignore) {
+ GPARS_PRESENT = false
+ }
}
+
static boolean isGparsAvailable() { GPARS_PRESENT }
private static final Closure<List<?>> originalValuesClosure = { List<?> values -> values } as Closure<List<?>>
GparsPromiseFactory() {
- try { GParsConfig.setPoolFactory(new LoggingPoolFactory()) }
- catch (IllegalArgumentException ignore) {}
+ try {
+ GParsConfig.setPoolFactory(new LoggingPoolFactory())
+ }
+ catch (IllegalArgumentException ignore) {
+ }
}
@Override
@@ -75,7 +83,7 @@ class GparsPromiseFactory extends AbstractPromiseFactory {
<T> Promise<T> createPromise(Closure<T>... closures) {
if (closures.length == 1) {
def callable = closures[0]
- return new GparsPromise(this, applyDecorators(callable,null))
+ return new GparsPromise(this, applyDecorators(callable, null))
}
PromiseList<T> promiseList = new PromiseList<>()
for (c in closures) {
@@ -105,16 +113,16 @@ class GparsPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> onComplete(List<Promise<T>> promises, Closure<T> callable) {
return new GparsPromise<T>(
- this,
- Dataflow.whenAllBound(toGparsPromises(promises), callable as Closure)
+ this,
+ Dataflow.whenAllBound(toGparsPromises(promises), callable as Closure)
)
}
@Override
<T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
return new GparsPromise<List<T>>(
- this,
- Dataflow.whenAllBound(toGparsPromises(promises), {} as Closure<T>, callable as Closure<T>)
+ this,
+ Dataflow.whenAllBound(toGparsPromises(promises), {} as Closure<T>, callable as Closure<T>)
)
}
}
diff --git a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/LoggingPoolFactory.groovy b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/LoggingPoolFactory.groovy
index c97b8cdc55..b5dfbe2163 100644
--- a/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/LoggingPoolFactory.groovy
+++ b/grails-async/gpars/src/main/groovy/org/grails/async/factory/gpars/LoggingPoolFactory.groovy
@@ -74,18 +74,20 @@ class LoggingPoolFactory implements PoolFactory {
* Creates a fixed-thread pool of given size. Each thread will have the uncaught exception handler set
* to print the unhandled exception to standard error output.
*
- * @param daemon Sets the daemon flag of threads in the pool.
+ * @param daemon Sets the daemon flag of threads in the pool.
* @param poolSize The required pool size @return The created thread pool
* @return The newly created thread pool
*/
private static ThreadPoolExecutor createResizeablePool(boolean daemon, int poolSize) {
assert poolSize > 0;
return new ThreadPoolExecutor(poolSize, 1000, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
+
@Override
Thread newThread(Runnable r) {
Thread thread = new Thread(r, createThreadNameMethod.invoke(DefaultPool).toString())
thread.daemon = daemon
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+
@Override
void uncaughtException(Thread t, Throwable e) {
LOG.error("Async execution error: ${e.message}", e)
@@ -94,11 +96,12 @@ class LoggingPoolFactory implements PoolFactory {
return thread
}
}, new RejectedExecutionHandler() {
+
@Override
void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
throw new IllegalStateException("The thread pool executor cannot run the task. " +
- "The upper limit of the thread pool size has probably been reached. " +
- "Current pool size: $executor.poolSize Maximum pool size: $executor.maximumPoolSize")
+ "The upper limit of the thread pool size has probably been reached. " +
+ "Current pool size: $executor.poolSize Maximum pool size: $executor.maximumPoolSize")
}
})
}
diff --git a/grails-async/plugin/build.gradle b/grails-async/plugin/build.gradle
index f8ff94c033..aaa17fcb75 100644
--- a/grails-async/plugin/build.gradle
+++ b/grails-async/plugin/build.gradle
@@ -60,4 +60,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/plugin/src/main/groovy/grails/async/services/PersistenceContextPromiseDecorator.groovy b/grails-async/plugin/src/main/groovy/grails/async/services/PersistenceContextPromiseDecorator.groovy
index abbc3a8e65..f2cf6d70b8 100644
--- a/grails-async/plugin/src/main/groovy/grails/async/services/PersistenceContextPromiseDecorator.groovy
+++ b/grails-async/plugin/src/main/groovy/grails/async/services/PersistenceContextPromiseDecorator.groovy
@@ -29,7 +29,8 @@ import grails.async.decorator.PromiseDecorator
* @since 2.3
*/
@CompileStatic
-class PersistenceContextPromiseDecorator implements PromiseDecorator{
+class PersistenceContextPromiseDecorator implements PromiseDecorator {
+
PersistenceContextInterceptorExecutor persistenceContextInterceptorExecutor
PersistenceContextPromiseDecorator(PersistenceContextInterceptorExecutor persistenceContextInterceptorExecutor) {
diff --git a/grails-async/plugin/src/main/groovy/grails/async/services/TransactionalPromiseDecorator.groovy b/grails-async/plugin/src/main/groovy/grails/async/services/TransactionalPromiseDecorator.groovy
index 7032c4a247..9f1de6154a 100644
--- a/grails-async/plugin/src/main/groovy/grails/async/services/TransactionalPromiseDecorator.groovy
+++ b/grails-async/plugin/src/main/groovy/grails/async/services/TransactionalPromiseDecorator.groovy
@@ -45,7 +45,8 @@ import java.lang.reflect.Method
class TransactionalPromiseDecorator implements PromiseDecorator, TransactionDefinition {
PlatformTransactionManager transactionManager
- @Delegate DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition()
+ @Delegate
+ DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition()
TransactionalPromiseDecorator(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager
@@ -78,7 +79,7 @@ class TransactionalPromiseDecorator implements PromiseDecorator, TransactionDefi
@Override
<D> Closure<D> decorate(Closure<D> original) {
if (transactionManager != null) {
- return (Closure<D>){ args ->
+ return (Closure<D>) { args ->
def transactionTemplate = transactionDefinition != null ? new TransactionTemplate(transactionManager, transactionDefinition) : new TransactionTemplate(transactionManager)
transactionTemplate.execute({
original.call(args)
diff --git a/grails-async/plugin/src/main/groovy/grails/async/web/AsyncController.groovy b/grails-async/plugin/src/main/groovy/grails/async/web/AsyncController.groovy
index be3bbe2b0b..c441bfed4d 100644
--- a/grails-async/plugin/src/main/groovy/grails/async/web/AsyncController.groovy
+++ b/grails-async/plugin/src/main/groovy/grails/async/web/AsyncController.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.async.web
import groovy.transform.CompileStatic
@@ -45,7 +44,7 @@ trait AsyncController {
* @return a new {@link javax.servlet.AsyncContext}
*/
AsyncContext startAsync() {
- GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes()
+ GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes()
HttpServletRequest request = webRequest.currentRequest
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request)
diff --git a/grails-async/plugin/src/main/groovy/grails/async/web/AsyncGrailsWebRequest.groovy b/grails-async/plugin/src/main/groovy/grails/async/web/AsyncGrailsWebRequest.groovy
index 7266d21403..760a41951b 100644
--- a/grails-async/plugin/src/main/groovy/grails/async/web/AsyncGrailsWebRequest.groovy
+++ b/grails-async/plugin/src/main/groovy/grails/async/web/AsyncGrailsWebRequest.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.async.web
import groovy.transform.CompileStatic
@@ -42,7 +41,8 @@ import java.util.function.Consumer
* @since 3.0
*/
@CompileStatic
-class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest, AsyncListener{
+class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest, AsyncListener {
+
static final String WEB_REQUEST = "org.grails.ASYNC_WEB_REQUEST"
Long timeout
@@ -97,7 +97,7 @@ class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest,
@Override
void startAsync() {
Assert.state(request.asyncSupported, "The current request does not support Async processing")
- if(!isAsyncStarted()) {
+ if (!isAsyncStarted()) {
asyncContext = request.startAsync(request, response)
asyncContext.addListener(this)
}
@@ -110,8 +110,8 @@ class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest,
@Override
void dispatch() {
- Assert.notNull this.asyncContext, "Cannot dispatch without an AsyncContext"
- asyncContext.dispatch()
+ Assert.notNull this.asyncContext, "Cannot dispatch without an AsyncContext"
+ asyncContext.dispatch()
}
@Override
@@ -121,7 +121,7 @@ class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest,
@Override
void onComplete(AsyncEvent event) throws IOException {
- for(handler in completionHandlers) {
+ for (handler in completionHandlers) {
handler.run()
}
asyncContext = null
@@ -130,7 +130,7 @@ class AsyncGrailsWebRequest extends GrailsWebRequest implements AsyncWebRequest,
@Override
void onTimeout(AsyncEvent event) throws IOException {
- for(handler in timeoutHandlers) {
+ for (handler in timeoutHandlers) {
handler.run()
}
}
diff --git a/grails-async/plugin/src/main/groovy/grails/async/web/WebPromises.groovy b/grails-async/plugin/src/main/groovy/grails/async/web/WebPromises.groovy
index 7a923d03d1..4b19afa345 100644
--- a/grails-async/plugin/src/main/groovy/grails/async/web/WebPromises.groovy
+++ b/grails-async/plugin/src/main/groovy/grails/async/web/WebPromises.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.async.web
import grails.async.Promise
@@ -32,7 +31,7 @@ import java.util.concurrent.TimeUnit
* A specific promises factory class designed for use in controllers and other web contexts
*
* @since 3.2.7
- * @author Graeme Rocher
+ * @author Graeme Rocher
*/
@CompileStatic
class WebPromises {
@@ -57,73 +56,73 @@ class WebPromises {
private WebPromises() {}
/**
- * @see grails.async.PromiseFactory#waitAll(grails.async.Promise[])
+ * @see grails.async.PromiseFactory#waitAll(grails.async.Promise [ ])
*/
- static<T> List<T> waitAll(Promise<T>...promises) {
+ static <T> List<T> waitAll(Promise<T>... promises) {
return getPromiseFactory().waitAll(promises)
}
/**
* @see grails.async.PromiseFactory#waitAll(java.util.List)
*/
- static<T> List<T> waitAll(List<Promise<T>> promises) {
+ static <T> List<T> waitAll(List<Promise<T>> promises) {
return getPromiseFactory().waitAll(promises)
}
/**
* @see grails.async.PromiseFactory#waitAll(java.util.List)
*/
- static<T> List<T> waitAll(List<Promise<T>> promises, final long timeout, final TimeUnit units) {
+ static <T> List<T> waitAll(List<Promise<T>> promises, final long timeout, final TimeUnit units) {
return getPromiseFactory().waitAll(promises, timeout, units)
}
/**
* @see grails.async.PromiseFactory#onComplete(java.util.List, groovy.lang.Closure)
*/
- static<T> Promise<List<T>> onComplete(List<Promise<T>> promises, Closure<T> callable) {
+ static <T> Promise<List<T>> onComplete(List<Promise<T>> promises, Closure<T> callable) {
return getPromiseFactory().onComplete(promises, callable)
}
/**
* @see grails.async.PromiseFactory#onError(java.util.List, groovy.lang.Closure)
*/
- static<T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
+ static <T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
return getPromiseFactory().onError(promises, callable)
}
/**
* @see grails.async.PromiseFactory#createPromise(java.util.Map)
*/
- static<K,V> Promise<Map<K,V>> createPromise(Map<K, V> map) {
+ static <K, V> Promise<Map<K, V>> createPromise(Map<K, V> map) {
return getPromiseFactory().createPromise(map, DECORATOR_LOOKUP.findDecorators())
}
/**
- * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<List<T>> createPromise(Closure<T>... c) {
+ static <T> Promise<List<T>> createPromise(Closure<T>... c) {
return getPromiseFactory().createPromise(Arrays.asList(c), DECORATOR_LOOKUP.findDecorators())
}
/**
* @see grails.async.PromiseFactory#createPromise(java.util.Map)
*/
- static<K,V> Promise<Map<K,V>> tasks(Map<K, V> map) {
+ static <K, V> Promise<Map<K, V>> tasks(Map<K, V> map) {
return createPromise(map)
}
/**
- * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<T> task(Closure<T> c) {
+ static <T> Promise<T> task(Closure<T> c) {
return getPromiseFactory().createPromise(c, DECORATOR_LOOKUP.findDecorators())
}
/**
- * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<List<T>> tasks(Closure<T>... c) {
+ static <T> Promise<List<T>> tasks(Closure<T>... c) {
return createPromise(c)
}
/**
- * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure[])
+ * @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure [ ])
*/
- static<T> Promise<List<T>> tasks(List<Closure<T>> closures) {
+ static <T> Promise<List<T>> tasks(List<Closure<T>> closures) {
return getPromiseFactory().createPromise(closures, DECORATOR_LOOKUP.findDecorators())
}
@@ -137,33 +136,33 @@ class WebPromises {
/**
* @see grails.async.PromiseFactory#createPromise(Class)
*/
- static<T> Promise<T> createPromise(Class<T> returnType) {
+ static <T> Promise<T> createPromise(Class<T> returnType) {
return getPromiseFactory().createPromise(returnType)
}
/**
* @see grails.async.PromiseFactory#createPromise(groovy.lang.Closure, java.util.List)
*/
- static<T> Promise<T> createPromise(Closure<T> c, List<PromiseDecorator> decorators) {
+ static <T> Promise<T> createPromise(Closure<T> c, List<PromiseDecorator> decorators) {
return getPromiseFactory().createPromise(c, DECORATOR_LOOKUP.findDecorators())
}
/**
* @see grails.async.PromiseFactory#createPromise(java.util.List, java.util.List)
*/
- static<T> Promise<List<T>> createPromise(List<Closure<T>> closures, List<PromiseDecorator> decorators) {
+ static <T> Promise<List<T>> createPromise(List<Closure<T>> closures, List<PromiseDecorator> decorators) {
return getPromiseFactory().createPromise(closures, DECORATOR_LOOKUP.findDecorators())
}
/**
- * @see grails.async.PromiseFactory#createPromise(grails.async.Promise[])
+ * @see grails.async.PromiseFactory#createPromise(grails.async.Promise [ ])
*/
- static <T> Promise<List<T>> createPromise(Promise<T>...promises) {
+ static <T> Promise<List<T>> createPromise(Promise<T>... promises) {
return getPromiseFactory().createPromise(promises)
}
/**
* @see grails.async.PromiseFactory#createBoundPromise(java.lang.Object)
*/
- static<T> Promise<T> createBoundPromise(T value) {
+ static <T> Promise<T> createBoundPromise(T value) {
return getPromiseFactory().createBoundPromise(value)
}
}
diff --git a/grails-async/plugin/src/main/groovy/org/grails/async/transform/internal/DefaultDelegateAsyncTransactionalMethodTransformer.groovy b/grails-async/plugin/src/main/groovy/org/grails/async/transform/internal/DefaultDelegateAsyncTransactionalMethodTransformer.groovy
index 2630bc9599..bbd279fe24 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/async/transform/internal/DefaultDelegateAsyncTransactionalMethodTransformer.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/async/transform/internal/DefaultDelegateAsyncTransactionalMethodTransformer.groovy
@@ -65,7 +65,7 @@ class DefaultDelegateAsyncTransactionalMethodTransformer implements DelegateAsyn
private static final ClassNode CLASS_NODE_MAP = new ClassNode(Map.class).getPlainNodeReference()
private static final String METHOD_NAME_SET_TRANSACTION_MANAGER = "setTransactionManager"
private static final VariableExpression EXPRESSION_THIS = new VariableExpression("this")
- private static final Token OPERATOR_ASSIGNMENT = new Token(Types.EQUAL,"=", -1,-1)
+ private static final Token OPERATOR_ASSIGNMENT = new Token(Types.EQUAL, "=", -1, -1)
private static final String VARIABLE_TRANSACTION_MANAGER = "txMgr"
private FieldNode transactionalField
private boolean isTransactional = false
@@ -73,14 +73,14 @@ class DefaultDelegateAsyncTransactionalMethodTransformer implements DelegateAsyn
private int promiseDecoratorCount = 0
@Override
- void transformTransactionalMethod(ClassNode classNode,ClassNode delegateClassNode, MethodNode methodNode, ListExpression promiseDecorators) {
+ void transformTransactionalMethod(ClassNode classNode, ClassNode delegateClassNode, MethodNode methodNode, ListExpression promiseDecorators) {
if (transactionalField == null) {
transactionalField = delegateClassNode.getField(TRANSACTIONAL_FIELD)
isTransactional = false
- if(transactionalField) {
+ if (transactionalField) {
def ie = transactionalField.getInitialExpression()
- if(ie instanceof ConstantExpression) {
+ if (ie instanceof ConstantExpression) {
isTransactional = ie.isTrueExpression()
}
}
@@ -92,30 +92,29 @@ class DefaultDelegateAsyncTransactionalMethodTransformer implements DelegateAsyn
int currentIndex = promiseDecoratorCount++
-
final methodLookupArguments = new ArgumentListExpression(new ConstantExpression(methodNode.getName()))
- for(Parameter p in methodNode.getParameters()) {
+ for (Parameter p in methodNode.getParameters()) {
methodLookupArguments.addExpression(new ClassExpression(p.getType().getPlainNodeReference()))
}
final promiseLookupExpression = new BinaryExpression(new PropertyExpression(EXPRESSION_THIS, FIELD_NAME_PROMISE_DECORATORS), Token.newSymbol(Types.LEFT_SQUARE_BRACKET, -1, -1), new ConstantExpression(currentIndex))
setTransactionManagerMethodBody.addStatement(
- new ExpressionStatement(
- new BinaryExpression(
- promiseLookupExpression,
- OPERATOR_ASSIGNMENT,
- new MethodCallExpression(
- new ClassExpression(new ClassNode(TransactionalAsyncTransformUtils).getPlainNodeReference()),
- "createTransactionalPromiseDecorator",
- new ArgumentListExpression(new VariableExpression(VARIABLE_TRANSACTION_MANAGER),
- new MethodCallExpression(
+ new ExpressionStatement(
+ new BinaryExpression(
+ promiseLookupExpression,
+ OPERATOR_ASSIGNMENT,
+ new MethodCallExpression(
+ new ClassExpression(new ClassNode(TransactionalAsyncTransformUtils).getPlainNodeReference()),
+ "createTransactionalPromiseDecorator",
+ new ArgumentListExpression(new VariableExpression(VARIABLE_TRANSACTION_MANAGER),
+ new MethodCallExpression(
new ClassExpression(delegateClassNode),
"getDeclaredMethod", methodLookupArguments
- )
- )
- )
+ )
+ )
+ )
+ )
)
- )
)
promiseDecorators.addExpression(promiseLookupExpression)
@@ -137,7 +136,7 @@ class DefaultDelegateAsyncTransactionalMethodTransformer implements DelegateAsyn
classNode.addField(new FieldNode(FIELD_NAME_TRANSACTION_MANAGER, Modifier.PRIVATE, INTERFACE_TRANSACTION_MANAGER, classNode, GrailsASTUtils.NULL_EXPRESSION))
}
final promiseDecoratorsField = classNode.getField(FIELD_NAME_PROMISE_DECORATORS)
- if(promiseDecoratorsField == null) {
+ if (promiseDecoratorsField == null) {
classNode.addField(new FieldNode(FIELD_NAME_PROMISE_DECORATORS, Modifier.PRIVATE, CLASS_NODE_MAP, classNode, new MapExpression()))
}
@@ -146,28 +145,28 @@ class DefaultDelegateAsyncTransactionalMethodTransformer implements DelegateAsyn
def parameters = [transactionManagerParameter] as Parameter[]
final txMgrParam = new VariableExpression(transactionManagerParameter)
methodBody.addStatement(
- new ExpressionStatement(
- new BinaryExpression(
- new PropertyExpression(EXPRESSION_THIS, FIELD_NAME_TRANSACTION_MANAGER),
- OPERATOR_ASSIGNMENT,
- txMgrParam
+ new ExpressionStatement(
+ new BinaryExpression(
+ new PropertyExpression(EXPRESSION_THIS, FIELD_NAME_TRANSACTION_MANAGER),
+ OPERATOR_ASSIGNMENT,
+ txMgrParam
+ )
)
- )
)
methodBody.addStatement(
- new ExpressionStatement(
- new DeclarationExpression(
- new VariableExpression(VARIABLE_TRANSACTION_MANAGER, INTERFACE_TRANSACTION_MANAGER),
- OPERATOR_ASSIGNMENT,
- txMgrParam
+ new ExpressionStatement(
+ new DeclarationExpression(
+ new VariableExpression(VARIABLE_TRANSACTION_MANAGER, INTERFACE_TRANSACTION_MANAGER),
+ OPERATOR_ASSIGNMENT,
+ txMgrParam
+ )
)
- )
)
method = new MethodNode(METHOD_NAME_SET_TRANSACTION_MANAGER, Modifier.PUBLIC, ClassHelper.VOID_TYPE, parameters, [] as ClassNode[], methodBody)
classNode.addMethod(method)
}
- return (BlockStatement)method.getCode()
+ return (BlockStatement) method.getCode()
}
}
diff --git a/grails-async/plugin/src/main/groovy/org/grails/compiler/web/async/TransactionalAsyncTransformUtils.groovy b/grails-async/plugin/src/main/groovy/org/grails/compiler/web/async/TransactionalAsyncTransformUtils.groovy
index 7b2a25157e..832981009e 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/compiler/web/async/TransactionalAsyncTransformUtils.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/compiler/web/async/TransactionalAsyncTransformUtils.groovy
@@ -34,7 +34,6 @@ import java.lang.reflect.Method
@CompileStatic
class TransactionalAsyncTransformUtils {
-
/**
* Creates a {@link TransactionalPromiseDecorator} for the given transactionManager and method to be invoked
*
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecorator.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecorator.groovy
index c63d86fd14..c6e0960ff8 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecorator.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecorator.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.plugins.web.async
import grails.async.web.AsyncGrailsWebRequest
@@ -42,6 +41,7 @@ import java.util.concurrent.TimeoutException
*/
@CompileStatic
class AsyncWebRequestPromiseDecorator implements PromiseDecorator {
+
GrailsWebRequest webRequest
final AsyncGrailsWebRequest asyncRequest
final AsyncContext asyncContext
@@ -52,15 +52,14 @@ class AsyncWebRequestPromiseDecorator implements PromiseDecorator {
HttpServletRequest currentServletRequest = webRequest.currentRequest
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(currentServletRequest)
AsyncGrailsWebRequest newWebRequest
- if(asyncManager.isConcurrentHandlingStarted()) {
+ if (asyncManager.isConcurrentHandlingStarted()) {
newWebRequest = AsyncGrailsWebRequest.lookup(currentServletRequest)
asyncContext = newWebRequest.asyncContext
- if( newWebRequest == null || newWebRequest.isAsyncComplete() ) {
+ if (newWebRequest == null || newWebRequest.isAsyncComplete()) {
throw new IllegalStateException("Cannot start a task once asynchronous request processing has completed")
}
- }
- else {
- newWebRequest = new AsyncGrailsWebRequest(currentServletRequest, webRequest.currentResponse, webRequest.servletContext,webRequest.applicationContext)
+ } else {
+ newWebRequest = new AsyncGrailsWebRequest(currentServletRequest, webRequest.currentResponse, webRequest.servletContext, webRequest.applicationContext)
asyncManager.setAsyncWebRequest(newWebRequest)
newWebRequest.startAsync()
asyncContext = newWebRequest.asyncContext
@@ -74,22 +73,21 @@ class AsyncWebRequestPromiseDecorator implements PromiseDecorator {
@Override
def <D> Closure<D> decorate(Closure<D> c) {
- return (Closure<D>) { args ->
- if(timeoutReached) {
+ return (Closure<D>) { args ->
+ if (timeoutReached) {
throw new TimeoutException("Asynchronous request processing timeout reached")
}
HttpServletRequest request = (HttpServletRequest) asyncContext.request
- if(request.isAsyncStarted()) {
+ if (request.isAsyncStarted()) {
- WebUtils.storeGrailsWebRequest(new GrailsWebRequest(request, (HttpServletResponse)asyncContext.response, webRequest.attributes))
+ WebUtils.storeGrailsWebRequest(new GrailsWebRequest(request, (HttpServletResponse) asyncContext.response, webRequest.attributes))
try {
return invokeClosure(c, args)
}
finally {
RequestContextHolder.resetRequestAttributes()
}
- }
- else {
+ } else {
throw new IllegalStateException("Asynchronous request already terminated. Likely timeout reached")
}
}
@@ -99,14 +97,11 @@ class AsyncWebRequestPromiseDecorator implements PromiseDecorator {
def invokeClosure(Closure c, args) {
if (args == null) {
c.call(null)
- }
- else if(args && args.getClass().isArray()) {
+ } else if (args && args.getClass().isArray()) {
c.call(*args)
- }
- else if (args instanceof List) {
+ } else if (args instanceof List) {
c.call(*args)
- }
- else {
+ } else {
c.call(args)
}
}
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecoratorLookupStrategy.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecoratorLookupStrategy.groovy
index f43bc1ab06..a9b2113d22 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecoratorLookupStrategy.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/AsyncWebRequestPromiseDecoratorLookupStrategy.groovy
@@ -31,6 +31,7 @@ import grails.async.decorator.PromiseDecoratorLookupStrategy
*/
@CompileStatic
class AsyncWebRequestPromiseDecoratorLookupStrategy implements PromiseDecoratorLookupStrategy {
+
@Override
List<PromiseDecorator> findDecorators() {
final webRequest = GrailsWebRequest.lookup()
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/ControllersAsyncGrailsPlugin.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/ControllersAsyncGrailsPlugin.groovy
index f6b20c9850..e004b64520 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/ControllersAsyncGrailsPlugin.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/ControllersAsyncGrailsPlugin.groovy
@@ -30,10 +30,14 @@ import org.grails.plugins.web.async.spring.PromiseFactoryBean
* @since 2.0
*/
class ControllersAsyncGrailsPlugin extends Plugin {
+
def grailsVersion = "7.0.0 > *"
def loadAfter = ['controllers']
- Closure doWithSpring() {{->
- asyncPromiseResponseActionResultTransformer(AsyncActionResultTransformer)
- grailsPromiseFactory(PromiseFactoryBean)
- }}
+
+ Closure doWithSpring() {
+ { ->
+ asyncPromiseResponseActionResultTransformer(AsyncActionResultTransformer)
+ grailsPromiseFactory(PromiseFactoryBean)
+ }
+ }
}
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/GrailsAsyncContext.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/GrailsAsyncContext.groovy
index ebba8346d9..fb6d403e85 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/GrailsAsyncContext.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/GrailsAsyncContext.groovy
@@ -37,7 +37,8 @@ class GrailsAsyncContext implements AsyncContext {
private static final String PERSISTENCE_INTERCEPTORS = 'org.codehaus.groovy.grails.PERSISTENCE_INTERCEPTORS'
- final @Delegate AsyncContext delegate
+ final @Delegate
+ AsyncContext delegate
final GrailsWebRequest originalWebRequest
final AsyncGrailsWebRequest asyncGrailsWebRequest
@@ -53,7 +54,7 @@ class GrailsAsyncContext implements AsyncContext {
void start(Runnable runnable) {
delegate.start {
- GrailsWebRequest webRequest = asyncGrailsWebRequest ?: new GrailsWebRequest((HttpServletRequest)request, (HttpServletResponse)response, request.getServletContext())
+ GrailsWebRequest webRequest = asyncGrailsWebRequest ?: new GrailsWebRequest((HttpServletRequest) request, (HttpServletResponse) response, request.getServletContext())
WebUtils.storeGrailsWebRequest(webRequest)
def interceptors = getPersistenceInterceptors(webRequest)
@@ -74,11 +75,11 @@ class GrailsAsyncContext implements AsyncContext {
void complete() {
delegate.complete()
- }
+ }
protected Collection<PersistenceContextInterceptor> getPersistenceInterceptors(GrailsWebRequest webRequest) {
def servletContext = webRequest.servletContext
- Collection<PersistenceContextInterceptor> interceptors = (Collection<PersistenceContextInterceptor>)servletContext?.getAttribute(PERSISTENCE_INTERCEPTORS)
+ Collection<PersistenceContextInterceptor> interceptors = (Collection<PersistenceContextInterceptor>) servletContext?.getAttribute(PERSISTENCE_INTERCEPTORS)
if (interceptors == null) {
interceptors = webRequest.applicationContext?.getBeansOfType(PersistenceContextInterceptor)?.values() ?: []
servletContext.setAttribute(PERSISTENCE_INTERCEPTORS, interceptors)
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/mvc/AsyncActionResultTransformer.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/mvc/AsyncActionResultTransformer.groovy
index df069f4285..d85c4839f3 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/mvc/AsyncActionResultTransformer.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/mvc/AsyncActionResultTransformer.groovy
@@ -55,13 +55,12 @@ class AsyncActionResultTransformer implements ActionResultTransformer {
final response = webRequest.getResponse()
AsyncGrailsWebRequest asyncWebRequest
- if(asyncManager.isConcurrentHandlingStarted()) {
+ if (asyncManager.isConcurrentHandlingStarted()) {
asyncWebRequest = AsyncGrailsWebRequest.lookup(request)
- if(asyncWebRequest == null) {
+ if (asyncWebRequest == null) {
throw new IllegalStateException("Concurrency handling already started by another process")
}
- }
- else {
+ } else {
asyncWebRequest = new AsyncGrailsWebRequest(request, response, webRequest.servletContext)
asyncManager.setAsyncWebRequest(asyncWebRequest)
asyncWebRequest.startAsync()
@@ -101,8 +100,7 @@ class AsyncActionResultTransformer implements ActionResultTransformer {
def modelAndView = exceptionResolver.resolveException(request, response, this, (Exception) t)
asyncContext.getRequest().setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, modelAndView)
asyncContext.dispatch()
- }
- else {
+ } else {
asyncContext.complete()
}
}
diff --git a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/spring/PromiseFactoryBean.groovy b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/spring/PromiseFactoryBean.groovy
index 6bce2a5788..639548ffbf 100644
--- a/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/spring/PromiseFactoryBean.groovy
+++ b/grails-async/plugin/src/main/groovy/org/grails/plugins/web/async/spring/PromiseFactoryBean.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.plugins.web.async.spring
import grails.async.PromiseFactory
@@ -33,6 +32,7 @@ import org.springframework.beans.factory.FactoryBean
*/
@CompileStatic
class PromiseFactoryBean extends PromiseFactoryBuilder implements FactoryBean<PromiseFactory> {
+
@Override
PromiseFactory getObject() throws Exception {
PromiseFactory promiseFactory = build()
diff --git a/grails-async/rxjava/build.gradle b/grails-async/rxjava/build.gradle
index b15111a395..363846c1ce 100644
--- a/grails-async/rxjava/build.gradle
+++ b/grails-async/rxjava/build.gradle
@@ -46,4 +46,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromise.groovy b/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromise.groovy
index f44de3fab5..71358ca0b2 100644
--- a/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromise.groovy
+++ b/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromise.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava
import grails.async.Promise
@@ -47,21 +46,21 @@ import java.util.concurrent.TimeoutException
@AutoFinal
@CompileStatic
@PackageScope
-class RxPromise<T> implements Promise<T> {
+class RxPromise<T> implements Promise<T> {
- final Subject<T,T> subject
+ final Subject<T, T> subject
final RxPromiseFactory promiseFactory
protected Subscription subscription
RxPromise(RxPromiseFactory promiseFactory, Closure callable, Scheduler scheduler) {
- this(promiseFactory, Single.create( { SingleSubscriber<? super T> singleSubscriber ->
+ this(promiseFactory, Single.create({ SingleSubscriber<? super T> singleSubscriber ->
try {
- singleSubscriber.onSuccess((T)callable.call())
+ singleSubscriber.onSuccess((T) callable.call())
} catch (Throwable t) {
singleSubscriber.onError(t)
}
} as Single.OnSubscribe<T>)
- .subscribeOn(scheduler))
+ .subscribeOn(scheduler))
}
RxPromise(RxPromiseFactory promiseFactory, Observable single) {
@@ -78,7 +77,7 @@ class RxPromise<T> implements Promise<T> {
this.subject = subject
}
- RxPromise(RxPromiseFactory promiseFactory,Observable observable, Subject subject) {
+ RxPromise(RxPromiseFactory promiseFactory, Observable observable, Subject subject) {
this.promiseFactory = promiseFactory
this.subscription = observable.subscribe(subject)
this.subject = subject
@@ -92,13 +91,13 @@ class RxPromise<T> implements Promise<T> {
@Override
Promise<T> onComplete(Closure callable) {
def decoratedCallable = promiseFactory.applyDecorators(callable, null)
- return new RxPromise<T>(promiseFactory,subject.map(decoratedCallable as Func1<T, T>))
+ return new RxPromise<T>(promiseFactory, subject.map(decoratedCallable as Func1<T, T>))
}
@Override
Promise<T> onError(Closure callable) {
def decoratedCallable = promiseFactory.applyDecorators(callable, null)
- return new RxPromise<T>(promiseFactory,subject.doOnError(decoratedCallable as Action1<Throwable>))
+ return new RxPromise<T>(promiseFactory, subject.doOnError(decoratedCallable as Action1<Throwable>))
}
@Override
@@ -108,7 +107,7 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean cancel(boolean mayInterruptIfRunning) {
- if(subscription != null) {
+ if (subscription != null) {
subscription.unsubscribe()
return subscription.isUnsubscribed()
}
@@ -117,10 +116,9 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean isCancelled() {
- if(subscription == null) {
+ if (subscription == null) {
return false
- }
- else {
+ } else {
return subscription.isUnsubscribed()
}
}
@@ -140,10 +138,9 @@ class RxPromise<T> implements Promise<T> {
try {
return subject.timeout(timeout, unit).toBlocking().first()
} catch (Throwable e) {
- if(e.cause instanceof TimeoutException) {
+ if (e.cause instanceof TimeoutException) {
throw e.cause
- }
- else {
+ } else {
throw e
}
}
diff --git a/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromiseFactory.groovy b/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromiseFactory.groovy
index 6248acc299..0785de57a1 100644
--- a/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromiseFactory.groovy
+++ b/grails-async/rxjava/src/main/groovy/org/grails/async/factory/rxjava/RxPromiseFactory.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava
import grails.async.Promise
@@ -53,10 +52,9 @@ class RxPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> createPromise(Closure<T>[] closures) {
- if(closures.length == 1) {
- return new RxPromise<T>(this,closures[0], Schedulers.io())
- }
- else {
+ if (closures.length == 1) {
+ return new RxPromise<T>(this, closures[0], Schedulers.io())
+ } else {
def promiseList = new PromiseList()
for (Closure closure : closures) {
promiseList.add(closure)
@@ -79,22 +77,21 @@ class RxPromiseFactory extends AbstractPromiseFactory {
<T> Promise<T> onComplete(List<Promise<T>> promises, Closure<T> callable) {
new RxPromise<T>(this, Observable.concat(
promises.collect() { Promise p ->
- if(p instanceof BoundPromise) {
- return Observable.just(((BoundPromise)p).value)
- }
- else {
- return ((RxPromise)p).subject as Observable<T>
+ if (p instanceof BoundPromise) {
+ return Observable.just(((BoundPromise) p).value)
+ } else {
+ return ((RxPromise) p).subject as Observable<T>
}
}
).toList())
- .onComplete(callable)
+ .onComplete(callable)
}
@Override
<T> Promise<T> onError(List<Promise<T>> promises, Closure<?> callable) {
new RxPromise<T>(this, Observable.concat(
- promises.collect() { Promise p -> ((RxPromise)p).subject as Observable<T> }
+ promises.collect() { Promise p -> ((RxPromise) p).subject as Observable<T> }
).toList())
- .onError(callable)
+ .onError(callable)
}
}
diff --git a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseListSpec.groovy b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseListSpec.groovy
index 91409810b1..0fba6d90af 100644
--- a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseListSpec.groovy
+++ b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseListSpec.groovy
@@ -27,7 +27,6 @@ import spock.util.concurrent.PollingConditions
*/
class RxJavaPromiseListSpec extends Specification{
-
void 'Test promise list handling'() {
when: 'a list of promises is created'
diff --git a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseMapSpec.groovy b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseMapSpec.groovy
index 894c70ae33..7a94076761 100644
--- a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseMapSpec.groovy
+++ b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseMapSpec.groovy
@@ -82,7 +82,6 @@ class RxJavaPromiseMapSpec extends Specification{
}
}
-
void 'Test that a PromiseMap triggers onError for an exception and ignores onComplete'() {
when: 'a promise map is used with an onComplete handler'
diff --git a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseSpec.groovy b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseSpec.groovy
index 7108caafa8..f8f3f2a62f 100644
--- a/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseSpec.groovy
+++ b/grails-async/rxjava/src/test/groovy/org/grails/async/factory/rxjava/RxJavaPromiseSpec.groovy
@@ -153,4 +153,3 @@ class RxJavaPromiseSpec extends Specification {
}
}
-
diff --git a/grails-async/rxjava2/build.gradle b/grails-async/rxjava2/build.gradle
index 41732df8d9..cb6afbeebf 100644
--- a/grails-async/rxjava2/build.gradle
+++ b/grails-async/rxjava2/build.gradle
@@ -46,4 +46,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromise.groovy b/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromise.groovy
index a0f1bdf324..a3c804e75f 100644
--- a/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromise.groovy
+++ b/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromise.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava2
import grails.async.Promise
@@ -50,7 +49,7 @@ import java.util.concurrent.TimeoutException
@AutoFinal
@CompileStatic
@PackageScope
-class RxPromise<T> implements Promise<T> {
+class RxPromise<T> implements Promise<T> {
protected final Subject<T> subject
protected final RxPromiseFactory promiseFactory
@@ -61,9 +60,9 @@ class RxPromise<T> implements Promise<T> {
RxPromise(RxPromiseFactory promiseFactory, Closure callable, Scheduler scheduler) {
- this(promiseFactory, Single.create( { SingleEmitter<? super T> singleSubscriber ->
+ this(promiseFactory, Single.create({ SingleEmitter<? super T> singleSubscriber ->
try {
- singleSubscriber.onSuccess((T)runCallable(callable))
+ singleSubscriber.onSuccess((T) runCallable(callable))
} catch (Throwable t) {
singleSubscriber.onError(t)
}
@@ -87,6 +86,7 @@ class RxPromise<T> implements Promise<T> {
this.observable = observable
this.promiseFactory = promiseFactory
observable.subscribe(new Observer<T>() {
+
@Override
void onSubscribe(Disposable d) {
subscription = d
@@ -138,7 +138,7 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean cancel(boolean mayInterruptIfRunning) {
- if(subscription != null) {
+ if (subscription != null) {
subscription.dispose()
return subscription.isDisposed()
}
@@ -147,10 +147,9 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean isCancelled() {
- if(subscription == null) {
+ if (subscription == null) {
return false
- }
- else {
+ } else {
return subscription.isDisposed()
}
}
@@ -170,10 +169,9 @@ class RxPromise<T> implements Promise<T> {
try {
return subject.timeout(timeout, unit).blockingFirst()
} catch (Throwable e) {
- if(e.cause instanceof TimeoutException) {
+ if (e.cause instanceof TimeoutException) {
throw e.cause
- }
- else {
+ } else {
throw e
}
}
@@ -181,7 +179,7 @@ class RxPromise<T> implements Promise<T> {
static Object runCallable(Closure callable) {
Object rtn = callable.call()
- if(rtn == null) {
+ if (rtn == null) {
return Void
} else {
return rtn
diff --git a/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromiseFactory.groovy b/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromiseFactory.groovy
index c527d26d2b..2ec3611516 100644
--- a/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromiseFactory.groovy
+++ b/grails-async/rxjava2/src/main/groovy/org/grails/async/factory/rxjava2/RxPromiseFactory.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava2
import grails.async.Promise
@@ -53,10 +52,9 @@ class RxPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> createPromise(Closure<T>[] closures) {
- if(closures.length == 1) {
+ if (closures.length == 1) {
return new RxPromise<T>(this, closures[0], Schedulers.io())
- }
- else {
+ } else {
def promiseList = new PromiseList()
for (Closure closure : closures) {
promiseList.add(closure)
@@ -78,23 +76,22 @@ class RxPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> onComplete(List<Promise<T>> promises, Closure<T> callable) {
new RxPromise<T>(this, Observable.concat(
- promises.collect { Promise p ->
- if(p instanceof BoundPromise) {
- return Observable.just(((BoundPromise)p).value) as Observable<T>
+ promises.collect { Promise p ->
+ if (p instanceof BoundPromise) {
+ return Observable.just(((BoundPromise) p).value) as Observable<T>
+ } else {
+ return ((RxPromise) p).toObservable() as Observable<T>
+ }
}
- else {
- return ((RxPromise)p).toObservable() as Observable<T>
- }
- }
).toList())
- .onComplete(callable)
+ .onComplete(callable)
}
@Override
<T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
new RxPromise(this, Observable.concat(
- promises.collect { ((RxPromise<T>)it).toObservable() }
+ promises.collect { ((RxPromise<T>) it).toObservable() }
).toList())
- .onError(callable) as Promise<List<T>>
+ .onError(callable) as Promise<List<T>>
}
}
diff --git a/grails-async/rxjava2/src/test/groovy/org/grails/async/factory/rxjava2/RxPromiseSpec.groovy b/grails-async/rxjava2/src/test/groovy/org/grails/async/factory/rxjava2/RxPromiseSpec.groovy
index 30b3c3bfd2..6d9f31f72c 100644
--- a/grails-async/rxjava2/src/test/groovy/org/grails/async/factory/rxjava2/RxPromiseSpec.groovy
+++ b/grails-async/rxjava2/src/test/groovy/org/grails/async/factory/rxjava2/RxPromiseSpec.groovy
@@ -167,4 +167,3 @@ class RxPromiseSpec extends Specification {
}
}
-
diff --git a/grails-async/rxjava3/build.gradle b/grails-async/rxjava3/build.gradle
index 3c62cff0dd..5c647a42b2 100644
--- a/grails-async/rxjava3/build.gradle
+++ b/grails-async/rxjava3/build.gradle
@@ -46,4 +46,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromise.groovy b/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromise.groovy
index 187da07410..f21cc7c4ae 100644
--- a/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromise.groovy
+++ b/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromise.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava3
import grails.async.Promise
@@ -48,7 +47,7 @@ import java.util.concurrent.TimeoutException
@AutoFinal
@CompileStatic
@PackageScope
-class RxPromise<T> implements Promise<T> {
+class RxPromise<T> implements Promise<T> {
protected final Subject<T> subject
protected final RxPromiseFactory promiseFactory
@@ -58,9 +57,9 @@ class RxPromise<T> implements Promise<T> {
protected boolean finished = false
RxPromise(RxPromiseFactory promiseFactory, Closure callable, Scheduler scheduler) {
- this(promiseFactory, Single.create( { SingleEmitter<? super T> singleSubscriber ->
+ this(promiseFactory, Single.create({ SingleEmitter<? super T> singleSubscriber ->
try {
- singleSubscriber.onSuccess((T)runCallable(callable))
+ singleSubscriber.onSuccess((T) runCallable(callable))
} catch (Throwable t) {
singleSubscriber.onError(t)
}
@@ -84,6 +83,7 @@ class RxPromise<T> implements Promise<T> {
this.observable = observable
this.promiseFactory = promiseFactory
observable.subscribe(new Observer<T>() {
+
@Override
void onSubscribe(Disposable d) {
subscription = d
@@ -135,7 +135,7 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean cancel(boolean mayInterruptIfRunning) {
- if(subscription != null) {
+ if (subscription != null) {
subscription.dispose()
return subscription.isDisposed()
}
@@ -144,10 +144,9 @@ class RxPromise<T> implements Promise<T> {
@Override
boolean isCancelled() {
- if(subscription == null) {
+ if (subscription == null) {
return false
- }
- else {
+ } else {
return subscription.isDisposed()
}
}
@@ -167,10 +166,9 @@ class RxPromise<T> implements Promise<T> {
try {
return subject.timeout(timeout, unit).blockingFirst()
} catch (Throwable e) {
- if(e.cause instanceof TimeoutException) {
+ if (e.cause instanceof TimeoutException) {
throw e.cause
- }
- else {
+ } else {
throw e
}
}
@@ -178,7 +176,7 @@ class RxPromise<T> implements Promise<T> {
static Object runCallable(Closure callable) {
Object rtn = callable.call()
- if(rtn == null) {
+ if (rtn == null) {
return Void
} else {
return rtn
diff --git a/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromiseFactory.groovy b/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromiseFactory.groovy
index f93dab1925..1512b46852 100644
--- a/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromiseFactory.groovy
+++ b/grails-async/rxjava3/src/main/groovy/org/grails/async/factory/rxjava3/RxPromiseFactory.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.async.factory.rxjava3
import grails.async.Promise
@@ -50,10 +49,9 @@ class RxPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> createPromise(Closure<T>[] closures) {
- if(closures.length == 1) {
+ if (closures.length == 1) {
return new RxPromise<T>(this, closures[0], Schedulers.io())
- }
- else {
+ } else {
def promiseList = new PromiseList()
for (Closure closure : closures) {
promiseList.add(closure)
@@ -75,23 +73,22 @@ class RxPromiseFactory extends AbstractPromiseFactory {
@Override
<T> Promise<T> onComplete(List<Promise<T>> promises, Closure<T> callable) {
new RxPromise<T>(this, Observable.concat(
- promises.collect { Promise p ->
- if(p instanceof BoundPromise) {
- return Observable.just(((BoundPromise)p).value) as Observable<T>
+ promises.collect { Promise p ->
+ if (p instanceof BoundPromise) {
+ return Observable.just(((BoundPromise) p).value) as Observable<T>
+ } else {
+ return ((RxPromise) p).toObservable() as Observable<T>
+ }
}
- else {
- return ((RxPromise)p).toObservable() as Observable<T>
- }
- }
).toList())
- .onComplete(callable)
+ .onComplete(callable)
}
@Override
<T> Promise<List<T>> onError(List<Promise<T>> promises, Closure<?> callable) {
new RxPromise(this, Observable.concat(
- promises.collect { ((RxPromise<T>)it).toObservable() }
+ promises.collect { ((RxPromise<T>) it).toObservable() }
).toList())
- .onError(callable) as Promise<List<T>>
+ .onError(callable) as Promise<List<T>>
}
}
diff --git a/grails-async/rxjava3/src/test/groovy/org/grails/async/factory/rxjava3/RxPromiseSpec.groovy b/grails-async/rxjava3/src/test/groovy/org/grails/async/factory/rxjava3/RxPromiseSpec.groovy
index 77cfd92dfa..8e42cee870 100644
--- a/grails-async/rxjava3/src/test/groovy/org/grails/async/factory/rxjava3/RxPromiseSpec.groovy
+++ b/grails-async/rxjava3/src/test/groovy/org/grails/async/factory/rxjava3/RxPromiseSpec.groovy
@@ -164,4 +164,3 @@ class RxPromiseSpec extends Specification {
}
}
-
diff --git a/grails-bom/build.gradle b/grails-bom/build.gradle
index 7d23c61449..99c6261b33 100644
--- a/grails-bom/build.gradle
+++ b/grails-bom/build.gradle
@@ -200,4 +200,5 @@ ext {
apply {
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
diff --git a/grails-bootstrap/build.gradle b/grails-bootstrap/build.gradle
index b42df191c8..d8ac8a4b04 100644
--- a/grails-bootstrap/build.gradle
+++ b/grails-bootstrap/build.gradle
@@ -84,4 +84,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-bootstrap/src/main/groovy/grails/build/logging/ConsoleLogger.java b/grails-bootstrap/src/main/groovy/grails/build/logging/ConsoleLogger.java
index b83f5b9540..1cb417e3aa 100644
--- a/grails-bootstrap/src/main/groovy/grails/build/logging/ConsoleLogger.java
+++ b/grails-bootstrap/src/main/groovy/grails/build/logging/ConsoleLogger.java
@@ -25,6 +25,7 @@ package grails.build.logging;
* @since 3.0
*/
public interface ConsoleLogger {
+
/**
* Indicates progress with the default progress indicator
*/
@@ -91,7 +92,7 @@ public interface ConsoleLogger {
/**
* Use to log an error
*
- * @param msg The message
+ * @param msg The message
* @param error The error
*/
void error(String msg, Throwable error);
@@ -99,7 +100,7 @@ public interface ConsoleLogger {
/**
* Log an error with a specific error label
*
- * @param label The label
+ * @param label The label
* @param message The message
*/
void error(String label, String message);
@@ -127,9 +128,9 @@ public interface ConsoleLogger {
/**
* Outputs a verbose message
+ *
* @param msg The message
*/
void verbose(String msg);
-
}
diff --git a/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsConsole.java b/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsConsole.java
index fe3de1607e..705858eb4b 100644
--- a/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsConsole.java
+++ b/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsConsole.java
@@ -57,8 +57,6 @@ import static org.fusesource.jansi.Ansi.ansi;
*/
public class GrailsConsole implements ConsoleLogger {
- private static GrailsConsole instance;
-
public static final String ENABLE_TERMINAL = "grails.console.enable.terminal";
public static final String ENABLE_INTERACTIVE = "grails.console.enable.interactive";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
@@ -71,24 +69,8 @@ public class GrailsConsole implements ConsoleLogger {
public static final String STACKTRACE_FILTERED_MESSAGE = " (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)";
public static final String STACKTRACE_MESSAGE = " (Use --stacktrace to see the full trace)";
public static final Character SECURE_MASK_CHAR = Character.valueOf('*');
- private PrintStream originalSystemOut;
- private PrintStream originalSystemErr;
- private StringBuilder maxIndicatorString;
- private int cursorMove;
- private Thread shutdownHookThread;
- private Character defaultInputMask = null;
-
- /**
- * Whether to enable verbose mode
- */
- private boolean verbose = Boolean.getBoolean("grails.verbose");
-
- /**
- * Whether to show stack traces
- */
- private boolean stacktrace = Boolean.getBoolean("grails.show.stacktrace");
- private boolean progressIndicatorActive = false;
+ private static GrailsConsole instance;
/**
* The progress indicator to use
@@ -119,11 +101,32 @@ public class GrailsConsole implements ConsoleLogger {
Stack<String> category = new Stack<String>() {
@Override
public String toString() {
- if (size() == 1) return peek() + CATEGORY_SEPARATOR;
- return DefaultGroovyMethods.join((Iterable) this, CATEGORY_SEPARATOR) + CATEGORY_SEPARATOR;
+ if (size() == 1) {
+ return peek() + CATEGORY_SEPARATOR;
+ }
+ return DefaultGroovyMethods.join(this, CATEGORY_SEPARATOR) + CATEGORY_SEPARATOR;
}
};
+ private PrintStream originalSystemOut;
+ private PrintStream originalSystemErr;
+ private StringBuilder maxIndicatorString;
+ private int cursorMove;
+ private Thread shutdownHookThread;
+ private Character defaultInputMask = null;
+
+ /**
+ * Whether to enable verbose mode
+ */
+ private boolean verbose = Boolean.getBoolean("grails.verbose");
+
+ /**
+ * Whether to show stack traces
+ */
+ private boolean stacktrace = Boolean.getBoolean("grails.show.stacktrace");
+
+ private boolean progressIndicatorActive = false;
+
/**
* Whether ANSI should be enabled for output
*/
@@ -134,6 +137,23 @@ public class GrailsConsole implements ConsoleLogger {
*/
private boolean userInputActive;
+ /**
+ * Logs a message below the current status message
+ *
+ * @param msg The message to log
+ */
+ private boolean appendCalled = false;
+
+ protected GrailsConsole() throws IOException {
+ cursorMove = 1;
+
+ initialize(System.in, System.out, System.err);
+
+ // bit of a WTF this, but see no other way to allow a customization indicator
+ maxIndicatorString = new StringBuilder(indicator).append(indicator).append(indicator).append(indicator).append(indicator);
+
+ }
+
public void addShutdownHook() {
if (!Environment.isFork()) {
shutdownHookThread = new Thread(new Runnable() {
@@ -152,17 +172,6 @@ public class GrailsConsole implements ConsoleLogger {
}
}
-
- protected GrailsConsole() throws IOException {
- cursorMove = 1;
-
- initialize(System.in, System.out, System.err);
-
- // bit of a WTF this, but see no other way to allow a customization indicator
- maxIndicatorString = new StringBuilder(indicator).append(indicator).append(indicator).append(indicator).append(indicator);
-
- }
-
/**
* Use in testing when System.out, System.err or System.in change
*
@@ -571,7 +580,9 @@ public 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().length() == 0) {
+ return;
+ }
try {
if (isAnsiEnabled()) {
if (replaceCount > 0) {
@@ -584,7 +595,9 @@ public class GrailsConsole implements ConsoleLogger {
cursorMove = replaceCount;
}
} else {
- if (lastMessage != null && lastMessage.equals(msg)) return;
+ if (lastMessage != null && lastMessage.equals(msg)) {
+ return;
+ }
if (progressIndicatorActive) {
out.println();
@@ -745,13 +758,6 @@ public class GrailsConsole implements ConsoleLogger {
.eraseLine(Ansi.Erase.BACKWARD).cursorLeft(PROMPT.length()));
}
- /**
- * Logs a message below the current status message
- *
- * @param msg The message to log
- */
- private boolean appendCalled = false;
-
public void append(String msg) {
verifySystemOut();
PrintStream printStream = out;
@@ -956,7 +962,9 @@ public class GrailsConsole implements ConsoleLogger {
private Ansi erasePreviousLine(String categoryName) {
int cursorMove = this.cursorMove;
- if (userInputActive) cursorMove++;
+ if (userInputActive) {
+ cursorMove++;
+ }
if (cursorMove > 0) {
int moveLeftLength = categoryName.length() + lastMessage.length();
if (userInputActive) {
diff --git a/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsEclipseConsole.java b/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsEclipseConsole.java
index 72153378ae..9bcddd72e8 100644
--- a/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsEclipseConsole.java
+++ b/grails-bootstrap/src/main/groovy/grails/build/logging/GrailsEclipseConsole.java
@@ -36,7 +36,6 @@ import java.io.IOException;
* anticipated needs.
*
* @author Kris De Volder
- *
* @since 2.0.0.M2
*/
public class GrailsEclipseConsole extends GrailsConsole {
@@ -65,7 +64,7 @@ public class GrailsEclipseConsole extends GrailsConsole {
private static Boolean boolProp(String propName) {
try {
- String prop = System.getProperty(propName);
+ String prop = System.getProperty(propName);
return prop != null && Boolean.valueOf(prop);
} catch (Exception e) {
return false;
diff --git a/grails-bootstrap/src/main/groovy/grails/build/proxy/SystemPropertiesAuthenticator.groovy b/grails-bootstrap/src/main/groovy/grails/build/proxy/SystemPropertiesAuthenticator.groovy
index 9fac0165c1..d005afe410 100644
--- a/grails-bootstrap/src/main/groovy/grails/build/proxy/SystemPropertiesAuthenticator.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/build/proxy/SystemPropertiesAuthenticator.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.build.proxy
import grails.util.BuildSettings
@@ -33,7 +32,7 @@ class SystemPropertiesAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
- if(getRequestorType() == RequestorType.PROXY) {
+ if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(
System.getProperty(BuildSettings.PROXY_HTTP_USER, ""),
System.getProperty(BuildSettings.PROXY_HTTP_PASSWORD, "").toCharArray());
diff --git a/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.java b/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.java
index bedb635726..3f4a9a4854 100644
--- a/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.java
+++ b/grails-bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.java
@@ -32,13 +32,13 @@ import java.util.concurrent.ConcurrentHashMap;
* @since 2.0
*/
@SuppressWarnings("rawtypes")
-public class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener {
+public final class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventListener {
- private Map<Class, Object> alteredClasses = new ConcurrentHashMap<Class, Object> ();
- private Map<IdentityWeakReference, Object> alteredInstances = new ConcurrentHashMap<IdentityWeakReference, Object>();
private static final Object NO_CUSTOM_METACLASS = new Object();
- private static boolean cleaning;
private static final MetaClassRegistryCleaner INSTANCE = new MetaClassRegistryCleaner();
+ private static boolean cleaning;
+ private Map<Class, Object> alteredClasses = new ConcurrentHashMap<Class, Object>();
+ private Map<IdentityWeakReference, Object> alteredInstances = new ConcurrentHashMap<IdentityWeakReference, Object>();
private MetaClassRegistryCleaner() {
}
@@ -50,7 +50,8 @@ public class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventLis
boolean registered = false;
for (MetaClassRegistryChangeEventListener listener : listeners) {
if (listener == INSTANCE) {
- registered = true;break;
+ registered = true;
+ break;
}
}
if (!registered) {
@@ -96,11 +97,10 @@ public class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventLis
private void updateMetaClassOfClass(MetaClass oldMetaClass, Class classToUpdate) {
if (oldMetaClass != null && !(oldMetaClass.getClass().getName().equals("groovy.mock.interceptor.MockProxyMetaClass"))) {
Object current = alteredClasses.get(classToUpdate);
- if (current == null ) {
+ if (current == null) {
alteredClasses.put(classToUpdate, oldMetaClass);
}
- }
- else {
+ } else {
alteredClasses.put(classToUpdate, NO_CUSTOM_METACLASS);
}
}
@@ -137,8 +137,7 @@ public class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventLis
Object alteredMetaClass = alteredClasses.get(aClass);
if (alteredMetaClass == NO_CUSTOM_METACLASS) {
registry.removeMetaClass(aClass);
- }
- else {
+ } else {
registry.setMetaClass(aClass, (MetaClass) alteredMetaClass);
}
}
@@ -164,7 +163,7 @@ public class MetaClassRegistryCleaner implements MetaClassRegistryChangeEventLis
if (this == obj) {
return true;
}
- return get() == ((IdentityWeakReference)obj).get();
+ return get() == ((IdentityWeakReference) obj).get();
}
}
}
diff --git a/grails-bootstrap/src/main/groovy/grails/codegen/model/Model.groovy b/grails-bootstrap/src/main/groovy/grails/codegen/model/Model.groovy
index 7f68ac8a88..cea898d179 100644
--- a/grails-bootstrap/src/main/groovy/grails/codegen/model/Model.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/codegen/model/Model.groovy
@@ -58,7 +58,6 @@ interface Model {
*/
String getPropertyName()
-
/**
* A property name version of the class name. For example 'FooBar' becomes 'fooBar'
*
diff --git a/grails-bootstrap/src/main/groovy/grails/codegen/model/ModelBuilder.groovy b/grails-bootstrap/src/main/groovy/grails/codegen/model/ModelBuilder.groovy
index 31c023aac2..6d941c9596 100644
--- a/grails-bootstrap/src/main/groovy/grails/codegen/model/ModelBuilder.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/codegen/model/ModelBuilder.groovy
@@ -52,10 +52,9 @@ trait ModelBuilder {
* @return The {@link Model} instance
*/
Model model(String className) {
- if(defaultPackage && !className.contains('.')) {
+ if (defaultPackage && !className.contains('.')) {
return new ModelImpl("${defaultPackage}.$className")
- }
- else {
+ } else {
return new ModelImpl(className)
}
}
@@ -83,6 +82,7 @@ trait ModelBuilder {
@CompileStatic
private static class ModelImpl implements Model {
+
final String className
final String fullName
final String propertyName
@@ -114,13 +114,13 @@ trait ModelBuilder {
@Override
Map<String, Object> asMap() {
- [className: className,
- fullName: fullName,
+ [className : className,
+ fullName : fullName,
propertyName: propertyName,
- modelName: propertyName,
+ modelName : propertyName,
packageName: packageName,
packagePath: packagePath,
- simpleName: simpleName,
+ simpleName : simpleName,
lowerCaseName: lowerCaseName] as Map<String, Object>
}
}
diff --git a/grails-bootstrap/src/main/groovy/grails/io/ResourceUtils.groovy b/grails-bootstrap/src/main/groovy/grails/io/ResourceUtils.groovy
index b8e7dcd398..202ef56c5f 100644
--- a/grails-bootstrap/src/main/groovy/grails/io/ResourceUtils.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/io/ResourceUtils.groovy
@@ -23,7 +23,6 @@ import groovy.transform.CompileStatic
import groovy.transform.Memoized
import org.grails.io.support.GrailsResourceUtils
-
/**
* Utility methods for interacting with resources
*
@@ -52,7 +51,7 @@ class ResourceUtils extends GrailsResourceUtils {
def dirName = dir.name
if (!dir.hidden && !dirName.startsWith('.') && !['conf', 'i18n', 'assets', 'views', 'migrations'].contains(dirName)) {
File[] files = dir.listFiles()
- populatePackages(dir,files, packageNames, "")
+ populatePackages(dir, files, packageNames, "")
}
}
}
@@ -62,28 +61,26 @@ class ResourceUtils extends GrailsResourceUtils {
protected static populatePackages(File rootDir, File[] files, Collection<String> packageNames, String prefix) {
- if(files != null) {
- for(dir in files ) {
- if(dir.isDirectory()) {
+ if (files != null) {
+ for (dir in files) {
+ if (dir.isDirectory()) {
String dirName = dir.name
if (!dir.hidden && !dirName.startsWith('.')) {
def dirFiles = dir.listFiles()
- if(dirFiles != null) {
+ if (dirFiles != null) {
boolean hasGroovySources = dirFiles?.find() { File f -> f.name.endsWith('.groovy') }
- if(hasGroovySources) {
+ if (hasGroovySources) {
// if there are Groovy sources stop here, no need to add child packages
packageNames.add "${prefix}${dirName}".toString()
- }
- else {
+ } else {
// otherwise recurse into a child package
populatePackages(dir, dirFiles, packageNames, "${prefix}${dirName}.")
}
}
}
- }
- else {
- if(dir.name.endsWith('.groovy') && prefix == "") {
+ } else {
+ if (dir.name.endsWith('.groovy') && prefix == "") {
packageNames.add("")
}
}
diff --git a/grails-bootstrap/src/main/groovy/grails/io/support/SystemOutErrCapturer.groovy b/grails-bootstrap/src/main/groovy/grails/io/support/SystemOutErrCapturer.groovy
index 4cec2bb564..af3da1a91c 100644
--- a/grails-bootstrap/src/main/groovy/grails/io/support/SystemOutErrCapturer.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/io/support/SystemOutErrCapturer.groovy
@@ -25,17 +25,18 @@ import groovy.transform.CompileStatic
*/
@CompileStatic
class SystemOutErrCapturer {
+
ByteArrayOutputStream out
ByteArrayOutputStream err
SystemStreamsRedirector previousState
-
+
SystemOutErrCapturer capture() {
out = new ByteArrayOutputStream()
err = new ByteArrayOutputStream()
previousState = SystemStreamsRedirector.create(null, new PrintStream(out, true), new PrintStream(err, true)).redirect()
this
}
-
+
SystemOutErrCapturer redirectToNull() {
out = null
err = null
@@ -43,14 +44,14 @@ class SystemOutErrCapturer {
previousState = SystemStreamsRedirector.create(null, new PrintStream(nullStream, true), new PrintStream(nullStream, true)).redirect()
this
}
-
+
void close() {
- if(previousState != null) {
+ if (previousState != null) {
previousState.redirect()
previousState = null
}
}
-
+
public static <T> T withCapturedOutput(Closure<T> closure) {
SystemOutErrCapturer capturer = new SystemOutErrCapturer().capture()
try {
@@ -59,7 +60,7 @@ class SystemOutErrCapturer {
capturer.close()
}
}
-
+
public static <T> T withNullOutput(Closure<T> closure) {
SystemOutErrCapturer capturer = new SystemOutErrCapturer().redirectToNull()
try {
@@ -68,22 +69,23 @@ class SystemOutErrCapturer {
capturer.close()
}
}
-
+
@CompileStatic
public static class NullOutputStream extends OutputStream {
+
@Override
public void write(byte[] b) throws IOException {
-
- }
-
+
+ }
+
@Override
public void write(int b) throws IOException {
-
+
}
-
+
@Override
public void write(byte[] b, int off, int len) throws IOException {
-
+
}
}
}
diff --git a/grails-bootstrap/src/main/groovy/grails/io/support/SystemStreamsRedirector.groovy b/grails-bootstrap/src/main/groovy/grails/io/support/SystemStreamsRedirector.groovy
index 6bdbd8b7a3..322b90af15 100644
--- a/grails-bootstrap/src/main/groovy/grails/io/support/SystemStreamsRedirector.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/io/support/SystemStreamsRedirector.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.io.support
import groovy.transform.CompileStatic
@@ -25,33 +24,34 @@ import groovy.transform.ToString
@ToString
@CompileStatic
class SystemStreamsRedirector {
+
private static final SystemStreamsRedirector original = current()
final InputStream input
final PrintStream out
final PrintStream err
-
+
private SystemStreamsRedirector(InputStream input, PrintStream out, PrintStream err) {
this.input = input
this.out = out
this.err = err
}
-
+
static SystemStreamsRedirector create(InputStream input, PrintStream out, PrintStream err) {
new SystemStreamsRedirector(input, out, err)
}
-
+
static SystemStreamsRedirector current() {
create(System.in, System.out, System.err)
}
-
+
static SystemStreamsRedirector original() {
original
}
-
+
static <T> T withOriginalIO(Closure<T> closure) {
original().withRedirectedIO(closure)
}
-
+
public <T> T withRedirectedIO(Closure<T> closure) {
SystemStreamsRedirector previous = redirect()
try {
@@ -60,27 +60,26 @@ class SystemStreamsRedirector {
previous.redirect()
}
}
-
-
+
SystemStreamsRedirector redirect() {
InputStream prevInput = null
PrintStream prevOut = null
PrintStream prevErr = null
- if(input != null) {
+ if (input != null) {
prevInput = System.in
- if(!(prevInput.is(input))) {
+ if (!(prevInput.is(input))) {
System.setIn(input)
}
}
- if(out != null) {
+ if (out != null) {
prevOut = System.out
- if(!(prevOut.is(out))) {
+ if (!(prevOut.is(out))) {
System.setOut(out)
}
}
- if(err != null) {
+ if (err != null) {
prevErr = System.err
- if(!(prevErr.is(err))) {
+ if (!(prevErr.is(err))) {
System.setErr(err)
}
}
diff --git a/grails-bootstrap/src/main/groovy/grails/plugins/GrailsPluginInfo.java b/grails-bootstrap/src/main/groovy/grails/plugins/GrailsPluginInfo.java
index 40b87beb3e..3c969b8be9 100644
--- a/grails-bootstrap/src/main/groovy/grails/plugins/GrailsPluginInfo.java
+++ b/grails-bootstrap/src/main/groovy/grails/plugins/GrailsPluginInfo.java
@@ -24,6 +24,7 @@ import org.grails.io.support.Resource;
/**
* Base interface that just contains information about a particular plugin.
+ *
* @author Graeme Rocher
* @since 1.3
*/
@@ -61,6 +62,7 @@ public interface GrailsPluginInfo {
/**
* Returns the location of the Resource that represents the plugin descriptor (the *GrailsPlugin.groovy file)
+ *
* @return The resource
*/
Resource getDescriptor();
@@ -72,6 +74,7 @@ public interface GrailsPluginInfo {
/**
* Gets the properties of the plugin as a map
+ *
* @return A map of the properties
*/
@SuppressWarnings("rawtypes")
diff --git a/grails-bootstrap/src/main/groovy/grails/plugins/GrailsVersionUtils.groovy b/grails-bootstrap/src/main/groovy/grails/plugins/GrailsVersionUtils.groovy
index f09d6616f8..9641dc98f1 100644
--- a/grails-bootstrap/src/main/groovy/grails/plugins/GrailsVersionUtils.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/plugins/GrailsVersionUtils.groovy
@@ -53,7 +53,7 @@ class GrailsVersionUtils {
def vc = new VersionComparator()
pluginVersion = trimTag(pluginVersion)
- if (requiredVersion.indexOf('>') >- 1) {
+ if (requiredVersion.indexOf('>') > -1) {
def tokens = requiredVersion.split(">")*.trim()
tokens = tokens.stream().collect({ String it -> trimTag(it) })
tokens << pluginVersion
@@ -62,8 +62,7 @@ class GrailsVersionUtils {
if (tokens[1] == pluginVersion) {
return true
}
- }
- else if (pluginVersion.equals(trimTag(requiredVersion))) {
+ } else if (pluginVersion.equals(trimTag(requiredVersion))) {
return true
}
@@ -112,13 +111,12 @@ class GrailsVersionUtils {
private static String trimTag(String pluginVersion) {
def i = pluginVersion.indexOf('-')
- if (i >- 1) {
- pluginVersion = pluginVersion[0..i-1]
+ if (i > -1) {
+ pluginVersion = pluginVersion[0..i - 1]
}
def tokens = pluginVersion.split(/\./)
- return tokens.findAll { String it -> it ==~ /\d+/ || it =='*'}.join(".")
+ return tokens.findAll { String it -> it ==~ /\d+/ || it == '*' }.join(".")
}
}
-
diff --git a/grails-bootstrap/src/main/groovy/grails/plugins/VersionComparator.groovy b/grails-bootstrap/src/main/groovy/grails/plugins/VersionComparator.groovy
index fcec1cc82a..2f2886a621 100644
--- a/grails-bootstrap/src/main/groovy/grails/plugins/VersionComparator.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/plugins/VersionComparator.groovy
@@ -32,11 +32,9 @@ class VersionComparator implements Comparator<String> {
int result = 0
if (o1 == '*') {
result = 1
- }
- else if (o2 == '*') {
+ } else if (o2 == '*') {
result = -1
- }
- else {
+ } else {
def nums1
try {
def tokens = deSnapshot(o1).split(/\./)
@@ -63,12 +61,11 @@ class VersionComparator implements Comparator<String> {
if (result != 0) {
break
}
- if (i == (nums1.size()-1) && bigRight) {
- if (nums2[i+1] != 0)
+ if (i == (nums1.size() - 1) && bigRight) {
+ if (nums2[i + 1] != 0)
result = -1; break
}
- }
- else if (bigLeft) {
+ } else if (bigLeft) {
if (nums1[i] != 0)
result = 1; break
}
diff --git a/grails-bootstrap/src/main/groovy/grails/plugins/metadata/GrailsPlugin.java b/grails-bootstrap/src/main/groovy/grails/plugins/metadata/GrailsPlugin.java
index c5b0258c0e..6f00500e74 100644
--- a/grails-bootstrap/src/main/groovy/grails/plugins/metadata/GrailsPlugin.java
+++ b/grails-bootstrap/src/main/groovy/grails/plugins/metadata/GrailsPlugin.java
@@ -32,6 +32,8 @@ import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface GrailsPlugin {
+
String name();
+
String version();
}
diff --git a/grails-bootstrap/src/main/groovy/grails/plugins/metadata/PluginSource.java b/grails-bootstrap/src/main/groovy/grails/plugins/metadata/PluginSource.java
index 202ed16d84..5e0a5e0691 100644
--- a/grails-bootstrap/src/main/groovy/grails/plugins/metadata/PluginSource.java
+++ b/grails-bootstrap/src/main/groovy/grails/plugins/metadata/PluginSource.java
@@ -32,4 +32,5 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE})
public @interface PluginSource {
+
}
diff --git a/grails-bootstrap/src/main/groovy/grails/util/CosineSimilarity.groovy b/grails-bootstrap/src/main/groovy/grails/util/CosineSimilarity.groovy
index 96721ebf5b..6994963e6c 100644
--- a/grails-bootstrap/src/main/groovy/grails/util/CosineSimilarity.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/util/CosineSimilarity.groovy
@@ -28,9 +28,9 @@ class CosineSimilarity {
/**
* Sort the candidates by their similarity to the specified input.
- * @param pattern the input string
- * @param candidates the possible matches
- * @return the ordered candidates
+ * @param pattern the input string
+ * @param candidates the possible matches
+ * @return the ordered candidates
*/
static List<String> mostSimilar(String pattern, candidates, double threshold = 0) {
SortedMap<Double, String> sorted = new TreeMap<Double, String>()
diff --git a/grails-bootstrap/src/main/groovy/grails/util/Described.groovy b/grails-bootstrap/src/main/groovy/grails/util/Described.groovy
index d7febf70d2..a0311669fe 100644
--- a/grails-bootstrap/src/main/groovy/grails/util/Described.groovy
+++ b/grails-bootstrap/src/main/groovy/grails/util/Described.groovy
@@ -16,10 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.util
-
/**
* Interface for classes that are described
*
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/interactive/CandidateListCompletionHandler.java b/grails-bootstrap/src/main/groovy/org/grails/build/interactive/CandidateListCompletionHandler.java
index e09740b679..831fcad2bf 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/interactive/CandidateListCompletionHandler.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/interactive/CandidateListCompletionHandler.java
@@ -18,7 +18,6 @@
*/
package org.grails.build.interactive;
-
import jline.console.ConsoleReader;
import jline.console.CursorBuffer;
import jline.console.completer.CompletionHandler;
@@ -82,7 +81,7 @@ public class CandidateListCompletionHandler implements CompletionHandler {
* <i>foobar</i>, <i>foobaz</i>, <i>foobuz</i>, the
* method will return <i>foob</i>.
*/
- private final String getUnambiguousCompletions(final List<?> candidates) {
+ private String getUnambiguousCompletions(final List<?> candidates) {
if (candidates == null || candidates.isEmpty()) {
return null;
}
@@ -106,9 +105,9 @@ public class CandidateListCompletionHandler implements CompletionHandler {
/**
* @return true is all the elements of <i>candidates</i>
- * start with <i>starts</i>
+ * start with <i>starts</i>
*/
- private final boolean startsWith(final String starts, final String[] candidates) {
+ private boolean startsWith(final String starts, final String[] candidates) {
for (int i = 0; i < candidates.length; i++) {
if (!candidates[i].startsWith(starts)) {
return false;
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.java b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.java
index 63d4f70c3b..c19e7b733d 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleAntBuilder.java
@@ -73,13 +73,14 @@ public class GrailsConsoleAntBuilder extends AntBuilder {
if (!instance.isVerbose()) {
for (Object buildListener : project.getBuildListeners()) {
if (buildListener instanceof BuildLogger) {
- ((BuildLogger)buildListener).setMessageOutputLevel(LogLevel.ERR.getLevel());
+ ((BuildLogger) buildListener).setMessageOutputLevel(LogLevel.ERR.getLevel());
}
}
}
}
private static class GrailsConsoleLogger extends DefaultLogger {
+
/**
* Name of the current target, if it should
* be displayed on the next message. This is
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleBuildListener.java b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleBuildListener.java
index f507539101..4a2d2fd5a2 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleBuildListener.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleBuildListener.java
@@ -53,8 +53,7 @@ public class GrailsConsoleBuildListener implements BuildListener {
* will still be fired if an error occurred during the build.</p>
*
* @param finish An event with any relevant extra information.
- * Must not be <code>null</code>.
- *
+ * Must not be <code>null</code>.
* @see BuildEvent#getException()
*/
public final void buildFinished(final BuildEvent finish) {
@@ -66,7 +65,6 @@ public class GrailsConsoleBuildListener implements BuildListener {
*
* @param start An event with any relevant extra information.
* Must not be <code>null</code>.
- *
* @see BuildEvent#getTarget()
*/
public final void targetStarted(final BuildEvent start) {
@@ -78,8 +76,7 @@ public class GrailsConsoleBuildListener implements BuildListener {
* still be fired if an error occurred during the build.</p>
*
* @param finish An event with any relevant extra information.
- * Must not be <code>null</code>.
- *
+ * Must not be <code>null</code>.
* @see BuildEvent#getException()
*/
public final void targetFinished(final BuildEvent finish) {
@@ -91,7 +88,6 @@ public class GrailsConsoleBuildListener implements BuildListener {
*
* @param start An event with any relevant extra information.
* Must not be <code>null</code>.
- *
* @see BuildEvent#getTask()
*/
public final void taskStarted(final BuildEvent start) {
@@ -103,18 +99,18 @@ public class GrailsConsoleBuildListener implements BuildListener {
* be fired if an error occurred during the build.</p>
*
* @param finish An event with any relevant extra information.
- * Must not be <code>null</code>.
- *
+ * Must not be <code>null</code>.
* @see BuildEvent#getException()
*/
public final void taskFinished(final BuildEvent finish) {
ui.indicateProgress();
}
- /** <p>When a message is sent to this logger, Ant calls this method.</p>
+ /**
+ * <p>When a message is sent to this logger, Ant calls this method.</p>
+ *
* @param event An event with any relevant extra information.
* Must not be <code>null</code>.
- *
* @see BuildEvent#getMessage()
* @see BuildEvent#getPriority()
*/
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleErrorPrintStream.java b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleErrorPrintStream.java
index 20400d3986..377aa39631 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleErrorPrintStream.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsoleErrorPrintStream.java
@@ -35,7 +35,7 @@ public class GrailsConsoleErrorPrintStream extends PrintStream {
}
public PrintStream getTargetOut() {
- return (PrintStream)out;
+ return (PrintStream) out;
}
@Override
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsolePrintStream.java b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsolePrintStream.java
index 69ab0972af..e7c10e57ce 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsolePrintStream.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/logging/GrailsConsolePrintStream.java
@@ -35,7 +35,7 @@ public class GrailsConsolePrintStream extends PrintStream {
}
public PrintStream getTargetOut() {
- return (PrintStream)out;
+ return (PrintStream) out;
}
@Override
diff --git a/grails-bootstrap/src/main/groovy/org/grails/build/parsing/ScriptNameResolver.groovy b/grails-bootstrap/src/main/groovy/org/grails/build/parsing/ScriptNameResolver.groovy
index 872e3452c2..f055dad705 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/build/parsing/ScriptNameResolver.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/build/parsing/ScriptNameResolver.groovy
@@ -33,7 +33,7 @@ class ScriptNameResolver {
* The following scriptNames match FooBar: FB, FoB, FBa
*/
static boolean resolvesTo(String scriptName, String scriptFileName) {
- def scriptFileNameTokens = GrailsNameUtils.getNameFromScript( scriptFileName ).findAll(/[A-Z][a-z]+/)
+ def scriptFileNameTokens = GrailsNameUtils.getNameFromScript(scriptFileName).findAll(/[A-Z][a-z]+/)
def scriptNameTokens = GrailsNameUtils.getNameFromScript(scriptName).findAll(/[A-Z][a-z]*/)
if (scriptFileNameTokens.size() != scriptNameTokens.size()) return false
diff --git a/grails-bootstrap/src/main/groovy/org/grails/config/CodeGenConfig.groovy b/grails-bootstrap/src/main/groovy/org/grails/config/CodeGenConfig.groovy
index 232717bf77..5de2bbbfc2 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/config/CodeGenConfig.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/config/CodeGenConfig.groovy
@@ -40,6 +40,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor
@CompileStatic
@Canonical
class CodeGenConfig implements Cloneable, ConfigMap {
+
final NavigableMap configMap
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(CodeGenConfig.getClassLoader())
@@ -125,7 +126,7 @@ class CodeGenConfig implements Cloneable, ConfigMap {
@Override
def <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
def value = getProperty(key, targetType)
- if(value == null) {
+ if (value == null) {
throw new IllegalStateException("Property [$key] not found")
}
return value
@@ -138,15 +139,15 @@ class CodeGenConfig implements Cloneable, ConfigMap {
def envName = Environment.current.name
def environmentSpecific = getProperty("environments.${envName}", Map.class)
- if(environmentSpecific != null) {
- if(!environmentSpecific.isEmpty()) {
+ if (environmentSpecific != null) {
+ if (!environmentSpecific.isEmpty()) {
mergeMap(environmentSpecific, false)
}
}
}
void loadGroovy(File groovyConfig) {
- if(groovyConfig.exists()) {
+ if (groovyConfig.exists()) {
def envName = Environment.current.name
def configSlurper = new ConfigSlurper(envName)
configSlurper.classLoader = groovyClassLoader
@@ -155,68 +156,68 @@ class CodeGenConfig implements Cloneable, ConfigMap {
}
}
- @CompileDynamic // fails with CompileStatic!
+ @CompileDynamic
+ // fails with CompileStatic!
void loadYml(InputStream input) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()))
- for(Object yamlObject : yaml.loadAll(input)) {
- if(yamlObject instanceof Map) { // problem here with CompileStatic
- mergeMap((Map)yamlObject)
+ for (Object yamlObject : yaml.loadAll(input)) {
+ if (yamlObject instanceof Map) { // problem here with CompileStatic
+ mergeMap((Map) yamlObject)
}
}
}
-
- void mergeMap(Map sourceMap, boolean parseFlatKeys =false) {
+
+ void mergeMap(Map sourceMap, boolean parseFlatKeys = false) {
configMap.merge(sourceMap, parseFlatKeys)
}
-
+
public <T> T navigate(Class<T> requiredType, String... path) {
Object result = configMap.navigate(path)
- if(result == null) {
+ if (result == null) {
return null
}
return convertToType(result, requiredType)
}
-
+
protected <T> T convertToType(Object value, Class<T> requiredType) {
- if(value == null || value instanceof NavigableMap.NullSafeNavigator) {
+ if (value == null || value instanceof NavigableMap.NullSafeNavigator) {
return null
+ } else if (requiredType.isInstance(value)) {
+ return (T) value
}
- else if(requiredType.isInstance(value)) {
- return (T)value
- }
- if(requiredType==String.class) {
+ if (requiredType == String.class) {
return String.valueOf(value)
- } else if(requiredType==Boolean.class) {
+ } else if (requiredType == Boolean.class) {
Boolean booleanObject = toBooleanObject(String.valueOf(value))
return booleanObject != null ? booleanObject : Boolean.FALSE
- } else if (requiredType==boolean) {
+ } else if (requiredType == boolean) {
Boolean booleanObject = toBooleanObject(String.valueOf(value))
return booleanObject != null ? booleanObject.booleanValue() : Boolean.FALSE.booleanValue()
- } else if(requiredType==Integer.class) {
- if(value instanceof Number) {
- return Integer.valueOf(((Number)value).intValue())
+ } else if (requiredType == Integer.class) {
+ if (value instanceof Number) {
+ return Integer.valueOf(((Number) value).intValue())
} else {
return Integer.valueOf(String.valueOf(value))
}
- } else if(requiredType==Long.class) {
- if(value instanceof Number) {
- return Long.valueOf(((Number)value).longValue())
+ } else if (requiredType == Long.class) {
+ if (value instanceof Number) {
+ return Long.valueOf(((Number) value).longValue())
} else {
return Long.valueOf(String.valueOf(value))
}
- } else if(requiredType==Double.class) {
- if(value instanceof Number) {
- return Double.valueOf(((Number)value).doubleValue())
+ } else if (requiredType == Double.class) {
+ if (value instanceof Number) {
+ return Double.valueOf(((Number) value).doubleValue())
} else {
return Double.valueOf(String.valueOf(value))
}
- } else if(requiredType==BigDecimal.class) {
+ } else if (requiredType == BigDecimal.class) {
return new BigDecimal(String.valueOf(value))
} else {
return convertToOtherTypes(value, requiredType)
}
}
-
+
protected <T> T convertToOtherTypes(Object value, Class<T> requiredType) {
throw new RuntimeException("conversion of $value to $requiredType.name not implemented")
}
@@ -224,33 +225,33 @@ class CodeGenConfig implements Cloneable, ConfigMap {
public Object navigate(String... path) {
return navigate(Object, path)
}
-
+
public boolean asBoolean() {
return !configMap.isEmpty()
}
public Object asType(Class type) {
- if(type==Boolean || type==boolean) {
+ if (type == Boolean || type == boolean) {
return asBoolean()
- } else if (type==String) {
+ } else if (type == String) {
return toString()
- } else if (type==Map) {
+ } else if (type == Map) {
return this
- } else if (type==CodeGenConfig) {
+ } else if (type == CodeGenConfig) {
return new CodeGenConfig(this)
} else {
throw new GroovyCastException(this, type)
}
}
-
+
public Object getAt(Object key) {
getProperty(String.valueOf(key))
}
-
+
public void setAt(Object key, Object value) {
setProperty(String.valueOf(key), value)
}
-
+
public Object getProperty(String name) {
if ("configMap".equals(name))
return this.configMap
@@ -269,13 +270,13 @@ class CodeGenConfig implements Cloneable, ConfigMap {
}
public <T> T getProperty(String name, Class<T> requiredType) {
- return convertToType( configMap.get(name), requiredType )
+ return convertToType(configMap.get(name), requiredType)
}
@Override
def <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
def v = getProperty(key, targetType)
- if(v == null) {
+ if (v == null) {
return defaultValue
}
return v
@@ -284,8 +285,7 @@ class CodeGenConfig implements Cloneable, ConfigMap {
public void setProperty(String name, Object value) {
configMap.setProperty(name, value)
}
-
-
+
/**
* toBooleanObject method ported from org.apache.commons.lang.BooleanUtils.toBooleanObject to Groovy code
* @param str
@@ -299,27 +299,27 @@ class CodeGenConfig implements Cloneable, ConfigMap {
return null
}
int strlen = str.length()
- if (strlen==0) {
+ if (strlen == 0) {
return null
} else if (strlen == 1) {
char ch0 = str.charAt(0)
if ((ch0 == 'y' || ch0 == 'Y') ||
- (ch0 == 't' || ch0 == 'T')) {
+ (ch0 == 't' || ch0 == 'T')) {
return Boolean.TRUE
}
if ((ch0 == 'n' || ch0 == 'N') ||
- (ch0 == 'f' || ch0 == 'F')) {
+ (ch0 == 'f' || ch0 == 'F')) {
return Boolean.FALSE
}
} else if (strlen == 2) {
char ch0 = str.charAt(0)
char ch1 = str.charAt(1)
if ((ch0 == 'o' || ch0 == 'O') &&
- (ch1 == 'n' || ch1 == 'N') ) {
+ (ch1 == 'n' || ch1 == 'N')) {
return Boolean.TRUE
}
if ((ch0 == 'n' || ch0 == 'N') &&
- (ch1 == 'o' || ch1 == 'O') ) {
+ (ch1 == 'o' || ch1 == 'O')) {
return Boolean.FALSE
}
} else if (strlen == 3) {
@@ -327,13 +327,13 @@ class CodeGenConfig implements Cloneable, ConfigMap {
char ch1 = str.charAt(1)
char ch2 = str.charAt(2)
if ((ch0 == 'y' || ch0 == 'Y') &&
- (ch1 == 'e' || ch1 == 'E') &&
- (ch2 == 's' || ch2 == 'S') ) {
+ (ch1 == 'e' || ch1 == 'E') &&
+ (ch2 == 's' || ch2 == 'S')) {
return Boolean.TRUE
}
if ((ch0 == 'o' || ch0 == 'O') &&
- (ch1 == 'f' || ch1 == 'F') &&
- (ch2 == 'f' || ch2 == 'F') ) {
+ (ch1 == 'f' || ch1 == 'F') &&
+ (ch2 == 'f' || ch2 == 'F')) {
return Boolean.FALSE
}
} else if (strlen == 4) {
@@ -342,9 +342,9 @@ class CodeGenConfig implements Cloneable, ConfigMap {
char ch2 = str.charAt(2)
char ch3 = str.charAt(3)
if ((ch0 == 't' || ch0 == 'T') &&
- (ch1 == 'r' || ch1 == 'R') &&
- (ch2 == 'u' || ch2 == 'U') &&
- (ch3 == 'e' || ch3 == 'E') ) {
+ (ch1 == 'r' || ch1 == 'R') &&
+ (ch2 == 'u' || ch2 == 'U') &&
+ (ch3 == 'e' || ch3 == 'E')) {
return Boolean.TRUE
}
} else if (strlen == 5) {
@@ -354,10 +354,10 @@ class CodeGenConfig implements Cloneable, ConfigMap {
char ch3 = str.charAt(3)
char ch4 = str.charAt(4)
if ((ch0 == 'f' || ch0 == 'F') &&
- (ch1 == 'a' || ch1 == 'A') &&
- (ch2 == 'l' || ch2 == 'L') &&
- (ch3 == 's' || ch3 == 'S') &&
- (ch4 == 'e' || ch4 == 'E') ) {
+ (ch1 == 'a' || ch1 == 'A') &&
+ (ch2 == 'l' || ch2 == 'L') &&
+ (ch3 == 's' || ch3 == 'S') &&
+ (ch4 == 'e' || ch4 == 'E')) {
return Boolean.FALSE
}
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/config/NavigableMap.groovy b/grails-bootstrap/src/main/groovy/org/grails/config/NavigableMap.groovy
index 94a2a9c352..fde5adc061 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/config/NavigableMap.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/config/NavigableMap.groovy
@@ -70,7 +70,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
this.rootConfig = rootConfig
this.path = path
dottedPath = path.join('.')
- this.delegateMap= delegateMap
+ this.delegateMap = delegateMap
}
@Override
@@ -148,7 +148,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
delegateMap.entrySet()
}
- void merge(Map sourceMap, boolean parseFlatKeys=false) {
+ void merge(Map sourceMap, boolean parseFlatKeys = false) {
mergeMaps(this, "", this, sourceMap, parseFlatKeys)
}
@@ -158,7 +158,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
Map sourceMap,
boolean parseFlatKeys) {
- if(springProfileExclude(sourceMap, path)) {
+ if (springProfileExclude(sourceMap, path)) {
return
}
@@ -189,7 +189,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
def activeSpringProfile = System.getProperty(SPRING_PROFILES)
// Is there a 'spring.config.activate.on-profile' property defined in the source map?
- def sourceMapProfile1 = ((Map)((Map)((Map)sourceMap?.get(SPRING))?.get(CONFIG))?.get(ACTIVATE))?.get(ON_PROFILE)
+ def sourceMapProfile1 = ((Map) ((Map) ((Map) sourceMap?.get(SPRING))?.get(CONFIG))?.get(ACTIVATE))?.get(ON_PROFILE)
if (!sourceMapProfile1 && path == "$SPRING.$CONFIG.$ACTIVATE") {
sourceMapProfile1 = sourceMap?.get(ON_PROFILE)
}
@@ -206,7 +206,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
}
// Is there a 'spring.profiles' property defined in the source map? (Old way of Spring profiles activation)
- def sourceMapProfile2 = ((Map)sourceMap?.get(SPRING))?.get(PROFILES)
+ def sourceMapProfile2 = ((Map) sourceMap?.get(SPRING))?.get(PROFILES)
if (!sourceMapProfile2 && path == SPRING) {
sourceMapProfile2 = sourceMap?.get(PROFILES)
}
@@ -235,106 +235,105 @@ class NavigableMap implements Map<String, Object>, Cloneable {
int subscriptStart = sourceKey.indexOf('[')
int subscriptEnd = sourceKey.indexOf(']')
if (subscriptEnd > subscriptStart) {
- if(subscriptStart > -1) {
- String k = sourceKey[0..<subscriptStart]
- String index = sourceKey[subscriptStart+1..<subscriptEnd]
- String remainder = subscriptEnd != sourceKey.length() -1 ? sourceKey[subscriptEnd+2..-1] : null
- if (remainder) {
-
- boolean isNumber = index.isNumber()
- if (isNumber) {
- int i = index.toInteger()
- def currentValue = targetMap.get(k)
- List list = currentValue instanceof List ? currentValue : []
- if (list.size() > i) {
- def v = list.get(i)
- if (v instanceof Map) {
- ((Map)v).put(remainder, sourceValue)
- } else {
- Map newMap = [:]
- newMap.put(remainder, sourceValue)
- fill(list, i, null)
- list.set(i, newMap)
- }
- } else {
- Map newMap = [:]
- newMap.put(remainder, sourceValue)
- fill(list, i, null)
- list.set(i, newMap)
- }
- targetMap.put(k, list)
- } else {
- def currentValue = targetMap.get(k)
- Map nestedMap = currentValue instanceof Map ? currentValue : [:]
- targetMap.put(k, nestedMap)
-
- def v = nestedMap.get(index)
- if (v instanceof Map) {
- ((Map)v).put(remainder, sourceValue)
- } else {
- Map newMap = [:]
- newMap.put(remainder, sourceValue)
- nestedMap.put(index, newMap)
- }
- }
- } else {
- def currentValue = targetMap.get(k)
- if (index.isNumber()) {
- List list = currentValue instanceof List ? currentValue : []
- int i = index.toInteger()
- fill(list, i, null)
- list.set(i, sourceValue)
- targetMap.put(k, list)
- } else {
- Map nestedMap = currentValue instanceof Map ? currentValue : [:]
- targetMap.put(k, nestedMap)
- nestedMap.put(index, sourceValue)
- }
- targetMap.put(sourceKey, sourceValue)
- }
-
- }
+ if (subscriptStart > -1) {
+ String k = sourceKey[0..<subscriptStart]
+ String index = sourceKey[subscriptStart + 1..<subscriptEnd]
+ String remainder = subscriptEnd != sourceKey.length() - 1 ? sourceKey[subscriptEnd + 2..-1] : null
+ if (remainder) {
+
+ boolean isNumber = index.isNumber()
+ if (isNumber) {
+ int i = index.toInteger()
+ def currentValue = targetMap.get(k)
+ List list = currentValue instanceof List ? currentValue : []
+ if (list.size() > i) {
+ def v = list.get(i)
+ if (v instanceof Map) {
+ ((Map) v).put(remainder, sourceValue)
+ } else {
+ Map newMap = [:]
+ newMap.put(remainder, sourceValue)
+ fill(list, i, null)
+ list.set(i, newMap)
+ }
+ } else {
+ Map newMap = [:]
+ newMap.put(remainder, sourceValue)
+ fill(list, i, null)
+ list.set(i, newMap)
+ }
+ targetMap.put(k, list)
+ } else {
+ def currentValue = targetMap.get(k)
+ Map nestedMap = currentValue instanceof Map ? currentValue : [:]
+ targetMap.put(k, nestedMap)
+
+ def v = nestedMap.get(index)
+ if (v instanceof Map) {
+ ((Map) v).put(remainder, sourceValue)
+ } else {
+ Map newMap = [:]
+ newMap.put(remainder, sourceValue)
+ nestedMap.put(index, newMap)
+ }
+ }
+ } else {
+ def currentValue = targetMap.get(k)
+ if (index.isNumber()) {
+ List list = currentValue instanceof List ? currentValue : []
+ int i = index.toInteger()
+ fill(list, i, null)
+ list.set(i, sourceValue)
+ targetMap.put(k, list)
+ } else {
+ Map nestedMap = currentValue instanceof Map ? currentValue : [:]
+ targetMap.put(k, nestedMap)
+ nestedMap.put(index, sourceValue)
+ }
+ targetMap.put(sourceKey, sourceValue)
+ }
+
+ }
} else {
Object currentValue = targetMap.containsKey(sourceKey) ? targetMap.get(sourceKey) : null
Object newValue
- if(sourceValue instanceof Map) {
+ if (sourceValue instanceof Map) {
List<String> newPathList = []
- newPathList.addAll( targetMap.getPath() )
+ newPathList.addAll(targetMap.getPath())
newPathList.add(sourceKey)
NavigableMap subMap
- if(currentValue instanceof NavigableMap) {
- subMap = (NavigableMap)currentValue
- }
- else {
+ if (currentValue instanceof NavigableMap) {
+ subMap = (NavigableMap) currentValue
+ } else {
subMap = new NavigableMap(targetMap.getRootConfig(), newPathList.asImmutable())
- if(currentValue instanceof Map) {
- subMap.putAll((Map)currentValue)
+ if (currentValue instanceof Map) {
+ subMap.putAll((Map) currentValue)
}
}
String newPath = path ? "${path}.${sourceKey}" : sourceKey
- mergeMaps(rootMap, newPath , subMap, (Map)sourceValue, parseFlatKeys)
+ mergeMaps(rootMap, newPath, subMap, (Map) sourceValue, parseFlatKeys)
newValue = subMap
} else {
newValue = sourceValue
}
if (isNestedSet && newValue == null) {
- if(path) {
+ if (path) {
def subMap = rootMap.get(path)
- if(subMap instanceof Map) {
+ if (subMap instanceof Map) {
subMap.remove(sourceKey)
}
def keysToRemove = rootMap.keySet().findAll() { String key ->
key.startsWith("${path}.")
}
- for(key in keysToRemove) {
+ for (key in keysToRemove) {
rootMap.remove(key)
}
}
targetMap.remove(sourceKey)
} else {
- if(path) {
- rootMap.put( "${path}.${sourceKey}".toString(), newValue )
+ if (path) {
+ rootMap.put("${path}.${sourceKey}".toString(), newValue)
}
mergeMapEntry(targetMap, sourceKey, newValue)
}
@@ -373,16 +372,16 @@ class NavigableMap implements Map<String, Object>, Cloneable {
Object navigate(String... path) {
return navigateMap(this, path)
}
-
+
private Object navigateMap(Map<String, Object> map, String... path) {
- if(map==null || path == null) return null
- if(path.length == 0) {
+ if (map == null || path == null) return null
+ if (path.length == 0) {
return map
} else if (path.length == 1) {
return map.get(path[0])
} else {
def submap = map.get(path[0])
- if(submap instanceof Map) {
+ if (submap instanceof Map) {
return navigateMap((Map<String, Object>) submap, path.tail())
}
return submap
@@ -402,28 +401,27 @@ class NavigableMap implements Map<String, Object>, Cloneable {
NavigableMap currentMap = this
StringBuilder accumulatedPath = new StringBuilder()
boolean isFirst = true
- for(String pathElement : path) {
- if(!isFirst) {
+ for (String pathElement : path) {
+ if (!isFirst) {
accumulatedPath.append(".").append(pathElement)
- }
- else {
+ } else {
isFirst = false
accumulatedPath.append(pathElement)
}
- Object currentItem = currentMap.get(pathElement)
- if(currentItem instanceof NavigableMap) {
- currentMap = (NavigableMap)currentItem
+ Object currentItem = currentMap.get(pathElement)
+ if (currentItem instanceof NavigableMap) {
+ currentMap = (NavigableMap) currentItem
} else if (createMissing) {
List<String> newPathList = []
- newPathList.addAll( currentMap.getPath() )
+ newPathList.addAll(currentMap.getPath())
newPathList.add(pathElement)
Map<String, Object> newMap = new NavigableMap(currentMap.getRootConfig(), newPathList.asImmutable())
currentMap.put(pathElement, newMap)
def fullPath = accumulatedPath.toString()
- if(!rootMap.containsKey(fullPath)) {
+ if (!rootMap.containsKey(fullPath)) {
rootMap.put(fullPath, newMap)
}
currentMap = newMap
@@ -433,44 +431,44 @@ class NavigableMap implements Map<String, Object>, Cloneable {
}
currentMap
}
-
+
Map<String, Object> toFlatConfig() {
Map<String, Object> flatConfig = [:]
flattenKeys(flatConfig, this, [], false)
flatConfig
}
-
+
Properties toProperties() {
Properties properties = new Properties()
flattenKeys((Map<Object, Object>) properties, this, [], true)
properties
}
-
+
private void flattenKeys(Map<? extends Object, Object> flatConfig, Map currentMap, List<String> path, boolean forceStrings) {
currentMap.each { key, value ->
String stringKey = String.valueOf(key)
- if(value != null) {
- if(value instanceof Map) {
+ if (value != null) {
+ if (value instanceof Map) {
List<String> newPathList = []
- newPathList.addAll( path )
- newPathList.add( stringKey )
+ newPathList.addAll(path)
+ newPathList.add(stringKey)
- flattenKeys(flatConfig, (Map)value, newPathList.asImmutable(), forceStrings)
+ flattenKeys(flatConfig, (Map) value, newPathList.asImmutable(), forceStrings)
} else {
String fullKey
- if(path) {
+ if (path) {
fullKey = path.join('.') + '.' + stringKey
} else {
fullKey = stringKey
}
- if(value instanceof Collection) {
- if(forceStrings) {
- flatConfig.put(fullKey, ((Collection)value).join(","))
+ if (value instanceof Collection) {
+ if (forceStrings) {
+ flatConfig.put(fullKey, ((Collection) value).join(","))
} else {
flatConfig.put(fullKey, value)
}
int index = 0
- for(Object item: (Collection)value) {
+ for (Object item : (Collection) value) {
String collectionKey = "${fullKey}[${index}]".toString()
flatConfig.put(collectionKey, forceStrings ? String.valueOf(item) : item)
index++
@@ -480,7 +478,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
}
}
}
- }
+ }
}
@Override
@@ -498,7 +496,8 @@ class NavigableMap implements Map<String, Object>, Cloneable {
*/
@Deprecated
@CompileStatic
- static class NullSafeNavigator implements Map<String, Object>{
+ static class NullSafeNavigator implements Map<String, Object> {
+
final NavigableMap parent
final List<String> path
@@ -521,7 +520,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
int size() {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.size()
}
return 0
@@ -530,7 +529,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
boolean isEmpty() {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.isEmpty()
}
return true
@@ -538,7 +537,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
boolean containsKey(Object key) {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap == null) return false
+ if (parentMap == null) return false
else {
return parentMap.containsKey(key)
}
@@ -547,7 +546,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
boolean containsValue(Object value) {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.containsValue(value)
}
return false
@@ -581,7 +580,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
Set<String> keySet() {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.keySet()
}
return Collections.emptySet()
@@ -590,7 +589,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
Collection<Object> values() {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.values()
}
return Collections.emptySet()
@@ -599,7 +598,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
@Override
Set<Entry<String, Object>> entrySet() {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap != null) {
+ if (parentMap != null) {
return parentMap.entrySet()
}
return Collections.emptySet()
@@ -607,7 +606,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
Object getProperty(String name) {
NavigableMap parentMap = parent.navigateSubMap(path, false)
- if(parentMap == null) {
+ if (parentMap == null) {
return new NullSafeNavigator(parent, ((path + [name]) as List<String>).asImmutable())
} else {
return parentMap.get(name)
@@ -648,7 +647,7 @@ class NavigableMap implements Map<String, Object>, Cloneable {
}
Object asType(Class c) {
- if(c==Boolean || c==boolean) return false
+ if (c == Boolean || c == boolean) return false
return null
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/ExceptionUtils.groovy b/grails-bootstrap/src/main/groovy/org/grails/exceptions/ExceptionUtils.groovy
index 6e733ffd51..815418617c 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/ExceptionUtils.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/ExceptionUtils.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.exceptions
import groovy.transform.CompileStatic
@@ -35,7 +34,6 @@ class ExceptionUtils {
public static final String EXCEPTION_ATTRIBUTE = "exception";
-
static RuntimeException getFirstRuntimeException(Throwable e) {
if (e instanceof RuntimeException) return (RuntimeException) e
@@ -61,10 +59,10 @@ class ExceptionUtils {
static int extractLineNumber(CompilationFailedException e) {
int lineNumber = -1
if (e instanceof MultipleCompilationErrorsException) {
- MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException)e
+ MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) e
Object message = mcee.errorCollector.errors.iterator().next()
if (message instanceof SyntaxErrorMessage) {
- SyntaxErrorMessage sem = (SyntaxErrorMessage)message
+ SyntaxErrorMessage sem = (SyntaxErrorMessage) message
lineNumber = sem.cause.line
}
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.java b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.java
index 95215b5e82..05b994d94b 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTraceFilterer.java
@@ -28,31 +28,32 @@ import java.util.List;
/**
* Default implementation of StackTraceFilterer.
*
- * @since 2.0
* @author Graeme Rocher
+ * @since 2.0
*/
public class DefaultStackTraceFilterer implements StackTraceFilterer {
+
public static final String STACK_LOG_NAME = "StackTrace";
public static final Log STACK_LOG = LogFactory.getLog(STACK_LOG_NAME);
- private static final String[] DEFAULT_INTERNAL_PACKAGES = new String[] {
- "org.codehaus.groovy.runtime.",
- "org.codehaus.groovy.reflection.",
- "org.codehaus.groovy.ast.",
- "org.springframework.web.filter",
- "org.springframework.boot.actuate",
- "org.mortbay.",
- "groovy.lang.",
- "org.apache.catalina.",
- "org.apache.coyote.",
- "org.apache.tomcat.",
- "net.sf.cglib.proxy.",
- "sun.",
- "java.lang.reflect.",
- "org.springframework.boot.devtools.",
- "org.springsource.loaded.",
- "com.opensymphony.",
- "jakarta.servlet."
+ private static final String[] DEFAULT_INTERNAL_PACKAGES = new String[]{
+ "org.codehaus.groovy.runtime.",
+ "org.codehaus.groovy.reflection.",
+ "org.codehaus.groovy.ast.",
+ "org.springframework.web.filter",
+ "org.springframework.boot.actuate",
+ "org.mortbay.",
+ "groovy.lang.",
+ "org.apache.catalina.",
+ "org.apache.coyote.",
+ "org.apache.tomcat.",
+ "net.sf.cglib.proxy.",
+ "sun.",
+ "java.lang.reflect.",
+ "org.springframework.boot.devtools.",
+ "org.springsource.loaded.",
+ "com.opensymphony.",
+ "jakarta.servlet."
};
private List<String> packagesToFilter = new ArrayList<String>();
@@ -69,7 +70,9 @@ public class DefaultStackTraceFilterer implements StackTraceFilterer {
}
public void addInternalPackage(String name) {
- if (name == null) throw new IllegalArgumentException("Package name cannot be null");
+ if (name == null) {
+ throw new IllegalArgumentException("Package name cannot be null");
+ }
packagesToFilter.add(name);
}
@@ -120,7 +123,9 @@ public class DefaultStackTraceFilterer implements StackTraceFilterer {
if (!foundGroovy && fileName != null && fileName.endsWith(".groovy")) {
foundGroovy = true;
}
- if (endPackage != null && className.startsWith(endPackage) && foundGroovy) break;
+ if (endPackage != null && className.startsWith(endPackage) && foundGroovy) {
+ break;
+ }
if (isApplicationClass(className)) {
if (stackTraceElement.getLineNumber() > -1) {
newTrace.add(stackTraceElement);
@@ -132,12 +137,15 @@ public class DefaultStackTraceFilterer implements StackTraceFilterer {
/**
* Whether the given class name is an internal class and should be filtered
+ *
* @param className The class name
* @return true if is internal
*/
protected boolean isApplicationClass(String className) {
for (String packageName : packagesToFilter) {
- if (className.startsWith(packageName)) return false;
+ if (className.startsWith(packageName)) {
+ return false;
+ }
}
return true;
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTracePrinter.groovy b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTracePrinter.groovy
index 1673bc7d60..b80dfa606c 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTracePrinter.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/DefaultStackTracePrinter.groovy
@@ -62,23 +62,21 @@ class DefaultStackTracePrinter implements StackTracePrinter {
printCausedByMessage(sb, e)
}
if (e instanceof MultipleCompilationErrorsException) break
- if(last > 0) {
+ if (last > 0) {
stackTrace[0..-1].eachWithIndex { te, idx ->
def fileName = getFileName(te)
def lineNumber
if (e instanceof SourceCodeAware) {
if (e.lineNumber && e.lineNumber > -1) {
lineNumber = e.lineNumber.toString().padLeft(lineNumWidth)
- }
- else {
+ } else {
lineNumber = te.lineNumber.toString().padLeft(lineNumWidth)
}
if (e.fileName) {
fileName = e.fileName
fileName = makeRelativeIfPossible(fileName)
}
- }
- else {
+ } else {
lineNumber = te.lineNumber.toString().padLeft(lineNumWidth)
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/SourceCodeAware.java b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/SourceCodeAware.java
index a826fd04f2..10abd7b27a 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/SourceCodeAware.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/SourceCodeAware.java
@@ -27,6 +27,7 @@ import java.io.Serializable;
* @since 1.0
*/
public interface SourceCodeAware extends Serializable {
+
String getFileName();
int getLineNumber();
diff --git a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/StackTraceFilterer.java b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/StackTraceFilterer.java
index ff0d9b6786..cb6e61c0b5 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/StackTraceFilterer.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/exceptions/reporting/StackTraceFilterer.java
@@ -21,8 +21,8 @@ package org.grails.exceptions.reporting;
/**
* Improves the output of stack traces produced by exceptions in a Grails application.
*
- * @since 2.0
* @author Graeme Rocher
+ * @since 2.0
*/
public interface StackTraceFilterer {
@@ -38,6 +38,7 @@ public interface StackTraceFilterer {
/**
* Sets the package where the stack trace should end
+ *
* @param cutOffPackage The cut off package
*/
void setCutOffPackage(String cutOffPackage);
@@ -45,7 +46,8 @@ public interface StackTraceFilterer {
/**
* <p>Remove all apparently Grails-internal trace entries from the exception instance<p>
* <p>This modifies the original instance and returns it, it does not clone</p>
- * @param source The source exception
+ *
+ * @param source The source exception
* @param recursive Whether to recursively filter the cause
* @return The exception passed in, after cleaning the stack trace
*/
@@ -54,6 +56,7 @@ public interface StackTraceFilterer {
/**
* <p>Remove all apparently Grails-internal trace entries from the exception instance<p>
* <p>This modifies the original instance and returns it, it does not clone</p>
+ *
* @param source The source exception
* @return The exception passed in, after cleaning the stack trace
*/
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.java
index d92fcccb0f..4d9831e46f 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/AntPathMatcher.java
@@ -50,16 +50,20 @@ import org.codehaus.groovy.runtime.StringGroovyMethods;
* @author Arjen Poutsma
* @since 16.07.2003
*/
-public class AntPathMatcher {
+public final class AntPathMatcher {
- private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}");
-
- /** Default path separator: "/" */
+ /**
+ * Default path separator: "/"
+ */
public static final String DEFAULT_PATH_SEPARATOR = "/";
+ private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}");
+
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
- /** Set the path separator to use for pattern parsing. Default is "/", as in Ant. */
+ /**
+ * Set the path separator to use for pattern parsing. Default is "/", as in Ant.
+ */
public void setPathSeparator(String pathSeparator) {
this.pathSeparator = pathSeparator == null ? DEFAULT_PATH_SEPARATOR : pathSeparator;
}
@@ -78,10 +82,11 @@ public class AntPathMatcher {
/**
* Actually match the given <code>path</code> against the given <code>pattern</code>.
- * @param pattern the pattern to match against
- * @param path the path String to test
+ *
+ * @param pattern the pattern to match against
+ * @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern match
- * as far as the given base path goes is sufficient)
+ * as far as the given base path goes is sufficient)
* @return <code>true</code> if the supplied <code>path</code> matched, <code>false</code> if it didn't
*/
protected boolean doMatch(String pattern, String path, boolean fullMatch,
@@ -130,12 +135,10 @@ public class AntPathMatcher {
}
}
return true;
- }
- else if (pattIdxStart > pattIdxEnd) {
+ } else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
- }
- else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
+ } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
@@ -212,15 +215,16 @@ public class AntPathMatcher {
}
private String[] tokenize(String pattern) {
- List<String> list = StringGroovyMethods.tokenize((CharSequence)pattern, (CharSequence)pathSeparator);
+ List<String> list = StringGroovyMethods.tokenize((CharSequence) pattern, (CharSequence) pathSeparator);
return list.toArray(new String[list.size()]);
}
/**
* Tests whether or not a string matches against a pattern. The pattern may contain two special characters:<br> '*'
* means zero or more characters<br> '?' means one and only one character
+ *
* @param pattern pattern to match against. Must not be <code>null</code>.
- * @param str string which must be matched against the pattern. Must not be <code>null</code>.
+ * @param str string which must be matched against the pattern. Must not be <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise.
*/
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) {
@@ -273,7 +277,8 @@ public class AntPathMatcher {
public Map<String, String> extractUriTemplateVariables(String pattern, String path) {
Map<String, String> variables = new LinkedHashMap<String, String>();
- /*boolean result =*/ doMatch(pattern, path, true, variables);
+ /*boolean result =*/
+ doMatch(pattern, path, true, variables);
return variables;
}
@@ -291,6 +296,7 @@ public class AntPathMatcher {
* <tr><td>/hotels/**</td><td>{hotel}</td><td>/hotels/**/{hotel}</td></tr>
* <tr><td>/*.html</td><td>/hotels.html</td><td>/hotels.html</td></tr> <tr><td>/*.html</td><td>/hotels</td><td>/hotels.html</td></tr>
* <tr><td>/*.html</td><td>/*.txt</td><td>IllegalArgumentException</td></tr> </table>
+ *
* @param pattern1 the first pattern
* @param pattern2 the second pattern
* @return the combination of the two patterns
@@ -341,8 +347,7 @@ public class AntPathMatcher {
if (dotPos2 != -1) {
fileName2 = pattern2.substring(0, dotPos2);
extension2 = pattern2.substring(dotPos2);
- }
- else {
+ } else {
fileName2 = pattern2;
extension2 = "";
}
@@ -353,7 +358,7 @@ public class AntPathMatcher {
}
private boolean hasText(String txt) {
- return txt != null && txt.length()>0;
+ return txt != null && txt.length() > 0;
}
/**
@@ -365,6 +370,7 @@ public class AntPathMatcher {
* list so that the order will be as indicated.
* <p>The full path given as parameter is used to test for exact matches. So when the given path is {@code /hotels/2},
* the pattern {@code /hotels/2} will be sorted before {@code /hotels/1}.
+ *
* @param path the full path to use for comparison
* @return a comparator capable of sorting patterns in order of explicitness
*/
@@ -372,86 +378,24 @@ public class AntPathMatcher {
return new AntPatternComparator(path);
}
- private static class AntPatternComparator implements Comparator<String> {
-
- private final String path;
-
- private AntPatternComparator(String path) {
- this.path = path;
- }
-
- public int compare(String pattern1, String pattern2) {
- if (pattern1 == null && pattern2 == null) {
- return 0;
- }
- else if (pattern1 == null) {
- return 1;
- }
- else if (pattern2 == null) {
- return -1;
- }
- boolean pattern1EqualsPath = pattern1.equals(path);
- boolean pattern2EqualsPath = pattern2.equals(path);
- if (pattern1EqualsPath && pattern2EqualsPath) {
- return 0;
- }
- else if (pattern1EqualsPath) {
- return -1;
- }
- else if (pattern2EqualsPath) {
- return 1;
- }
- int wildCardCount1 = getWildCardCount(pattern1);
- int wildCardCount2 = getWildCardCount(pattern2);
-
- int bracketCount1 = countOccurrencesOf(pattern1, "{");
- int bracketCount2 = countOccurrencesOf(pattern2, "{");
-
- int totalCount1 = wildCardCount1 + bracketCount1;
- int totalCount2 = wildCardCount2 + bracketCount2;
-
- if (totalCount1 != totalCount2) {
- return totalCount1 - totalCount2;
- }
-
- int pattern1Length = getPatternLength(pattern1);
- int pattern2Length = getPatternLength(pattern2);
-
- if (pattern1Length != pattern2Length) {
- return pattern2Length - pattern1Length;
- }
-
- if (wildCardCount1 < wildCardCount2) {
- return -1;
- }
- else if (wildCardCount2 < wildCardCount1) {
- return 1;
- }
-
- if (bracketCount1 < bracketCount2) {
- return -1;
- }
- else if (bracketCount2 < bracketCount1) {
- return 1;
- }
-
+ /**
+ * Count the occurrences of the substring in string s.
+ *
+ * @param str string to search in. Return 0 if this is null.
+ * @param sub string to search for. Return 0 if this is null.
+ */
+ public static int countOccurrencesOf(String str, String sub) {
+ if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
return 0;
}
-
- private int getWildCardCount(String pattern) {
- if (pattern.endsWith(".*")) {
- pattern = pattern.substring(0, pattern.length() - 2);
- }
- return countOccurrencesOf(pattern, "*");
- }
-
- /**
- * Returns the length of the given pattern, where template variables are considered to be 1 long.
- */
- private int getPatternLength(String pattern) {
- Matcher m = VARIABLE_PATTERN.matcher(pattern);
- return m.replaceAll("#").length();
+ int count = 0;
+ int pos = 0;
+ int idx;
+ while ((idx = str.indexOf(sub, pos)) != -1) {
+ ++count;
+ pos = idx + sub.length();
}
+ return count;
}
/**
@@ -465,7 +409,7 @@ public class AntPathMatcher {
* @author Rossen Stoyanchev
* @since 3.0
*/
- static class AntPathStringMatcher {
+ static class AntPathStringMatcher {
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}");
@@ -479,7 +423,9 @@ public class AntPathMatcher {
private final Map<String, String> uriTemplateVariables;
- /** Construct a new instance of the <code>AntPatchStringMatcher</code>. */
+ /**
+ * Construct a new instance of the <code>AntPatchStringMatcher</code>.
+ */
AntPathStringMatcher(String pattern, String str, Map<String, String> uriTemplateVariables) {
this.str = str;
this.uriTemplateVariables = uriTemplateVariables;
@@ -495,17 +441,14 @@ public class AntPathMatcher {
String match = m.group();
if ("?".equals(match)) {
patternBuilder.append('.');
- }
- else if ("*".equals(match)) {
+ } else if ("*".equals(match)) {
patternBuilder.append(".*");
- }
- else if (match.startsWith("{") && match.endsWith("}")) {
+ } else if (match.startsWith("{") && match.endsWith("}")) {
int colonIdx = match.indexOf(':');
if (colonIdx == -1) {
patternBuilder.append(DEFAULT_VARIABLE_PATTERN);
variableNames.add(m.group(1));
- }
- else {
+ } else {
String variablePattern = match.substring(colonIdx + 1, match.length() - 1);
patternBuilder.append('(');
patternBuilder.append(variablePattern);
@@ -548,22 +491,79 @@ public class AntPathMatcher {
}
}
- /**
- * Count the occurrences of the substring in string s.
- * @param str string to search in. Return 0 if this is null.
- * @param sub string to search for. Return 0 if this is null.
- */
- public static int countOccurrencesOf(String str, String sub) {
- if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
+ private static final class AntPatternComparator implements Comparator<String> {
+
+ private final String path;
+
+ private AntPatternComparator(String path) {
+ this.path = path;
+ }
+
+ public int compare(String pattern1, String pattern2) {
+ if (pattern1 == null && pattern2 == null) {
+ return 0;
+ } else if (pattern1 == null) {
+ return 1;
+ } else if (pattern2 == null) {
+ return -1;
+ }
+ boolean pattern1EqualsPath = pattern1.equals(path);
+ boolean pattern2EqualsPath = pattern2.equals(path);
+ if (pattern1EqualsPath && pattern2EqualsPath) {
+ return 0;
+ } else if (pattern1EqualsPath) {
+ return -1;
+ } else if (pattern2EqualsPath) {
+ return 1;
+ }
+ int wildCardCount1 = getWildCardCount(pattern1);
+ int wildCardCount2 = getWildCardCount(pattern2);
+
+ int bracketCount1 = countOccurrencesOf(pattern1, "{");
+ int bracketCount2 = countOccurrencesOf(pattern2, "{");
+
+ int totalCount1 = wildCardCount1 + bracketCount1;
+ int totalCount2 = wildCardCount2 + bracketCount2;
+
+ if (totalCount1 != totalCount2) {
+ return totalCount1 - totalCount2;
+ }
+
+ int pattern1Length = getPatternLength(pattern1);
+ int pattern2Length = getPatternLength(pattern2);
+
+ if (pattern1Length != pattern2Length) {
+ return pattern2Length - pattern1Length;
+ }
+
+ if (wildCardCount1 < wildCardCount2) {
+ return -1;
+ } else if (wildCardCount2 < wildCardCount1) {
+ return 1;
+ }
+
+ if (bracketCount1 < bracketCount2) {
+ return -1;
+ } else if (bracketCount2 < bracketCount1) {
+ return 1;
+ }
+
return 0;
}
- int count = 0;
- int pos = 0;
- int idx;
- while ((idx = str.indexOf(sub, pos)) != -1) {
- ++count;
- pos = idx + sub.length();
+
+ private int getWildCardCount(String pattern) {
+ if (pattern.endsWith(".*")) {
+ pattern = pattern.substring(0, pattern.length() - 2);
+ }
+ return countOccurrencesOf(pattern, "*");
+ }
+
+ /**
+ * Returns the length of the given pattern, where template variables are considered to be 1 long.
+ */
+ private int getPatternLength(String pattern) {
+ Matcher m = VARIABLE_PATTERN.matcher(pattern);
+ return m.replaceAll("#").length();
}
- return count;
}
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/DevNullPrintStream.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/support/DevNullPrintStream.groovy
index 3017de89a7..fdd05df47b 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/DevNullPrintStream.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/DevNullPrintStream.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.support
import groovy.transform.CompileStatic
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.java b/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.java
index 6b791c3e63..c3e0b3c488 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/FileSystemResourceLoader.java
@@ -27,13 +27,13 @@ package org.grails.io.support;
* to the current VM working directory, even if they start with a slash.
* (This is consistent with the semantics in a Servlet container.)
* <b>Use an explicit "file:" prefix to enforce an absolute file path.</b>
- *
+ * <p>
* is a full-fledged ApplicationContext implementation that provides
* the same resource path resolution strategy.
*
* @author Juergen Hoeller
- * @since 1.1.3
* @see DefaultResourceLoader
+ * @since 1.1.3
*/
public class FileSystemResourceLoader extends DefaultResourceLoader {
@@ -41,6 +41,7 @@ public class FileSystemResourceLoader extends DefaultResourceLoader {
* Resolve resource paths as file system paths.
* <p>Note: Even if a given path starts with a slash, it will get
* interpreted as relative to the current VM working directory.
+ *
* @param path the path to the resource
* @return the corresponding Resource handle
* @see FileSystemResource
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.java b/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.java
index 7205754f75..744db9b3df 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/PathMatchingResourcePatternResolver.java
@@ -31,7 +31,6 @@ import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
-
/**
* A ResourcePatternResolver implementation that is able to resolve a
* specified resource location path into one or more matching Resources.
@@ -142,14 +141,13 @@ import java.util.jar.JarFile;
* @author Colin Sampaleanu
* @author Marius Bogoevici
* @author Costin Leau
- * @since 1.0.2
* @see java.lang.ClassLoader#getResources(String)
+ * @since 1.0.2
*/
public class PathMatchingResourcePatternResolver {
private static final String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
-
private final ResourceLoader resourceLoader;
private AntPathMatcher pathMatcher = new AntPathMatcher();
@@ -164,9 +162,10 @@ public class PathMatchingResourcePatternResolver {
/**
* Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.
+ *
* @param classLoader the ClassLoader to load classpath resources with,
- * or <code>null</code> for using the thread context class loader
- * at the time of actual resource access
+ * or <code>null</code> for using the thread context class loader
+ * at the time of actual resource access
*/
public PathMatchingResourcePatternResolver(ClassLoader classLoader) {
resourceLoader = new DefaultResourceLoader(classLoader);
@@ -175,8 +174,9 @@ public class PathMatchingResourcePatternResolver {
/**
* Create a new PathMatchingResourcePatternResolver.
* <p>ClassLoader access will happen via the thread context class loader.
+ *
* @param resourceLoader the ResourceLoader to load root directories and
- * actual resources with
+ * actual resources with
*/
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
@@ -234,11 +234,12 @@ public class PathMatchingResourcePatternResolver {
return findPathMatchingResources(locationPattern);
}
// a single resource with the given name
- return new Resource[] {getResourceLoader().getResource(locationPattern)};
+ return new Resource[]{getResourceLoader().getResource(locationPattern)};
}
/**
* Find all class location resources with the given location via the ClassLoader.
+ *
* @param location the absolute path within the classpath
* @return the result as Resource array
* @throws IOException in case of I/O errors
@@ -262,6 +263,7 @@ public class PathMatchingResourcePatternResolver {
/**
* Convert the given URL as returned from the ClassLoader into a Resource object.
* <p>The default implementation simply creates a UrlResource instance.
+ *
* @param url a URL as returned from the ClassLoader
* @return the corresponding Resource object
* @see java.lang.ClassLoader#getResources
@@ -274,6 +276,7 @@ public class PathMatchingResourcePatternResolver {
* Find all resources that match the given location pattern via the
* Ant-style PathMatcher. Supports resources in jar files and zip files
* and in the file system.
+ *
* @param locationPattern the location pattern to match
* @return the result as Resource array
* @throws IOException in case of I/O errors
@@ -289,8 +292,7 @@ public class PathMatchingResourcePatternResolver {
rootDirResource = resolveRootDirResource(rootDirResource);
if (isJarResource(rootDirResource)) {
result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern));
- }
- else {
+ } else {
result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
}
}
@@ -305,6 +307,7 @@ public class PathMatchingResourcePatternResolver {
* remainder of the location as pattern.
* <p>Will return "/WEB-INF/" for the pattern "/WEB-INF/*.xml",
* for example.
+ *
* @param location the location to check
* @return the part of the location that denotes the root directory
* @see #retrieveMatchingFiles
@@ -326,6 +329,7 @@ public class PathMatchingResourcePatternResolver {
* <p>The default implementation detects an Equinox OSGi "bundleresource:"
* / "bundleentry:" URL and resolves it into a standard jar file URL that
* can be traversed using Spring's standard jar file traversal algorithm.
+ *
* @param original the resource to resolve
* @return the resolved resource (may be identical to the passed-in resource)
* @throws IOException in case of resolution failure
@@ -340,8 +344,9 @@ public class PathMatchingResourcePatternResolver {
* <p>The default implementation checks against the URL protocols
* "jar", "zip" and "wsjar" (the latter are used by BEA WebLogic Server
* and IBM WebSphere, respectively, but can be treated like jar files).
+ *
* @param resource the resource handle to check
- * (usually the root directory to start path matching from)
+ * (usually the root directory to start path matching from)
* @see #doFindPathMatchingJarResources
*/
protected boolean isJarResource(Resource resource) throws IOException {
@@ -351,8 +356,9 @@ public class PathMatchingResourcePatternResolver {
/**
* Find all resources in jar files that match the given location pattern
* via the Ant-style PathMatcher.
+ *
* @param rootDirResource the root directory as Resource
- * @param subPattern the sub pattern to match (below the root directory)
+ * @param subPattern the sub pattern to match (below the root directory)
* @return the Set of matching Resource instances
* @throws IOException in case of I/O errors
* @see java.net.JarURLConnection
@@ -374,8 +380,7 @@ public class PathMatchingResourcePatternResolver {
jarFileUrl = jarCon.getJarFileURL().toExternalForm();
JarEntry jarEntry = jarCon.getJarEntry();
rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
- }
- else {
+ } 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.
@@ -386,8 +391,7 @@ public class PathMatchingResourcePatternResolver {
jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
- }
- else {
+ } else {
jarFile = new JarFile(urlFile);
jarFileUrl = urlFile;
rootEntryPath = "";
@@ -402,7 +406,7 @@ public class PathMatchingResourcePatternResolver {
rootEntryPath = rootEntryPath + "/";
}
Set<Resource> result = new LinkedHashSet<Resource>(8);
- for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
+ for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
if (entryPath.startsWith(rootEntryPath)) {
@@ -413,8 +417,7 @@ public class PathMatchingResourcePatternResolver {
}
}
return result;
- }
- finally {
+ } finally {
// Close jar file, but only if freshly obtained -
// not from JarURLConnection, which might cache the file reference.
if (newJarFile) {
@@ -430,8 +433,7 @@ public class PathMatchingResourcePatternResolver {
if (jarFileUrl.startsWith(GrailsResourceUtils.FILE_URL_PREFIX)) {
try {
return new JarFile(GrailsResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart());
- }
- catch (URISyntaxException ex) {
+ } catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new JarFile(jarFileUrl.substring(GrailsResourceUtils.FILE_URL_PREFIX.length()));
}
@@ -442,8 +444,9 @@ public class PathMatchingResourcePatternResolver {
/**
* Find all resources in the file system that match the given location pattern
* via the Ant-style PathMatcher.
+ *
* @param rootDirResource the root directory as Resource
- * @param subPattern the sub pattern to match (below the root directory)
+ * @param subPattern the sub pattern to match (below the root directory)
* @return the Set of matching Resource instances
* @throws IOException in case of I/O errors
* @see #retrieveMatchingFiles
@@ -454,8 +457,7 @@ public class PathMatchingResourcePatternResolver {
File rootDir;
try {
rootDir = rootDirResource.getFile().getAbsoluteFile();
- }
- catch (IOException ex) {
+ } catch (IOException ex) {
return Collections.emptySet();
}
return doFindMatchingFileSystemResources(rootDir, subPattern);
@@ -464,7 +466,8 @@ public class PathMatchingResourcePatternResolver {
/**
* Find all resources in the file system that match the given location pattern
* via the Ant-style PathMatcher.
- * @param rootDir the root directory in the file system
+ *
+ * @param rootDir the root directory in the file system
* @param subPattern the sub pattern to match (below the root directory)
* @return the Set of matching Resource instances
* @throws IOException in case of I/O errors
@@ -482,9 +485,10 @@ public class PathMatchingResourcePatternResolver {
/**
* Retrieve files that match the given path pattern,
* checking the given directory and its subdirectories.
+ *
* @param rootDir the directory to start from
* @param pattern the pattern to match against,
- * relative to the root directory
+ * relative to the root directory
* @return the Set of matching File instances
* @throws IOException if directory contents could not be retrieved
*/
@@ -500,7 +504,7 @@ public class PathMatchingResourcePatternResolver {
if (!rootDir.canRead()) {
return Collections.emptySet();
}
- String fullPattern = rootDir.getAbsolutePath().replace( File.separator, "/");
+ String fullPattern = rootDir.getAbsolutePath().replace(File.separator, "/");
if (!pattern.startsWith("/")) {
fullPattern += "/";
}
@@ -513,10 +517,11 @@ public class PathMatchingResourcePatternResolver {
/**
* Recursively retrieve files that match the given pattern,
* adding them to the given result list.
+ *
* @param fullPattern the pattern to match against,
- * with prepended root directory path
- * @param dir the current directory
- * @param result the Set of matching File instances to add to
+ * with prepended root directory path
+ * @param dir the current directory
+ * @param result the Set of matching File instances to add to
* @throws IOException if directory contents could not be retrieved
*/
protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
@@ -525,7 +530,7 @@ public class PathMatchingResourcePatternResolver {
return;
}
for (File content : dirContents) {
- String currPath = content.getAbsolutePath().replace( File.separator, "/");
+ String currPath = content.getAbsolutePath().replace(File.separator, "/");
if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
if (content.canRead()) {
doRetrieveMatchingFiles(fullPattern, content, result);
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.java b/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.java
index cc753ad658..6b3e4267cc 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/ResourceLocator.java
@@ -36,6 +36,7 @@ import java.util.concurrent.ConcurrentHashMap;
* @since 3.0
*/
public class ResourceLocator {
+
public static final String WILDCARD = "*";
public static final String FILE_SEPARATOR = File.separator;
public static final String CLOSURE_MARKER = "$";
@@ -48,7 +49,7 @@ public class ResourceLocator {
protected List<String> resourceSearchDirectories = new ArrayList<String>();
protected Map<String, Resource> classNameToResourceCache = new ConcurrentHashMap<String, Resource>();
protected Map<String, Resource> uriToResourceCache = new ConcurrentHashMap<String, Resource>();
- protected ResourceLoader defaultResourceLoader = new FileSystemResourceLoader();
+ protected ResourceLoader defaultResourceLoader = new FileSystemResourceLoader();
protected boolean warDeployed = Environment.isWarDeployed();
public void setSearchLocation(String searchLocation) {
@@ -100,16 +101,14 @@ public class ResourceLocator {
if (defaultResource != null && defaultResource.exists()) {
resource = defaultResource;
}
- }
- else {
+ } else {
String uriWebAppRelative = WEB_APP_DIR + uri;
for (String resourceSearchDirectory : resourceSearchDirectories) {
Resource res = resolveExceptionSafe(resourceSearchDirectory + uriWebAppRelative);
if (res.exists()) {
resource = res;
- }
- else if (!warDeployed) {
+ } else if (!warDeployed) {
Resource dir = resolveExceptionSafe(resourceSearchDirectory);
if (dir.exists() && info != null) {
String filename = dir.getFilename();
@@ -124,7 +123,6 @@ public class ResourceLocator {
}
}
-
if (resource == null || !resource.exists()) {
Resource tmp = defaultResourceLoader != null ? defaultResourceLoader.getResource(uri) : null;
if (tmp != null && tmp.exists()) {
@@ -134,15 +132,13 @@ public class ResourceLocator {
if (resource != null) {
uriToResourceCache.put(uri, resource);
- }
- else if (warDeployed) {
+ } else if (warDeployed) {
uriToResourceCache.put(uri, NULL_RESOURCE);
}
}
return resource == NULL_RESOURCE ? null : resource;
}
-
private PluginResourceInfo inferPluginNameFromURI(String uri) {
if (uri.startsWith("/plugins/")) {
String withoutPluginsPath = uri.substring("/plugins/".length(), uri.length());
@@ -173,7 +169,7 @@ public class ResourceLocator {
}
}
if (resource == null || !resource.exists()) {
- for(String ext : new String[]{".groovy", ".java"}) {
+ for (String ext : new String[]{".groovy", ".java"}) {
resource = resolveExceptionSafe(GrailsResourceUtils.DOMAIN_DIR_PATH + "**/" + className + ext);
if (resource != null && resource.exists()) {
classNameToResourceCache.put(className, resource);
@@ -214,8 +210,8 @@ public class ResourceLocator {
defaultResourceLoader = resourceLoader;
}
-
class PluginResourceInfo {
+
String pluginName;
String uri;
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.java b/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.java
index 08630df935..39f9e19ae3 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/support/StaticResourceLoader.java
@@ -18,7 +18,6 @@
*/
package org.grails.io.support;
-
/**
* Loads relative to a static base resource
*
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.java
index 83ff54b689..e6b57acde8 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/AbstractDirectoryWatcher.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch;
import java.io.File;
@@ -24,19 +23,20 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-
/**
* Backend for {@link DirectoryWatcher}
+ *
* @author Craig Andrews
- * @since 2.4
* @see WatchServiceDirectoryWatcher
* @see PollingDirectoryWatcher
* @see DirectoryWatcher
+ * @since 2.4
*/
abstract class AbstractDirectoryWatcher implements Runnable {
- private List<DirectoryWatcher.FileChangeListener> listeners = new ArrayList<DirectoryWatcher.FileChangeListener>();
- 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;
+ protected volatile boolean active = true; //must be volatile as it's read by multiple threads and the value should be reflected in all of them
+ private List<DirectoryWatcher.FileChangeListener> listeners = new ArrayList<DirectoryWatcher.FileChangeListener>();
/**
* Sets whether to stop the directory watcher
@@ -44,7 +44,7 @@ abstract class AbstractDirectoryWatcher implements Runnable {
* @param active False if you want to stop watching
*/
public void setActive(boolean active) {
- this.active = active;
+ this.active = active;
}
/**
@@ -85,7 +85,7 @@ abstract class AbstractDirectoryWatcher implements Runnable {
* Adds a directory to watch for the given file and extensions.
* No String in the fileExtensions list can start with a dot (DirectoryWatcher guarantees that)
*
- * @param dir The directory
+ * @param dir The directory
* @param fileExtensions The extensions
*/
public abstract void addWatchDirectory(File dir, List<String> fileExtensions);
@@ -102,8 +102,8 @@ abstract class AbstractDirectoryWatcher implements Runnable {
}
}
- protected boolean isValidDirectoryToMonitor(File file){
- return file.isDirectory() && ! file.isHidden() && !file.getName().startsWith(".");
+ protected boolean isValidDirectoryToMonitor(File file) {
+ return file.isDirectory() && !file.isHidden() && !file.getName().startsWith(".");
}
protected boolean isValidFileToMonitor(File file, Collection<String> fileExtensions) {
@@ -111,7 +111,7 @@ abstract class AbstractDirectoryWatcher implements Runnable {
String path = file.getAbsolutePath();
boolean isSvnFile = path.indexOf(File.separator + DirectoryWatcher.SVN_DIR_NAME + File.separator) > 0;
return !isSvnFile &&
- !file.isDirectory() &&
+ !file.isDirectory() &&
!file.isHidden() &&
!file.getName().startsWith(".") &&
(fileExtensions.contains("*") || fileExtensions.contains(getFilenameExtension(name)));
@@ -120,6 +120,7 @@ abstract class AbstractDirectoryWatcher implements Runnable {
/**
* Extract the filename extension from the given path,
* e.g. "mypath/myfile.txt" -> "txt".
+ *
* @param path the file path (may be {@code null})
* @return the extracted filename extension, or {@code null} if none
*/
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java
index 52a56dfd8d..6fc68d4459 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch;
import org.slf4j.Logger;
@@ -34,11 +33,9 @@ import java.util.List;
*/
public class DirectoryWatcher extends Thread {
- private static final Logger LOG = LoggerFactory.getLogger(DirectoryWatcher.class);
-
- private final AbstractDirectoryWatcher directoryWatcherDelegate;
-
public static final String SVN_DIR_NAME = ".svn";
+ private static final Logger LOG = LoggerFactory.getLogger(DirectoryWatcher.class);
+ private final AbstractDirectoryWatcher directoryWatcherDelegate;
/**
* Constructor. Automatically selects the best means of watching for file system changes.
@@ -47,29 +44,29 @@ public class DirectoryWatcher extends Thread {
setDaemon(true);
AbstractDirectoryWatcher directoryWatcherDelegate;
try {
- if(System.getProperty("os.name").equals("Mac OS X")) {
+ if (System.getProperty("os.name").equals("Mac OS X")) {
Boolean jnaAvailable = false;
try {
- Class.forName( "com.sun.jna.Pointer" );
+ Class.forName("com.sun.jna.Pointer");
jnaAvailable = true;
- } catch( ClassNotFoundException e ) {
- if(LOG.isWarnEnabled()) {
- LOG.warn("Error Initializing Native OS X File Event Watcher. Add JNA to classpath for Faster File Watching performance.");
+ } catch (ClassNotFoundException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Error Initializing Native OS X File Event Watcher. Add JNA to classpath for Faster File Watching performance.");
}
-
+
}
- if(jnaAvailable) {
+ if (jnaAvailable) {
directoryWatcherDelegate = (AbstractDirectoryWatcher) Class.forName("org.grails.io.watch.MacOsWatchServiceDirectoryWatcher").newInstance();
} else {
- directoryWatcherDelegate = (AbstractDirectoryWatcher) Class.forName("org.grails.io.watch.WatchServiceDirectoryWatcher").newInstance();
+ directoryWatcherDelegate = (AbstractDirectoryWatcher) Class.forName("org.grails.io.watch.WatchServiceDirectoryWatcher").newInstance();
}
} else {
- directoryWatcherDelegate = (AbstractDirectoryWatcher) Class.forName("org.grails.io.watch.WatchServiceDirectoryWatcher").newInstance();
+ directoryWatcherDelegate = (AbstractDirectoryWatcher) Class.forName("org.grails.io.watch.WatchServiceDirectoryWatcher").newInstance();
}
- } catch (Throwable e) {
- LOG.info("Exception while trying to load WatchServiceDirectoryWatcher (this is probably Java 6 and WatchService isn't available). Falling back to PollingDirectoryWatcher.", e);
- directoryWatcherDelegate = new PollingDirectoryWatcher();
- }
+ } catch (Throwable e) {
+ LOG.info("Exception while trying to load WatchServiceDirectoryWatcher (this is probably Java 6 and WatchService isn't available). Falling back to PollingDirectoryWatcher.", e);
+ directoryWatcherDelegate = new PollingDirectoryWatcher();
+ }
this.directoryWatcherDelegate = directoryWatcherDelegate;
}
@@ -79,7 +76,7 @@ public class DirectoryWatcher extends Thread {
* @param active False if you want to stop watching
*/
public void setActive(boolean active) {
- directoryWatcherDelegate.setActive(active);
+ directoryWatcherDelegate.setActive(active);
}
/**
@@ -88,7 +85,7 @@ public class DirectoryWatcher extends Thread {
* @param sleepTime The sleep time
*/
public void setSleepTime(long sleepTime) {
- directoryWatcherDelegate.setSleepTime(sleepTime);
+ directoryWatcherDelegate.setSleepTime(sleepTime);
}
/**
@@ -97,7 +94,7 @@ public class DirectoryWatcher extends Thread {
* @param listener The file listener
*/
public void addListener(FileChangeListener listener) {
- directoryWatcherDelegate.addListener(listener);
+ directoryWatcherDelegate.addListener(listener);
}
/**
@@ -115,36 +112,36 @@ public class DirectoryWatcher extends Thread {
* @param fileToWatch The file to watch
*/
public void addWatchFile(File fileToWatch) {
- directoryWatcherDelegate.addWatchFile(fileToWatch);
+ directoryWatcherDelegate.addWatchFile(fileToWatch);
}
/**
* Adds a directory to watch for the given file and extensions.
*
- * @param dir The directory
+ * @param dir The directory
* @param fileExtensions The extensions
*/
public void addWatchDirectory(File dir, List<String> fileExtensions) {
- List<String> fileExtensionsWithoutDot = new ArrayList<String>(fileExtensions.size());
- for(String fileExtension : fileExtensions){
- fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension));
- }
- directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions);
+ List<String> fileExtensionsWithoutDot = new ArrayList<String>(fileExtensions.size());
+ for (String fileExtension : fileExtensions) {
+ fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension));
+ }
+ directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions);
}
/**
- * Adds a directory to watch for the given file. All files and subdirectories in the directory will be watched.
+ * Adds a directory to watch for the given file. All files and subdirectories in the directory will be watched.
*
* @param dir The directory
*/
public void addWatchDirectory(File dir) {
- addWatchDirectory(dir, "*");
+ addWatchDirectory(dir, "*");
}
/**
* Adds a directory to watch for the given file and extensions.
*
- * @param dir The directory
+ * @param dir The directory
* @param extension The extension
*/
public void addWatchDirectory(File dir, String extension) {
@@ -152,21 +149,33 @@ public class DirectoryWatcher extends Thread {
List<String> fileExtensions = new ArrayList<String>();
if (extension != null && extension.length() > 0) {
int i = extension.lastIndexOf('.');
- if(i > -1) {
+ if (i > -1) {
extension = extension.substring(i + 1);
}
fileExtensions.add(extension);
- }
- else {
+ } else {
fileExtensions.add("*");
}
addWatchDirectory(dir, fileExtensions);
}
+ @Override
+ public void run() {
+ directoryWatcherDelegate.run();
+ }
+
+ private String removeStartingDotIfPresent(String extension) {
+ if (extension.startsWith(".")) {
+ extension = extension.substring(1);
+ }
+ return extension;
+ }
+
/**
* Interface for FileChangeListeners
*/
public static interface FileChangeListener {
+
/**
* Fired when a file changes
*
@@ -181,16 +190,4 @@ public class DirectoryWatcher extends Thread {
*/
void onNew(File file);
}
-
- @Override
- public void run() {
- directoryWatcherDelegate.run();
- }
-
- private String removeStartingDotIfPresent(String extension) {
- if (extension.startsWith(".")) {
- extension = extension.substring(1);
- }
- return extension;
- }
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/FileExtensionFileChangeListener.groovy b/grails-bootstrap/src/main/groovy/org/grails/io/watch/FileExtensionFileChangeListener.groovy
index 8e38c2cadf..47ad0fe301 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/FileExtensionFileChangeListener.groovy
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/FileExtensionFileChangeListener.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch
import groovy.transform.CompileStatic
@@ -38,7 +37,7 @@ abstract class FileExtensionFileChangeListener implements DirectoryWatcher.FileC
@Override
final void onChange(File file) {
- if(file && extensions.any() { String ext -> file.name.endsWith( ext ) } ) {
+ if (file && extensions.any() { String ext -> file.name.endsWith(ext) }) {
onChange(file, extensions)
}
}
@@ -47,7 +46,7 @@ abstract class FileExtensionFileChangeListener implements DirectoryWatcher.FileC
@Override
final void onNew(File file) {
- if(file && extensions.any() { String ext -> file.name.endsWith( ext ) } ) {
+ if (file && extensions.any() { String ext -> file.name.endsWith(ext) }) {
onNew(file, extensions)
}
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.java
index 9120c534c5..07d15fa83c 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/MacOsWatchServiceDirectoryWatcher.java
@@ -16,15 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch;
import java.nio.file.WatchEvent.Kind;
+
import io.methvin.watchservice.MacOSXListeningWatchService;
import io.methvin.watchservice.WatchablePath;
+
import static io.methvin.watcher.DirectoryChangeEvent.EventType.*;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
@@ -35,36 +38,37 @@ import java.util.concurrent.ConcurrentHashMap;
/**
* Implementation of a {@link AbstractDirectoryWatcher} that uses {@link java.nio.WatchService}.
* This implementation is used for Java 7 and later.
+ *
* @author Eric Helgeson
* @author David Estes
- * @since 3.2
* @see DirectoryWatcher
+ * @since 3.2
*/
class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher {
- private static final Logger LOG = LoggerFactory.getLogger(MacOsWatchServiceDirectoryWatcher.class);
+ private static final Logger LOG = LoggerFactory.getLogger(MacOsWatchServiceDirectoryWatcher.class);
private Map<WatchKey, List<String>> watchKeyToExtensionsMap = new ConcurrentHashMap<WatchKey, List<String>>();
private Set<Path> individualWatchedFiles = new HashSet<Path>();
- private final WatchService watchService;
+ private final WatchService watchService;
+
+ public MacOsWatchServiceDirectoryWatcher() {
+ try {
+ watchService = new MacOSXListeningWatchService();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
- return (WatchEvent<T>)event;
+ return (WatchEvent<T>) event;
}
- public MacOsWatchServiceDirectoryWatcher(){
- try {
- watchService = new MacOSXListeningWatchService();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void run() {
+ @Override
+ public void run() {
while (active) {
- try {
+ try {
WatchKey watchKey;
try {
watchKey = watchService.take();
@@ -81,17 +85,16 @@ 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(kind == StandardWatchEventKinds.ENTRY_CREATE){
+ if (individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())) {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
fireOnNew(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
+ } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
fireOnChange(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
- // do nothing... there's no way to communicate deletions
- }
- }else{
+ } // else if (kind == StandardWatchEventKinds.ENTRY_DELETE)
+ // do nothing... there's no way to communicate deletions
+ } else {
List<String> fileExtensions = watchKeyToExtensionsMap.get(watchKey);
- if(fileExtensions==null){
+ 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)
// so it must be event for a file we're not interested in. An example of how this can happen is:
@@ -102,98 +105,100 @@ class MacOsWatchServiceDirectoryWatcher extends AbstractDirectoryWatcher {
// Now, /images/b.png is changed. Because java.nio.file.WatchService watches directories, it gets a WatchEvent
// for /images/b.png. But we aren't interested in that.
LOG.debug("WatchService received an event for a file/directory that it's not interested in.");
- }else{
- if(kind==StandardWatchEventKinds.ENTRY_CREATE){
+ } else {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
// new directory created, so watch its contents
- addWatchDirectory(child,fileExtensions);
- if(childFile.isDirectory() && childFile.exists()) {
+ addWatchDirectory(child, fileExtensions);
+ if (childFile.isDirectory() && childFile.exists()) {
final File[] files = childFile.listFiles();
- if(files != null) {
+ if (files != null) {
for (File newFile : files) {
- if(isValidFileToMonitor(newFile, fileExtensions)) {
+ if (isValidFileToMonitor(newFile, fileExtensions)) {
fireOnNew(newFile);
}
}
}
}
}
- if(isValidFileToMonitor(childFile,fileExtensions)){
- if(kind == StandardWatchEventKinds.ENTRY_CREATE){
+ if (isValidFileToMonitor(childFile, fileExtensions)) {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
fireOnNew(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
+ } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
fireOnChange(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
- // do nothing... there's no way to communicate deletions
- }
+ } // else if (kind == StandardWatchEventKinds.ENTRY_DELETE)
+ // do nothing... there's no way to communicate deletions
}
}
}
}
watchKey.reset();
- } catch (Exception e) {
+ } catch (Exception e) {
LOG.error(e.toString());
// ignore
- }
+ }
}
try {
- watchService.close();
- } catch (IOException e) {
- LOG.debug("Exception while closing watchService", e);
- }
- }
+ watchService.close();
+ } catch (IOException e) {
+ LOG.debug("Exception while closing watchService", e);
+ }
+ }
- @Override
- public void addWatchFile(File fileToWatch) {
- if(!isValidFileToMonitor(fileToWatch, Arrays.asList("*"))) return;
- try {
- if(!fileToWatch.exists()) return;
- Path pathToWatch = fileToWatch.toPath().toAbsolutePath();
- individualWatchedFiles.add(pathToWatch);
+ @Override
+ public void addWatchFile(File fileToWatch) {
+ if (!isValidFileToMonitor(fileToWatch, Arrays.asList("*"))) {
+ return;
+ }
+ try {
+ if (!fileToWatch.exists()) {
+ return;
+ }
+ Path pathToWatch = fileToWatch.toPath().toAbsolutePath();
+ individualWatchedFiles.add(pathToWatch);
WatchablePath watchPath = new WatchablePath(pathToWatch);
- Kind[] events = new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY };
- watchPath.register(watchService, events);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ Kind[] events = new Kind[]{StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY};
+ watchPath.register(watchService, events);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
- @Override
- public void addWatchDirectory(File dir, final List<String> fileExtensions) {
- Path dirPath = dir.toPath();
- addWatchDirectory(dirPath, fileExtensions);
- }
+ @Override
+ public void addWatchDirectory(File dir, final List<String> fileExtensions) {
+ Path dirPath = dir.toPath();
+ addWatchDirectory(dirPath, fileExtensions);
+ }
- private void addWatchDirectory(Path dir, final List<String> fileExtensions) {
- if(!isValidDirectoryToMonitor(dir.toFile())){
- return;
- }
- try {
- //add the subdirectories too
- Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
- throws IOException
- {
- if(!isValidDirectoryToMonitor(dir.toFile())){
- return FileVisitResult.SKIP_SUBTREE;
- }
+ private void addWatchDirectory(Path dir, final List<String> fileExtensions) {
+ if (!isValidDirectoryToMonitor(dir.toFile())) {
+ return;
+ }
+ try {
+ //add the subdirectories too
+ Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+ throws IOException {
+ if (!isValidDirectoryToMonitor(dir.toFile())) {
+ return FileVisitResult.SKIP_SUBTREE;
+ }
WatchablePath watchPath = new WatchablePath(dir);
- Kind[] events = new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY };
- WatchKey watchKey = watchPath.register(watchService, events);
- final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey);
- if(originalFileExtensions==null){
- watchKeyToExtensionsMap.put(watchKey, fileExtensions);
- }else{
- final HashSet<String> newFileExtensions = new HashSet<String>(originalFileExtensions);
- newFileExtensions.addAll(fileExtensions);
- watchKeyToExtensionsMap.put(watchKey, Collections.unmodifiableList(new ArrayList(newFileExtensions)));
- }
- return FileVisitResult.CONTINUE;
- }
- });
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ Kind[] events = new Kind[]{StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY};
+ WatchKey watchKey = watchPath.register(watchService, events);
+ final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey);
+ if (originalFileExtensions == null) {
+ watchKeyToExtensionsMap.put(watchKey, fileExtensions);
+ } else {
+ final HashSet<String> newFileExtensions = new HashSet<String>(originalFileExtensions);
+ newFileExtensions.addAll(fileExtensions);
+ watchKeyToExtensionsMap.put(watchKey, Collections.unmodifiableList(new ArrayList(newFileExtensions)));
+ }
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.java
index 94090900f8..bb169aa709 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/PollingDirectoryWatcher.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch;
import java.io.File;
@@ -31,10 +30,11 @@ import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Implementation of a {@link AbstractDirectoryWatcher} that uses polling.
* This implementation is used where {@link java.nio.WatchService} isn't available (pre Java 7).
+ *
* @author Craig Andrews
- * @since 2.4
* @see WatchServiceDirectoryWatcher
* @see DirectoryWatcher
+ * @since 2.4
*/
class PollingDirectoryWatcher extends AbstractDirectoryWatcher {
@@ -44,8 +44,8 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher {
private Map<File, Collection<String>> directoryToExtensionsMap = new ConcurrentHashMap<File, Collection<String>>();
private Map<File, Long> directoryWatch = new ConcurrentHashMap<File, Long>();
- @Override
- public void run() {
+ @Override
+ public void run() {
int count = 0;
while (active) {
Set<File> files = lastModifiedMap.keySet();
@@ -68,28 +68,27 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher {
// ignore
}
}
- }
+ }
- @Override
- public void addWatchFile(File fileToWatch) {
+ @Override
+ public void addWatchFile(File fileToWatch) {
lastModifiedMap.put(fileToWatch, fileToWatch.lastModified());
- }
+ }
- @Override
- public void addWatchDirectory(File dir, List<String> fileExtensions) {
- if(!isValidDirectoryToMonitor(dir)){
- return;
- }
+ @Override
+ public void addWatchDirectory(File dir, List<String> fileExtensions) {
+ if (!isValidDirectoryToMonitor(dir)) {
+ return;
+ }
trackDirectoryExtensions(dir, fileExtensions);
cacheFilesForDirectory(dir, fileExtensions, false);
- }
+ }
private void trackDirectoryExtensions(File dir, List<String> fileExtensions) {
Collection<String> existingExtensions = directoryToExtensionsMap.get(dir);
- if(existingExtensions == null) {
+ if (existingExtensions == null) {
directoryToExtensionsMap.put(dir, new ArrayList<String>(fileExtensions));
- }
- else {
+ } else {
existingExtensions.addAll(fileExtensions);
}
}
@@ -100,7 +99,7 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher {
if (currentTimestamp < directory.lastModified()) {
Collection<String> extensions = directoryToExtensionsMap.get(directory);
- if(extensions == null) {
+ if (extensions == null) {
extensions = this.extensions;
}
cacheFilesForDirectory(directory, extensions, true);
@@ -118,10 +117,9 @@ class PollingDirectoryWatcher extends AbstractDirectoryWatcher {
}
for (File file : files) {
- if(isValidDirectoryToMonitor(file)) {
+ if (isValidDirectoryToMonitor(file)) {
cacheFilesForDirectory(file, fileExtensions, fireEvent);
- }
- else if (isValidFileToMonitor(file, fileExtensions)) {
+ } else if (isValidFileToMonitor(file, fileExtensions)) {
if (!lastModifiedMap.containsKey(file) && fireEvent) {
fireOnNew(file);
}
diff --git a/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.java b/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.java
index 60dc0bb8b9..6cb0b9eaa1 100644
--- a/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.java
+++ b/grails-bootstrap/src/main/groovy/org/grails/io/watch/WatchServiceDirectoryWatcher.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.grails.io.watch;
import java.io.File;
@@ -47,160 +46,162 @@ import org.slf4j.LoggerFactory;
/**
* Implementation of a {@link AbstractDirectoryWatcher} that uses {@link java.nio.WatchService}.
* This implementation is used for Java 7 and later.
+ *
* @author Craig Andrews
- * @since 2.4
* @see WatchServiceDirectoryWatcher
* @see DirectoryWatcher
+ * @since 2.4
*/
class WatchServiceDirectoryWatcher extends AbstractDirectoryWatcher {
- private static final Logger LOG = LoggerFactory.getLogger(WatchServiceDirectoryWatcher.class);
+ private static final Logger LOG = LoggerFactory.getLogger(WatchServiceDirectoryWatcher.class);
private Map<WatchKey, List<String>> watchKeyToExtensionsMap = new ConcurrentHashMap<WatchKey, List<String>>();
private Set<Path> individualWatchedFiles = new HashSet<Path>();
- private final WatchService watchService;
+ private final WatchService watchService;
+
+ public WatchServiceDirectoryWatcher() {
+ try {
+ watchService = FileSystems.getDefault().newWatchService();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
- return (WatchEvent<T>)event;
+ return (WatchEvent<T>) event;
}
- public WatchServiceDirectoryWatcher(){
- try {
- watchService = FileSystems.getDefault().newWatchService();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void run() {
+ @Override
+ public void run() {
while (active) {
- try {
- WatchKey watchKey = watchService.poll(sleepTime, TimeUnit.MILLISECONDS);
- if(watchKey!=null){
- List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
- for(WatchEvent<?> watchEvent : watchEvents){
- WatchEvent.Kind<?> kind = watchEvent.kind();
- if (kind == StandardWatchEventKinds.OVERFLOW) {
- // TODO how is this supposed to be handled? I think the best thing to do is ignore it, but I'm not positive
- LOG.warn("WatchService Overflow occurred");
- continue;
- }
- WatchEvent<Path> pathWatchEvent = cast(watchEvent);
- Path name = pathWatchEvent.context();
- Path dir = (Path) watchKey.watchable();
- Path child = dir.resolve(name).toAbsolutePath();
- File childFile = child.toFile();
- if(individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())){
- if(kind == StandardWatchEventKinds.ENTRY_CREATE){
- fireOnNew(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
- fireOnChange(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
- // do nothing... there's no way to communicate deletions
- }
- }else{
- List<String> fileExtensions = watchKeyToExtensionsMap.get(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)
- // so it must be event for a file we're not interested in. An example of how this can happen is:
- // there's a directory with files in it like this:
- // /images/a.png
- // /images/b.png
- // by using the addWatchFile method, /images/a.png is watched.
- // Now, /images/b.png is changed. Because java.nio.file.WatchService watches directories, it gets a WatchEvent
- // for /images/b.png. But we aren't interested in that.
- LOG.debug("WatchService received an event for a file/directory that it's not interested in.");
- }else{
- if(kind==StandardWatchEventKinds.ENTRY_CREATE){
- // new directory created, so watch its contents
- addWatchDirectory(child,fileExtensions);
- if(childFile.isDirectory() && childFile.exists()) {
- final File[] files = childFile.listFiles();
- if(files != null) {
- for (File newFile : files) {
- if(isValidFileToMonitor(newFile, fileExtensions)) {
- fireOnNew(newFile);
- }
- }
- }
- }
- }
- if(isValidFileToMonitor(childFile,fileExtensions)){
- if(kind == StandardWatchEventKinds.ENTRY_CREATE){
- fireOnNew(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
- fireOnChange(childFile);
- }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
- // do nothing... there's no way to communicate deletions
- }
- }
- }
- }
- }
- watchKey.reset();
- }
- } catch (InterruptedException e) {
- // ignore
- }
+ try {
+ WatchKey watchKey = watchService.poll(sleepTime, TimeUnit.MILLISECONDS);
+ if (watchKey != null) {
+ List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
+ for (WatchEvent<?> watchEvent : watchEvents) {
+ WatchEvent.Kind<?> kind = watchEvent.kind();
+ if (kind == StandardWatchEventKinds.OVERFLOW) {
+ // TODO how is this supposed to be handled? I think the best thing to do is ignore it, but I'm not positive
+ LOG.warn("WatchService Overflow occurred");
+ continue;
+ }
+ WatchEvent<Path> pathWatchEvent = cast(watchEvent);
+ Path name = pathWatchEvent.context();
+ Path dir = (Path) watchKey.watchable();
+ Path child = dir.resolve(name).toAbsolutePath();
+ File childFile = child.toFile();
+ if (individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())) {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
+ fireOnNew(childFile);
+ } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
+ fireOnChange(childFile);
+ } // else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
+ // do nothing... there's no way to communicate deletions
+ } else {
+ List<String> fileExtensions = watchKeyToExtensionsMap.get(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)
+ // so it must be event for a file we're not interested in. An example of how this can happen is:
+ // there's a directory with files in it like this:
+ // /images/a.png
+ // /images/b.png
+ // by using the addWatchFile method, /images/a.png is watched.
+ // Now, /images/b.png is changed. Because java.nio.file.WatchService watches directories, it gets a WatchEvent
+ // for /images/b.png. But we aren't interested in that.
+ LOG.debug("WatchService received an event for a file/directory that it's not interested in.");
+ } else {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
+ // new directory created, so watch its contents
+ addWatchDirectory(child, fileExtensions);
+ if (childFile.isDirectory() && childFile.exists()) {
+ final File[] files = childFile.listFiles();
+ if (files != null) {
+ for (File newFile : files) {
+ if (isValidFileToMonitor(newFile, fileExtensions)) {
+ fireOnNew(newFile);
+ }
+ }
+ }
+ }
+ }
+ if (isValidFileToMonitor(childFile, fileExtensions)) {
+ if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
+ fireOnNew(childFile);
+ } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
+ fireOnChange(childFile);
+ } // else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
+ // do nothing... there's no way to communicate deletions
+ }
+ }
+ }
+ }
+ watchKey.reset();
+ }
+ } catch (InterruptedException e) {
+ // ignore
+ }
}
try {
- watchService.close();
- } catch (IOException e) {
- LOG.debug("Exception while closing watchService", e);
- }
- }
+ watchService.close();
+ } catch (IOException e) {
+ LOG.debug("Exception while closing watchService", e);
+ }
+ }
- @Override
- public void addWatchFile(File fileToWatch) {
- if(!isValidFileToMonitor(fileToWatch, Arrays.asList("*"))) 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);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ @Override
+ public void addWatchFile(File fileToWatch) {
+ if (!isValidFileToMonitor(fileToWatch, Arrays.asList("*"))) {
+ 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);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
- @Override
- public void addWatchDirectory(File dir, final List<String> fileExtensions) {
- Path dirPath = dir.toPath();
- addWatchDirectory(dirPath, fileExtensions);
- }
+ @Override
+ public void addWatchDirectory(File dir, final List<String> fileExtensions) {
+ Path dirPath = dir.toPath();
+ addWatchDirectory(dirPath, fileExtensions);
+ }
- private void addWatchDirectory(Path dir, final List<String> fileExtensions) {
- if(!isValidDirectoryToMonitor(dir.toFile())){
- return;
- }
- try {
- //add the subdirectories too
- Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
- throws IOException
- {
- if(!isValidDirectoryToMonitor(dir.toFile())){
- return FileVisitResult.SKIP_SUBTREE;
- }
- WatchKey watchKey = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
- final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey);
- if(originalFileExtensions==null){
- watchKeyToExtensionsMap.put(watchKey, fileExtensions);
- }else{
- final HashSet<String> newFileExtensions = new HashSet<String>(originalFileExtensions);
- newFileExtensions.addAll(fileExtensions);
- watchKeyToExtensionsMap.put(watchKey, Collections.unmodifiableList(new ArrayList(newFileExtensions)));
- }
- return FileVisitResult.CONTINUE;
- }
- });
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ private void addWatchDirectory(Path dir, final List<String> fileExtensions) {
+ if (!isValidDirectoryToMonitor(dir.toFile())) {
+ return;
+ }
+ try {
+ //add the subdirectories too
+ Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+ throws IOException {
+ if (!isValidDirectoryToMonitor(dir.toFile())) {
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+ WatchKey watchKey = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
+ final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey);
+ if (originalFileExtensions == null) {
+ watchKeyToExtensionsMap.put(watchKey, fileExtensions);
+ } else {
+ final HashSet<String> newFileExtensions = new HashSet<String>(originalFileExtensions);
+ newFileExtensions.addAll(fileExtensions);
+ watchKeyToExtensionsMap.put(watchKey, Collections.unmodifiableList(new ArrayList(newFileExtensions)));
+ }
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/grails-cache/build.gradle b/grails-cache/build.gradle
index 2575e34f18..e4fa085e69 100644
--- a/grails-cache/build.gradle
+++ b/grails-cache/build.gradle
@@ -64,4 +64,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/grails-extension-gradle-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
diff --git a/grails-cache/grails-app/taglib/grails/plugin/cache/CacheTagLib.groovy b/grails-cache/grails-app/taglib/grails/plugin/cache/CacheTagLib.groovy
index 6d57ea3b3d..37310a2460 100644
--- a/grails-cache/grails-app/taglib/grails/plugin/cache/CacheTagLib.groovy
+++ b/grails-cache/grails-app/taglib/grails/plugin/cache/CacheTagLib.groovy
@@ -31,7 +31,6 @@ import org.springframework.web.context.request.RequestContextHolder
@Slf4j
class CacheTagLib {
-
static namespace = 'cache'
GrailsCacheManager grailsCacheManager
diff --git a/grails-cache/src/ast/groovy/grails/plugin/cache/CustomCacheKeyGenerator.groovy b/grails-cache/src/ast/groovy/grails/plugin/cache/CustomCacheKeyGenerator.groovy
index e67226f8b3..a301fca14e 100644
--- a/grails-cache/src/ast/groovy/grails/plugin/cache/CustomCacheKeyGenerator.groovy
+++ b/grails-cache/src/ast/groovy/grails/plugin/cache/CustomCacheKeyGenerator.groovy
@@ -125,7 +125,6 @@ class CustomCacheKeyGenerator implements KeyGenerator, GrailsCacheKeyGenerator {
return new TemporaryGrailsCacheKey(className, methodName, objHashCode, simpleKey)
}
-
@CompileStatic
private static class TemporaryGrailsCacheKey implements Serializable {
final String targetClassName
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
index 09fd88b450..a94ac6b604 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy
@@ -175,7 +175,6 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans
return cacheKeyVariableExpression
}
-
@Override
protected Object getAppliedMarker() {
return APPLIED_MARKER
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
index 40aa18c3ac..cbc9423320 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy
@@ -54,7 +54,6 @@ class CachePutTransformation extends AbstractCacheTransformation {
VariableExpression cacheManagerVariableExpression = varX(GRAILS_CACHE_MANAGER_PROPERTY_NAME)
BlockStatement cachingBlock = block()
-
// Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("...");
VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock)
diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
index 9f98c7c2a0..16a736ce90 100644
--- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
+++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy
@@ -81,7 +81,6 @@ class CacheableTransformation extends AbstractCacheTransformation {
// def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map)
VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock)
-
// ValueWrapper $_cache_valueWrapper = $_cache_cacheVariable.get($_cache_cacheKey);
VariableExpression cacheValueWrapper = varX(CACHE_VALUE_WRAPPER_LOCAL_VARIABLE_NAME, make(Cache.ValueWrapper))
cachingBlock.addStatement(
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/CacheException.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/CacheException.groovy
index b17b721b55..b3c0a8e6ec 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/CacheException.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/CacheException.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.plugin.cache
import groovy.transform.CompileStatic
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
index 86d57e2029..b2d4a17a61 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.plugin.cache
import grails.plugins.Plugin
@@ -53,7 +52,6 @@ class CacheGrailsPlugin extends Plugin {
customCacheKeyGenerator(CustomCacheKeyGenerator)
-
Class<? extends GrailsCacheManager> cacheClazz = GrailsConcurrentMapCacheManager
// Selects cache manager from config
if (config.getProperty("grails.cache.cacheManager", String, null) == "GrailsConcurrentLinkedMapCacheManager") {
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/CachePluginConfiguration.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/CachePluginConfiguration.groovy
index 87e800d16d..e9b632f9a8 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/CachePluginConfiguration.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/CachePluginConfiguration.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package grails.plugin.cache
import groovy.transform.CompileStatic
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCache.java b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCache.java
index da62b521c7..ca2e048b26 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCache.java
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCache.java
@@ -28,5 +28,5 @@ import org.springframework.cache.Cache;
*/
public interface GrailsCache extends Cache {
- Collection<Object> getAllKeys();
+ Collection<Object> getAllKeys();
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCacheAdminService.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCacheAdminService.groovy
index e0cb95104b..7587008e42 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCacheAdminService.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsCacheAdminService.groovy
@@ -24,20 +24,20 @@ import org.grails.plugin.cache.GrailsCacheManagerAware
@CompileStatic
class GrailsCacheAdminService implements GrailsCacheManagerAware {
- @CacheEvict(value="grailsBlocksCache", allEntries = true)
+ @CacheEvict(value = "grailsBlocksCache", allEntries = true)
void clearBlocksCache() {}
- @CacheEvict(value="grailsTemplatesCache", allEntries = true)
+ @CacheEvict(value = "grailsTemplatesCache", allEntries = true)
void clearTemplatesCache() {}
void clearCache(CharSequence cacheName) {
- if(cacheName) {
+ if (cacheName) {
grailsCacheManager.getCache(cacheName.toString())?.clear()
}
}
void clearAllCaches() {
- for(CharSequence cacheName in grailsCacheManager.cacheNames) {
+ for (CharSequence cacheName in grailsCacheManager.cacheNames) {
clearCache(cacheName)
}
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCache.java b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCache.java
index f7530e86f0..897902bf8f 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCache.java
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCache.java
@@ -31,76 +31,78 @@ import java.util.concurrent.ConcurrentMap;
*/
public class GrailsConcurrentLinkedMapCache implements GrailsCache {
- private static final Object NULL_HOLDER = new NullHolder();
- private String name;
- private long capacity;
- private final ConcurrentLinkedHashMap<Object, Object> store;
- private final boolean allowNullValues;
-
- /**
- * Create a new GrailsConcurrentLinkedMapCache with the specified name
- * and capacity
- * @param name the name of the cache
- * @param capacity of the map
- * @param allowNullValues null values (default is true)
- */
- public GrailsConcurrentLinkedMapCache(String name, long capacity, boolean allowNullValues) {
- this.name = name;
- this.capacity = capacity;
- this.allowNullValues = allowNullValues;
- // Workaround: using explicit type arguments to prevent groovydoc error (#53)
- // Replace with diamond operator once a fix for GROOVY-8628 is included in groovy dependency
- this.store = new ConcurrentLinkedHashMap.Builder<Object, Object>()
- .maximumWeightedCapacity(capacity)
- .build();
- }
-
- /**
- * Create a new GrailsConcurrentLinkedMapCache with the specified name
- * and capacity
- * @param name the name of the cache
- * @param capacity of the map
- */
- public GrailsConcurrentLinkedMapCache(String name, long capacity) {
- this(name, capacity, true);
- }
-
- public final long getCapacity() {
- return this.store.capacity();
- }
-
- @Override
- public final String getName() {
- return this.name;
- }
-
- @Override
- public final ConcurrentMap<Object, Object> getNativeCache() {
- return this.store;
- }
-
- public final int getSize() {
- return this.store.size();
- }
-
- public final boolean isAllowNullValues() {
- return this.allowNullValues;
- }
-
- @Override
- public GrailsValueWrapper get(Object key) {
- Object value = getNativeCache().get(key);
- return value == null ? null : new GrailsValueWrapper(fromStoreValue(value), null);
- }
-
- @Override
- public <T> T get(Object key, Class<T> type) {
- Object value = getNativeCache().get(key);
- if (value != null && type != null && !type.isInstance(value)) {
- throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
- }
- return (T) value;
- }
+ private static final Object NULL_HOLDER = new NullHolder();
+ private String name;
+ private long capacity;
+ private final ConcurrentLinkedHashMap<Object, Object> store;
+ private final boolean allowNullValues;
+
+ /**
+ * Create a new GrailsConcurrentLinkedMapCache with the specified name
+ * and capacity
+ *
+ * @param name the name of the cache
+ * @param capacity of the map
+ * @param allowNullValues null values (default is true)
+ */
+ public GrailsConcurrentLinkedMapCache(String name, long capacity, boolean allowNullValues) {
+ this.name = name;
+ this.capacity = capacity;
+ this.allowNullValues = allowNullValues;
+ // Workaround: using explicit type arguments to prevent groovydoc error (#53)
+ // Replace with diamond operator once a fix for GROOVY-8628 is included in groovy dependency
+ this.store = new ConcurrentLinkedHashMap.Builder<Object, Object>()
+ .maximumWeightedCapacity(capacity)
+ .build();
+ }
+
+ /**
+ * Create a new GrailsConcurrentLinkedMapCache with the specified name
+ * and capacity
+ *
+ * @param name the name of the cache
+ * @param capacity of the map
+ */
+ public GrailsConcurrentLinkedMapCache(String name, long capacity) {
+ this(name, capacity, true);
+ }
+
+ public final long getCapacity() {
+ return this.store.capacity();
+ }
+
+ @Override
+ public final String getName() {
+ return this.name;
+ }
+
+ @Override
+ public final ConcurrentMap<Object, Object> getNativeCache() {
+ return this.store;
+ }
+
+ public final int getSize() {
+ return this.store.size();
+ }
+
+ public final boolean isAllowNullValues() {
+ return this.allowNullValues;
+ }
+
+ @Override
+ public GrailsValueWrapper get(Object key) {
+ Object value = getNativeCache().get(key);
+ return value == null ? null : new GrailsValueWrapper(fromStoreValue(value), null);
+ }
+
+ @Override
+ public <T> T get(Object key, Class<T> type) {
+ Object value = getNativeCache().get(key);
+ if (value != null && type != null && !type.isInstance(value)) {
+ throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
+ }
+ return (T) value;
+ }
@Override
public <T> T get(Object key, Callable<T> valueLoader) {
@@ -108,66 +110,69 @@ public class GrailsConcurrentLinkedMapCache implements GrailsCache {
}
@SuppressWarnings("unchecked")
- public Collection<Object> getAllKeys() {
- return getNativeCache().keySet();
- }
-
- public Collection<Object> getHottestKeys() {
- return this.store.descendingKeySet();
- }
-
- @Override
- public void put(Object key, Object value) {
- this.store.put(key, toStoreValue(value));
- }
-
- public ValueWrapper putIfAbsent(Object key, Object value) {
- Object existing = this.store.putIfAbsent(key, value);
- return toWrapper(existing);
- }
-
- @Override
- public void evict(Object key) {
- this.store.remove(key);
- }
-
- @Override
- public void clear() {
- this.store.clear();
- }
-
- /**
- * Convert the given value from the internal store to a user value
- * returned from the get method (adapting {@code null}).
- * @param storeValue the store value
- * @return the value to return to the user
- */
- protected Object fromStoreValue(Object storeValue) {
- if (this.allowNullValues && storeValue == NULL_HOLDER) {
- return null;
- }
- return storeValue;
- }
-
- /**
- * Convert the given user value, as passed into the put method,
- * to a value in the internal store (adapting {@code null}).
- * @param userValue the given user value
- * @return the value to store
- */
- protected Object toStoreValue(Object userValue) {
- if (this.allowNullValues && userValue == null) {
- return NULL_HOLDER;
- }
- return userValue;
- }
-
- private ValueWrapper toWrapper(Object value) {
- return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
- }
-
- @SuppressWarnings("serial")
-
- private static class NullHolder implements Serializable {
- }
+ public Collection<Object> getAllKeys() {
+ return getNativeCache().keySet();
+ }
+
+ public Collection<Object> getHottestKeys() {
+ return this.store.descendingKeySet();
+ }
+
+ @Override
+ public void put(Object key, Object value) {
+ this.store.put(key, toStoreValue(value));
+ }
+
+ public ValueWrapper putIfAbsent(Object key, Object value) {
+ Object existing = this.store.putIfAbsent(key, value);
+ return toWrapper(existing);
+ }
+
+ @Override
+ public void evict(Object key) {
+ this.store.remove(key);
+ }
+
+ @Override
+ public void clear() {
+ this.store.clear();
+ }
+
+ /**
+ * Convert the given value from the internal store to a user value
+ * returned from the get method (adapting {@code null}).
+ *
+ * @param storeValue the store value
+ * @return the value to return to the user
+ */
+ protected Object fromStoreValue(Object storeValue) {
+ if (this.allowNullValues && storeValue == NULL_HOLDER) {
+ return null;
+ }
+ return storeValue;
+ }
+
+ /**
+ * Convert the given user value, as passed into the put method,
+ * to a value in the internal store (adapting {@code null}).
+ *
+ * @param userValue the given user value
+ * @return the value to store
+ */
+ protected Object toStoreValue(Object userValue) {
+ if (this.allowNullValues && userValue == null) {
+ return NULL_HOLDER;
+ }
+ return userValue;
+ }
+
+ private ValueWrapper toWrapper(Object value) {
+ return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
+ }
+
+ @SuppressWarnings("serial")
+
+ private static class NullHolder implements Serializable {
+
+ }
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCacheManager.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCacheManager.groovy
index ab7cc818bf..6b5b9b433d 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCacheManager.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentLinkedMapCacheManager.groovy
@@ -33,43 +33,43 @@ import java.util.concurrent.ConcurrentMap
@CompileStatic
class GrailsConcurrentLinkedMapCacheManager implements GrailsCacheManager {
- protected final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>()
+ protected final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>()
- Collection<String> getCacheNames() {
- return Collections.unmodifiableSet(cacheMap.keySet())
- }
+ Collection<String> getCacheNames() {
+ return Collections.unmodifiableSet(cacheMap.keySet())
+ }
- Cache getCache(String name) {
- return getCache(name, 10000)
- }
+ Cache getCache(String name) {
+ return getCache(name, 10000)
+ }
- Cache getCache(String name, int capacity) {
- Cache cache = cacheMap.get(name)
- if (cache == null) {
- cache = createConcurrentLinkedMapCache(name, capacity)
- Cache existing = cacheMap.putIfAbsent(name, cache)
- if (existing != null) {
- cache = existing
- }
- }
- return cache
- }
+ Cache getCache(String name, int capacity) {
+ Cache cache = cacheMap.get(name)
+ if (cache == null) {
+ cache = createConcurrentLinkedMapCache(name, capacity)
+ Cache existing = cacheMap.putIfAbsent(name, cache)
+ if (existing != null) {
+ cache = existing
+ }
+ }
+ return cache
+ }
- boolean cacheExists(String name) {
- getCacheNames().contains(name)
- }
+ boolean cacheExists(String name) {
+ getCacheNames().contains(name)
+ }
- boolean destroyCache(String name) {
- cacheMap.remove(name) != null
- }
+ boolean destroyCache(String name) {
+ cacheMap.remove(name) != null
+ }
- protected GrailsConcurrentLinkedMapCache createConcurrentLinkedMapCache(String name, long capacity) {
- return new GrailsConcurrentLinkedMapCache(name, capacity)
- }
+ protected GrailsConcurrentLinkedMapCache createConcurrentLinkedMapCache(String name, long capacity) {
+ return new GrailsConcurrentLinkedMapCache(name, capacity)
+ }
- void setConfiguration(CachePluginConfiguration configuration) {
- configuration.caches.each { String key, CachePluginConfiguration.CacheConfig value ->
- getCache(key, value.maxCapacity)
- }
- }
+ void setConfiguration(CachePluginConfiguration configuration) {
+ configuration.caches.each { String key, CachePluginConfiguration.CacheConfig value ->
+ getCache(key, value.maxCapacity)
+ }
+ }
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCache.java b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCache.java
index 67421ec98f..981290983f 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCache.java
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCache.java
@@ -34,26 +34,26 @@ import org.springframework.cache.concurrent.ConcurrentMapCache;
*/
public class GrailsConcurrentMapCache extends ConcurrentMapCache implements GrailsCache {
- public GrailsConcurrentMapCache(String name) {
- super(name);
- }
-
- public GrailsConcurrentMapCache(String name, boolean allowNullValues) {
- super(name, allowNullValues);
- }
-
- public GrailsConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) {
- super(name, store, allowNullValues);
- }
-
- @Override
- public GrailsValueWrapper get(Object key) {
- Object value = getNativeCache().get(key);
- return value == null ? null : new GrailsValueWrapper(fromStoreValue(value), null);
- }
-
- @SuppressWarnings("unchecked")
- public Collection<Object> getAllKeys() {
- return getNativeCache().keySet();
- }
+ public GrailsConcurrentMapCache(String name) {
+ super(name);
+ }
+
+ public GrailsConcurrentMapCache(String name, boolean allowNullValues) {
+ super(name, allowNullValues);
+ }
+
+ public GrailsConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) {
+ super(name, store, allowNullValues);
+ }
+
+ @Override
+ public GrailsValueWrapper get(Object key) {
+ Object value = getNativeCache().get(key);
+ return value == null ? null : new GrailsValueWrapper(fromStoreValue(value), null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Collection<Object> getAllKeys() {
+ return getNativeCache().keySet();
+ }
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCacheManager.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCacheManager.groovy
index 6a6d7a5ab9..6451055333 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCacheManager.groovy
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsConcurrentMapCacheManager.groovy
@@ -34,39 +34,39 @@ import org.springframework.cache.Cache
@CompileStatic
class GrailsConcurrentMapCacheManager implements GrailsCacheManager {
- protected final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>()
+ protected final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>()
- Collection<String> getCacheNames() {
- Collections.unmodifiableSet(cacheMap.keySet())
- }
+ Collection<String> getCacheNames() {
+ Collections.unmodifiableSet(cacheMap.keySet())
+ }
- Cache getCache(String name) {
- Cache cache = cacheMap.get(name)
- if (cache == null) {
- cache = createConcurrentMapCache(name)
- Cache existing = cacheMap.putIfAbsent(name, cache)
- if (existing != null) {
- cache = existing
- }
- }
- cache
- }
+ Cache getCache(String name) {
+ Cache cache = cacheMap.get(name)
+ if (cache == null) {
+ cache = createConcurrentMapCache(name)
+ Cache existing = cacheMap.putIfAbsent(name, cache)
+ if (existing != null) {
+ cache = existing
+ }
+ }
+ cache
+ }
- boolean cacheExists(String name) {
- getCacheNames().contains(name)
- }
+ boolean cacheExists(String name) {
+ getCacheNames().contains(name)
+ }
- boolean destroyCache(String name) {
- cacheMap.remove(name) != null
- }
+ boolean destroyCache(String name) {
+ cacheMap.remove(name) != null
+ }
- protected GrailsConcurrentMapCache createConcurrentMapCache(String name) {
- new GrailsConcurrentMapCache(name)
- }
+ protected GrailsConcurrentMapCache createConcurrentMapCache(String name) {
+ new GrailsConcurrentMapCache(name)
+ }
- void setConfiguration(CachePluginConfiguration configuration) {
- configuration.caches.each { String key, CachePluginConfiguration.CacheConfig value ->
- getCache(key)
- }
- }
+ void setConfiguration(CachePluginConfiguration configuration) {
+ configuration.caches.each { String key, CachePluginConfiguration.CacheConfig value ->
+ getCache(key)
+ }
+ }
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsValueWrapper.java b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsValueWrapper.java
index 6b74a361e6..8ff0708b91 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/GrailsValueWrapper.java
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/GrailsValueWrapper.java
@@ -27,14 +27,14 @@ import org.springframework.cache.support.SimpleValueWrapper;
*/
public class GrailsValueWrapper extends SimpleValueWrapper {
- protected Object nativeWrapper;
+ protected Object nativeWrapper;
- public GrailsValueWrapper(Object value, Object nativeWrapper) {
- super(value);
- this.nativeWrapper = nativeWrapper;
- }
+ public GrailsValueWrapper(Object value, Object nativeWrapper) {
+ super(value);
+ this.nativeWrapper = nativeWrapper;
+ }
- public Object getNativeWrapper() {
- return nativeWrapper;
- }
+ public Object getNativeWrapper() {
+ return nativeWrapper;
+ }
}
diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/util/ClassUtils.java b/grails-cache/src/main/groovy/grails/plugin/cache/util/ClassUtils.java
index 5a6df4b185..520303d213 100644
--- a/grails-cache/src/main/groovy/grails/plugin/cache/util/ClassUtils.java
+++ b/grails-cache/src/main/groovy/grails/plugin/cache/util/ClassUtils.java
@@ -35,7 +35,7 @@ public class ClassUtils {
* object using a corresponding getter method. If no getter method is found
* then this method will look for the corresponding field and return its value.
*
- * @param object object to inspect
+ * @param object object to inspect
* @param propertyOrFieldName the name of the field or property to retrieve
* @return the value of the field or property, null if neither is found
*/
diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheTagLibSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheTagLibSpec.groovy
index 3047071bd8..1d699ebb74 100644
--- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheTagLibSpec.groovy
+++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheTagLibSpec.groovy
@@ -28,7 +28,6 @@ import spock.lang.Specification
import jakarta.servlet.ServletException
-
class CacheTagLibSpec extends Specification implements TagLibUnitTest<CacheTagLib> {
GrailsCacheManager grailsCacheManager
diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheableParseSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheableParseSpec.groovy
index 99b859bdb6..7bb482dfe3 100644
--- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheableParseSpec.groovy
+++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheableParseSpec.groovy
@@ -95,13 +95,11 @@ return TestService
then:
1 * keyGenerator.generate("TestService", "multiply", _, [x:1, y:2, tenantId: "test"])
-
cleanup:
System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "")
datastore?.close()
}
-
void "test include tenant id when used with @CurrentTenant and @Transactional"() {
given:
def config = [(Settings.SETTING_MULTI_TENANCY_MODE): MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR,
@@ -141,7 +139,6 @@ return TestService
then:
1 * keyGenerator.generate("TestService", "multiply", _, [x:1, y:2, tenantId: "test"])
-
cleanup:
System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "")
datastore?.close()
diff --git a/grails-codecs-core/build.gradle b/grails-codecs-core/build.gradle
index 4fa52b2bb4..970f96a6ea 100644
--- a/grails-codecs-core/build.gradle
+++ b/grails-codecs-core/build.gradle
@@ -57,4 +57,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/DigestUtils.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/DigestUtils.groovy
index fccb6489a1..0960e45b1d 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/DigestUtils.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/DigestUtils.groovy
@@ -33,12 +33,10 @@ abstract class DigestUtils {
def src
if (data instanceof Byte[] || data instanceof byte[]) {
src = data
- }
- else if (data instanceof List || data.getClass().isArray()) {
+ } else if (data instanceof List || data.getClass().isArray()) {
src = new byte[data.size()]
data.eachWithIndex { v, i -> src[i] = v }
- }
- else {
+ } else {
src = data.toString().getBytes(StandardCharsets.UTF_8)
}
md.update(src) // This probably needs to use the thread's Locale encoding
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy
index 7dda93f99a..0944166cd1 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy
@@ -57,8 +57,7 @@ class HexCodecExtensionMethods {
str.eachWithIndex { val, idx ->
if (!(idx % 2)) {
currentByte = HEXDIGITS.indexOf(val) << 4
- }
- else {
+ } else {
output << (currentByte | HEXDIGITS.indexOf(val))
currentByte = 0
}
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5BytesCodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5BytesCodecExtensionMethods.groovy
index 4b5fdeccc6..8422367f87 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5BytesCodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5BytesCodecExtensionMethods.groovy
@@ -24,7 +24,7 @@ class MD5BytesCodecExtensionMethods {
// Returns the byte[] of the digest, taken from UTF-8 of the string representation
// or the raw data coerced to bytes
static encodeAsMD5Bytes(theTarget) {
- if(theTarget == null || theTarget instanceof NullObject) {
+ if (theTarget == null || theTarget instanceof NullObject) {
return null
}
DigestUtils.digest("MD5", theTarget)
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1BytesCodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1BytesCodecExtensionMethods.groovy
index 398dac6c9f..967db854b7 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1BytesCodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1BytesCodecExtensionMethods.groovy
@@ -23,7 +23,7 @@ import org.codehaus.groovy.runtime.NullObject
class SHA1BytesCodecExtensionMethods {
// Returns the byte[] of the digest
static encodeAsSHA1Bytes(theTarget) {
- if(theTarget == null || theTarget instanceof NullObject) {
+ if (theTarget == null || theTarget instanceof NullObject) {
return null
}
DigestUtils.digest("SHA-1", theTarget)
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1CodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1CodecExtensionMethods.groovy
index f952e00325..0eb9d8f138 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1CodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1CodecExtensionMethods.groovy
@@ -23,7 +23,7 @@ import org.codehaus.groovy.runtime.NullObject
class SHA1CodecExtensionMethods {
// Returns the byte[] of the digest
static encodeAsSHA1(theTarget) {
- if(theTarget == null || theTarget instanceof NullObject) {
+ if (theTarget == null || theTarget instanceof NullObject) {
return null
}
theTarget.encodeAsSHA1Bytes().encodeAsHex()
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256BytesCodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256BytesCodecExtensionMethods.groovy
index d3aab53f5c..05de30348d 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256BytesCodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256BytesCodecExtensionMethods.groovy
@@ -23,7 +23,7 @@ import org.codehaus.groovy.runtime.NullObject
class SHA256BytesCodecExtensionMethods {
// Returns the byte[] of the digest
static encodeAsSHA256Bytes(theTarget) {
- if(theTarget == null || theTarget instanceof NullObject) {
+ if (theTarget == null || theTarget instanceof NullObject) {
return null
}
DigestUtils.digest("SHA-256", theTarget)
diff --git a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256CodecExtensionMethods.groovy b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256CodecExtensionMethods.groovy
index a34298e1a9..1034ba090b 100644
--- a/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256CodecExtensionMethods.groovy
+++ b/grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256CodecExtensionMethods.groovy
@@ -23,7 +23,7 @@ import org.codehaus.groovy.runtime.NullObject
class SHA256CodecExtensionMethods extends DigestUtils {
// Returns the byte[] of the digest
static encodeAsSHA256(theTarget) {
- if(theTarget == null || theTarget instanceof NullObject) {
+ if (theTarget == null || theTarget instanceof NullObject) {
return null
}
theTarget.encodeAsSHA256Bytes()?.encodeAsHex()
diff --git a/grails-codecs/build.gradle b/grails-codecs/build.gradle
index a109b376ad..c8802f4b83 100644
--- a/grails-codecs/build.gradle
+++ b/grails-codecs/build.gradle
@@ -67,4 +67,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-codecs/src/main/groovy/org/grails/commons/CodecArtefactHandler.java b/grails-codecs/src/main/groovy/org/grails/commons/CodecArtefactHandler.java
index bcf4cc69ea..b34e9461e8 100644
--- a/grails-codecs/src/main/groovy/org/grails/commons/CodecArtefactHandler.java
+++ b/grails-codecs/src/main/groovy/org/grails/commons/CodecArtefactHandler.java
@@ -34,7 +34,9 @@ public class CodecArtefactHandler extends ArtefactHandlerAdapter {
@Override
public boolean isArtefactClass(@SuppressWarnings("rawtypes") Class clazz) {
- if (clazz == null) return false;
+ if (clazz == null) {
+ return false;
+ }
return clazz.getName().endsWith(DefaultGrailsCodecClass.CODEC) && !DomainClassArtefactHandler.isDomainClass(clazz);
}
diff --git a/grails-codecs/src/main/groovy/org/grails/commons/DefaultGrailsCodecClass.java b/grails-codecs/src/main/groovy/org/grails/commons/DefaultGrailsCodecClass.java
index 1e815ae11e..ed8d9e8687 100644
--- a/grails-codecs/src/main/groovy/org/grails/commons/DefaultGrailsCodecClass.java
+++ b/grails-codecs/src/main/groovy/org/grails/commons/DefaultGrailsCodecClass.java
@@ -48,10 +48,11 @@ import org.springframework.util.ReflectionUtils;
* @since 0.4
*/
public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass implements InitializingBean, GrailsCodecClass, Ordered {
+
public static final String CODEC = CodecArtefactHandler.TYPE;
+ private static int instantionCounter = 0;
private Encoder encoder;
private Decoder decoder;
- private static int instantionCounter=0;
private int order = 100 + instantionCounter++;
private boolean initialized = false;
@@ -64,7 +65,9 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
private void initializeCodec() {
- if (initialized) return;
+ if (initialized) {
+ return;
+ }
initialized = true;
Integer orderSetting = getStaticPropertyValue("order", Integer.class);
if (orderSetting != null) {
@@ -73,42 +76,42 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
Object instance = getReferenceInstance();
if (Encoder.class.isAssignableFrom(getClazz())) {
encoder = (Encoder) instance;
- encoder = (Encoder)autowireCodecBean(encoder);
+ encoder = (Encoder) autowireCodecBean(encoder);
if (encoder instanceof Ordered) {
- order = ((Ordered)encoder).getOrder();
+ order = ((Ordered) encoder).getOrder();
}
}
if (Decoder.class.isAssignableFrom(getClazz())) {
decoder = (Decoder) instance;
- decoder = (Decoder)autowireCodecBean(decoder);
+ decoder = (Decoder) autowireCodecBean(decoder);
if (decoder instanceof Ordered) {
- order = ((Ordered)decoder).getOrder();
+ order = ((Ordered) decoder).getOrder();
}
}
- if (encoder==null && decoder==null) {
- CodecFactory codecFactory=null;
+ if (encoder == null && decoder == null) {
+ CodecFactory codecFactory = null;
if (CodecFactory.class.isAssignableFrom(getClazz())) {
- codecFactory=(CodecFactory) instance;
- codecFactory=(CodecFactory)autowireCodecBean(codecFactory);
+ codecFactory = (CodecFactory) instance;
+ codecFactory = (CodecFactory) autowireCodecBean(codecFactory);
}
- if (codecFactory==null) {
- codecFactory=getStaticPropertyValue("codecFactory", CodecFactory.class);
- codecFactory=(CodecFactory)autowireCodecBean(codecFactory);
+ if (codecFactory == null) {
+ codecFactory = getStaticPropertyValue("codecFactory", CodecFactory.class);
+ codecFactory = (CodecFactory) autowireCodecBean(codecFactory);
}
- if (codecFactory==null) {
- codecFactory=new ClosureCodecFactory(instance);
+ if (codecFactory == null) {
+ codecFactory = new ClosureCodecFactory(instance);
}
- encoder=codecFactory.getEncoder();
- decoder=codecFactory.getDecoder();
+ encoder = codecFactory.getEncoder();
+ decoder = codecFactory.getDecoder();
if (codecFactory instanceof Ordered) {
- order = ((Ordered)codecFactory).getOrder();
+ order = ((Ordered) codecFactory).getOrder();
}
}
if (encoder != null) {
if (encoder instanceof StreamingEncoder) {
- encoder=new StreamingStateAwareEncoderWrapper((StreamingEncoder)encoder);
+ encoder = new StreamingStateAwareEncoderWrapper((StreamingEncoder) encoder);
} else {
- encoder=new StateAwareEncoderWrapper(encoder);
+ encoder = new StateAwareEncoderWrapper(encoder);
}
}
}
@@ -123,7 +126,28 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
return existingBean;
}
+ public Encoder getEncoder() {
+ return encoder;
+ }
+
+ public Decoder getDecoder() {
+ return decoder;
+ }
+
+ public void configureCodecMethods() {
+ // for compatibility. Not everything (especially unit tests written by existing Grails applications) call afterPropertiesSet(), but everything calls
+ // configureCodecMethods() at least once
+ initializeCodec();
+
+ new CodecMetaClassSupport().configureCodecMethods(this);
+ }
+
+ public int getOrder() {
+ return order;
+ }
+
private class ClosureCodecFactory implements CodecFactory {
+
private Encoder encoder;
private Decoder decoder;
private final Object codecInstance;
@@ -132,11 +156,11 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
this.codecInstance = codecInstance;
Closure<Object> encoderClosure = getMethodOrClosureMethod(getClazz(), "encode");
if (encoderClosure != null) {
- encoder=new ClosureEncoder(getName(), encoderClosure);
+ encoder = new ClosureEncoder(getName(), encoderClosure);
}
Closure<Object> decoderClosure = getMethodOrClosureMethod(getClazz(), "decode");
if (decoderClosure != null) {
- decoder=new ClosureDecoder(getName(), decoderClosure);
+ decoder = new ClosureDecoder(getName(), decoderClosure);
}
}
@@ -152,13 +176,13 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
@SuppressWarnings("unchecked")
Closure<Object> closure = getStaticPropertyValue(methodName, Closure.class);
if (closure == null) {
- Method method = ReflectionUtils.findMethod(clazz, methodName, (Class<?>[])null);
+ Method method = ReflectionUtils.findMethod(clazz, methodName, (Class<?>[]) null);
if (method != null) {
Object owner;
if (Modifier.isStatic(method.getModifiers())) {
- owner=clazz;
+ owner = clazz;
} else {
- owner=codecInstance;
+ owner = codecInstance;
}
return new MethodCallingClosure(owner, method);
}
@@ -170,12 +194,13 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
private static class ClosureDecoder implements Decoder {
+
private CodecIdentifier codecIdentifier;
private Closure<Object> closure;
public ClosureDecoder(String codecName, Closure<Object> closure) {
- this.codecIdentifier=new DefaultCodecIdentifier(codecName);
- this.closure=closure;
+ this.codecIdentifier = new DefaultCodecIdentifier(codecName);
+ this.closure = closure;
}
public CodecIdentifier getCodecIdentifier() {
@@ -188,10 +213,11 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
private static class StateAwareEncoderWrapper implements Encoder {
+
private Encoder delegate;
public StateAwareEncoderWrapper(Encoder delegate) {
- this.delegate=delegate;
+ this.delegate = delegate;
}
public CodecIdentifier getCodecIdentifier() {
@@ -200,18 +226,19 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
public Object encode(Object target) {
if (target instanceof Encodeable) {
- return ((Encodeable)target).encode(this);
+ return ((Encodeable) target).encode(this);
}
- EncodingStateRegistry encodingState=lookupEncodingState();
+ EncodingStateRegistry encodingState = lookupEncodingState();
if (encodingState != null && target instanceof CharSequence) {
- if (!encodingState.shouldEncodeWith(this, (CharSequence)target)) {
+ if (!encodingState.shouldEncodeWith(this, (CharSequence) target)) {
return target;
}
}
Object encoded = delegate.encode(target);
- if (encodingState != null && encoded instanceof CharSequence)
- encodingState.registerEncodedWith(this, (CharSequence)encoded);
+ if (encodingState != null && encoded instanceof CharSequence) {
+ encodingState.registerEncodedWith(this, (CharSequence) encoded);
+ }
return encoded;
}
@@ -221,7 +248,7 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
public void markEncoded(CharSequence string) {
- EncodingStateRegistry encodingState=lookupEncodingState();
+ EncodingStateRegistry encodingState = lookupEncodingState();
if (encodingState != null) {
encodingState.registerEncodedWith(this, string);
}
@@ -237,24 +264,28 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
private static class StreamingStateAwareEncoderWrapper extends StateAwareEncoderWrapper implements StreamingEncoder {
+
private StreamingEncoder delegate;
+
public StreamingStateAwareEncoderWrapper(StreamingEncoder delegate) {
super(delegate);
- this.delegate=delegate;
+ this.delegate = delegate;
}
+
public void encodeToStream(Encoder thisInstance, CharSequence source, int offset, int len, EncodedAppender appender,
- EncodingState encodingState) throws IOException {
+ EncodingState encodingState) throws IOException {
delegate.encodeToStream(this, source, offset, len, appender, encodingState);
}
}
private static class ClosureEncoder implements Encoder {
+
private CodecIdentifier codecIdentifier;
private Closure<Object> closure;
public ClosureEncoder(String codecName, Closure<Object> closure) {
- this.codecIdentifier=new DefaultCodecIdentifier(codecName);
- this.closure=closure;
+ this.codecIdentifier = new DefaultCodecIdentifier(codecName);
+ this.closure = closure;
}
public CodecIdentifier getCodecIdentifier() {
@@ -262,7 +293,9 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
public Object encode(Object target) {
- if (target==null) return null;
+ if (target == null) {
+ return null;
+ }
return closure.call(target);
}
@@ -280,6 +313,7 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
private static class MethodCallingClosure extends Closure<Object> {
+
private static final long serialVersionUID = 1L;
private Method method;
@@ -287,7 +321,7 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
super(owner);
maximumNumberOfParameters = 1;
parameterTypes = new Class[]{Object.class};
- this.method=method;
+ this.method = method;
}
protected Object callMethod(Object argument) {
@@ -300,33 +334,14 @@ public class DefaultGrailsCodecClass extends AbstractInjectableGrailsClass imple
}
protected Object doCall(Object[] args) {
- Object target=null;
- if (args != null && args.length > 0)
- target=args[0];
- if (target==null) {
+ Object target = null;
+ if (args != null && args.length > 0) {
+ target = args[0];
+ }
+ if (target == null) {
return null;
}
return callMethod(target);
}
}
-
- public Encoder getEncoder() {
- return encoder;
- }
-
- public Decoder getDecoder() {
- return decoder;
- }
-
- public void configureCodecMethods() {
- // for compatibility. Not everything (especially unit tests written by existing Grails applications) call afterPropertiesSet(), but everything calls
- // configureCodecMethods() at least once
- initializeCodec();
-
- new CodecMetaClassSupport().configureCodecMethods(this);
- }
-
- public int getOrder() {
- return order;
- }
}
diff --git a/grails-codecs/src/main/groovy/org/grails/commons/GrailsCodecClass.java b/grails-codecs/src/main/groovy/org/grails/commons/GrailsCodecClass.java
index f3456bcb67..1591be02d1 100644
--- a/grails-codecs/src/main/groovy/org/grails/commons/GrailsCodecClass.java
+++ b/grails-codecs/src/main/groovy/org/grails/commons/GrailsCodecClass.java
@@ -29,5 +29,6 @@ import org.grails.encoder.CodecFactory;
* @since 0.4
*/
public interface GrailsCodecClass extends InjectableGrailsClass, CodecFactory {
- public void configureCodecMethods();
+
+ void configureCodecMethods();
}
diff --git a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/CodecsGrailsPlugin.groovy b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/CodecsGrailsPlugin.groovy
index 403897ba7f..af29028a5e 100644
--- a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/CodecsGrailsPlugin.groovy
+++ b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/CodecsGrailsPlugin.groovy
@@ -32,6 +32,7 @@ import org.grails.encoder.impl.RawCodec
* @since 0.4
*/
class CodecsGrailsPlugin extends Plugin {
+
def version = GrailsUtil.getGrailsVersion()
def dependsOn = [core: version]
def watchedResources = "file:./grails-app/utils/**/*Codec.groovy"
diff --git a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/DefaultCodecLookup.java b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/DefaultCodecLookup.java
index 519ba504e2..22efacbeda 100644
--- a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/DefaultCodecLookup.java
+++ b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/DefaultCodecLookup.java
@@ -37,6 +37,7 @@ import org.springframework.core.OrderComparator;
* @since 2.3
*/
public class DefaultCodecLookup extends BasicCodecLookup implements GrailsApplicationAware {
+
protected ApplicationContext applicationContext;
protected GrailsApplication grailsApplication;
@@ -54,7 +55,7 @@ public class DefaultCodecLookup extends BasicCodecLookup implements GrailsApplic
Collections.sort(codecs, OrderComparator.INSTANCE);
Collections.reverse(codecs);
for (GrailsClass grailsClass : codecs) {
- registerCodec((GrailsCodecClass)grailsClass);
+ registerCodec((GrailsCodecClass) grailsClass);
}
}
diff --git a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/HTMLCodec.java b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/HTMLCodec.java
index dc1366099f..feb80df7c8 100644
--- a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/HTMLCodec.java
+++ b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/HTMLCodec.java
@@ -38,23 +38,24 @@ import org.springframework.beans.factory.InitializingBean;
* @since 1.1
*/
public final class HTMLCodec implements CodecFactory, GrailsApplicationAware, InitializingBean {
+
public static final String CONFIG_PROPERTY_GSP_HTMLCODEC = "grails.views.gsp.htmlcodec";
static final String CODEC_NAME = "HTML";
- private GrailsApplication grailsApplication;
- private Encoder encoder;
- static final Encoder xml_encoder = new HTMLEncoder();
- static final Encoder html4_encoder = new HTML4Encoder() {
+ static final Encoder XML_ENCODER = new HTMLEncoder();
+ static final Encoder HTML_4_ENCODER = new HTML4Encoder() {
@Override
public CodecIdentifier getCodecIdentifier() {
return HTMLEncoder.HTML_CODEC_IDENTIFIER;
}
};
- static final Decoder decoder = new HTML4Decoder() {
+ static final Decoder DECODER = new HTML4Decoder() {
@Override
public CodecIdentifier getCodecIdentifier() {
return HTMLEncoder.HTML_CODEC_IDENTIFIER;
}
};
+ private GrailsApplication grailsApplication;
+ private Encoder encoder;
public HTMLCodec() {
setUseLegacyEncoder(true);
@@ -65,7 +66,7 @@ public final class HTMLCodec implements CodecFactory, GrailsApplicationAware, In
}
public Decoder getDecoder() {
- return decoder;
+ return DECODER;
}
public void setGrailsApplication(GrailsApplication grailsApplication) {
@@ -89,6 +90,6 @@ public final class HTMLCodec implements CodecFactory, GrailsApplicationAware, In
}
public void setUseLegacyEncoder(boolean useLegacyEncoder) {
- encoder = useLegacyEncoder ? html4_encoder : xml_encoder;
+ encoder = useLegacyEncoder ? HTML_4_ENCODER : XML_ENCODER;
}
}
diff --git a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/URLCodec.groovy b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/URLCodec.groovy
index c25d3efd88..835443579a 100644
--- a/grails-codecs/src/main/groovy/org/grails/plugins/codecs/URLCodec.groovy
+++ b/grails-codecs/src/main/groovy/org/grails/plugins/codecs/URLCodec.groovy
@@ -28,6 +28,7 @@ import org.springframework.web.context.request.RequestContextHolder
* @since 0.5
*/
class URLCodec extends URLCodecFactory {
+
protected String resolveEncoding() {
RequestContextHolder.getRequestAttributes()?.request?.characterEncoding ?: 'UTF-8'
}
diff --git a/grails-common/build.gradle b/grails-common/build.gradle
index 3dadf85c54..66de40dc01 100644
--- a/grails-common/build.gradle
+++ b/grails-common/build.gradle
@@ -56,4 +56,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AbstractRecursiveAnnotationVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AbstractRecursiveAnnotationVisitor.java
index a810868fd4..eb9fc3fa3b 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AbstractRecursiveAnnotationVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AbstractRecursiveAnnotationVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -31,7 +34,7 @@ import org.springframework.util.ReflectionUtils;
/**
* {@link AnnotationVisitor} to recursively visit annotations.
-
+ *
* <p>Note: This class was ported to Grails 7 from Spring Framework 5.3 as it was
* removed in Spring 6 without a public replacement.
*
@@ -54,14 +57,12 @@ abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor {
@Nullable
protected final ClassLoader classLoader;
-
public AbstractRecursiveAnnotationVisitor(@Nullable ClassLoader classLoader, AnnotationAttributes attributes) {
super(SpringAsmInfo.ASM_VERSION);
this.classLoader = classLoader;
this.attributes = attributes;
}
-
@Override
public void visit(String attributeName, Object attributeValue) {
this.attributes.put(attributeName, attributeValue);
@@ -95,11 +96,9 @@ abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor {
ReflectionUtils.makeAccessible(enumConstant);
valueToUse = enumConstant.get(null);
}
- }
- catch (ClassNotFoundException | NoClassDefFoundError ex) {
+ } catch (ClassNotFoundException | NoClassDefFoundError ex) {
logger.debug("Failed to classload enum type while reading annotation metadata", ex);
- }
- catch (IllegalAccessException | AccessControlException ex) {
+ } catch (IllegalAccessException | AccessControlException ex) {
logger.debug("Could not access enum value while reading annotation metadata", ex);
}
return valueToUse;
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationAttributesReadingVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationAttributesReadingVisitor.java
index 91e4bad1d0..066888b7be 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationAttributesReadingVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationAttributesReadingVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -54,7 +57,6 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
private final Map<String, Set<String>> metaAnnotationMap;
-
public AnnotationAttributesReadingVisitor(String annotationType,
MultiValueMap<String, AnnotationAttributes> attributesMap, Map<String, Set<String>> metaAnnotationMap,
@Nullable ClassLoader classLoader) {
@@ -64,7 +66,6 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
this.metaAnnotationMap = metaAnnotationMap;
}
-
@Override
public void visitEnd() {
super.visitEnd();
@@ -74,8 +75,7 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
List<AnnotationAttributes> attributeList = this.attributesMap.get(this.annotationType);
if (attributeList == null) {
this.attributesMap.add(this.annotationType, this.attributes);
- }
- else {
+ } else {
attributeList.add(0, this.attributes);
}
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotationClass.getName())) {
@@ -94,8 +94,7 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
}
}
- }
- catch (Throwable ex) {
+ } catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to introspect meta-annotations on " + annotationClass + ": " + ex);
}
@@ -119,8 +118,7 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
for (Annotation metaMetaAnnotation : annotationType.getAnnotations()) {
recursivelyCollectMetaAnnotations(visited, metaMetaAnnotation);
}
- }
- catch (Throwable ex) {
+ } catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to introspect meta-annotations on " + annotation + ": " + ex);
}
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationMetadataReadingVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationMetadataReadingVisitor.java
index 664ba4afd2..8a89adbee6 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationMetadataReadingVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationMetadataReadingVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -68,18 +71,17 @@ public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisito
/**
* Declared as a {@link LinkedMultiValueMap} instead of a {@link MultiValueMap}
* to ensure that the hierarchical ordering of the entries is preserved.
+ *
* @see AnnotationReadingVisitorUtils#getMergedAnnotationAttributes
*/
protected final LinkedMultiValueMap<String, AnnotationAttributes> attributesMap = new LinkedMultiValueMap<>(3);
protected final Set<MethodMetadata> methodMetadataSet = new LinkedHashSet<>(4);
-
public AnnotationMetadataReadingVisitor(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
}
-
@Override
public MergedAnnotations getAnnotations() {
throw new UnsupportedOperationException();
@@ -111,7 +113,6 @@ public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisito
className, this.attributesMap, this.metaAnnotationMap, this.classLoader);
}
-
@Override
public Set<String> getAnnotationTypes() {
return this.annotationSet;
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationReadingVisitorUtils.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationReadingVisitorUtils.java
index 7b20f290af..b51fbe46b9 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationReadingVisitorUtils.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/AnnotationReadingVisitorUtils.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -62,19 +65,16 @@ abstract class AnnotationReadingVisitorUtils {
if (value instanceof AnnotationAttributes) {
value = convertClassValues(
annotatedElement, classLoader, (AnnotationAttributes) value, classValuesAsString);
- }
- else if (value instanceof AnnotationAttributes[]) {
+ } else if (value instanceof AnnotationAttributes[]) {
AnnotationAttributes[] values = (AnnotationAttributes[]) value;
for (int i = 0; i < values.length; i++) {
values[i] = convertClassValues(annotatedElement, classLoader, values[i], classValuesAsString);
}
value = values;
- }
- else if (value instanceof Type) {
+ } else if (value instanceof Type) {
value = (classValuesAsString ? ((Type) value).getClassName() :
ClassUtils.forName(((Type) value).getClassName(), classLoader));
- }
- else if (value instanceof Type[]) {
+ } else if (value instanceof Type[]) {
Type[] array = (Type[]) value;
Object[] convArray =
(classValuesAsString ? new String[array.length] : new Class<?>[array.length]);
@@ -83,12 +83,10 @@ abstract class AnnotationReadingVisitorUtils {
ClassUtils.forName(array[i].getClassName(), classLoader));
}
value = convArray;
- }
- else if (classValuesAsString) {
+ } else if (classValuesAsString) {
if (value instanceof Class) {
value = ((Class<?>) value).getName();
- }
- else if (value instanceof Class[]) {
+ } else if (value instanceof Class[]) {
Class<?>[] clazzArray = (Class<?>[]) value;
String[] newValue = new String[clazzArray.length];
for (int i = 0; i < clazzArray.length; i++) {
@@ -98,8 +96,7 @@ abstract class AnnotationReadingVisitorUtils {
}
}
entry.setValue(value);
- }
- catch (Throwable ex) {
+ } catch (Throwable ex) {
// Class not found - can't resolve class reference in annotation attribute.
result.put(entry.getKey(), ex);
}
@@ -114,12 +111,13 @@ abstract class AnnotationReadingVisitorUtils {
* <p>Annotation attribute values appearing <em>lower</em> in the annotation
* hierarchy (i.e., closer to the declaring class) will override those
* defined <em>higher</em> in the annotation hierarchy.
- * @param attributesMap the map of annotation attribute lists, keyed by
- * annotation type name
+ *
+ * @param attributesMap the map of annotation attribute lists, keyed by
+ * annotation type name
* @param metaAnnotationMap the map of meta annotation relationships,
- * keyed by annotation type name
- * @param annotationName the fully qualified class name of the annotation
- * type to look for
+ * keyed by annotation type name
+ * @param annotationName the fully qualified class name of the annotation
+ * type to look for
* @return the merged annotation attributes, or {@code null} if no
* matching annotation is present in the {@code attributesMap}
* @since 4.0.3
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/ClassMetadataReadingVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/ClassMetadataReadingVisitor.java
index c51cf9414e..a2863c09a1 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/ClassMetadataReadingVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/ClassMetadataReadingVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -73,12 +76,10 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
private Set<String> memberClassNames = new LinkedHashSet<>(4);
-
public ClassMetadataReadingVisitor() {
super(SpringAsmInfo.ASM_VERSION);
}
-
@Override
public void visit(
int version, int access, String name, String signature, @Nullable String supername, String[] interfaces) {
@@ -110,8 +111,7 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
if (this.className.equals(fqName)) {
this.enclosingClassName = fqOuterName;
this.independentInnerClass = ((access & Opcodes.ACC_STATIC) != 0);
- }
- else if (this.className.equals(fqOuterName)) {
+ } else if (this.className.equals(fqOuterName)) {
this.memberClassNames.add(fqName);
}
}
@@ -151,7 +151,6 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
// no-op
}
-
@Override
public String getClassName() {
return this.className;
@@ -209,7 +208,6 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
return StringUtils.toStringArray(this.memberClassNames);
}
-
private static class EmptyAnnotationVisitor extends AnnotationVisitor {
public EmptyAnnotationVisitor() {
@@ -227,7 +225,6 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
}
}
-
private static class EmptyMethodVisitor extends MethodVisitor {
public EmptyMethodVisitor() {
@@ -235,7 +232,6 @@ class ClassMetadataReadingVisitor extends ClassVisitor implements ClassMetadata
}
}
-
private static class EmptyFieldVisitor extends FieldVisitor {
public EmptyFieldVisitor() {
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/MethodMetadataReadingVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/MethodMetadataReadingVisitor.java
index 9e06949c6a..cbe59cb124 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/MethodMetadataReadingVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/MethodMetadataReadingVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -70,7 +73,6 @@ public class MethodMetadataReadingVisitor extends MethodVisitor implements Metho
protected final LinkedMultiValueMap<String, AnnotationAttributes> attributesMap = new LinkedMultiValueMap<>(3);
-
public MethodMetadataReadingVisitor(String methodName, int access, String declaringClassName,
String returnTypeName, @Nullable ClassLoader classLoader, Set<MethodMetadata> methodMetadataSet) {
@@ -83,7 +85,6 @@ public class MethodMetadataReadingVisitor extends MethodVisitor implements Metho
this.methodMetadataSet = methodMetadataSet;
}
-
@Override
public MergedAnnotations getAnnotations() {
throw new UnsupportedOperationException();
@@ -101,7 +102,6 @@ public class MethodMetadataReadingVisitor extends MethodVisitor implements Metho
className, this.attributesMap, this.metaAnnotationMap, this.classLoader);
}
-
@Override
public String getMethodName() {
return this.methodName;
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationArrayVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationArrayVisitor.java
index d7ee022739..e96682e611 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationArrayVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationArrayVisitor.java
@@ -1,17 +1,20 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
@@ -46,7 +49,6 @@ class RecursiveAnnotationArrayVisitor extends AbstractRecursiveAnnotationVisitor
private final List<AnnotationAttributes> allNestedAttributes = new ArrayList<>();
-
public RecursiveAnnotationArrayVisitor(
String attributeName, AnnotationAttributes attributes, @Nullable ClassLoader classLoader) {
@@ -54,15 +56,13 @@ class RecursiveAnnotationArrayVisitor extends AbstractRecursiveAnnotationVisitor
this.attributeName = attributeName;
}
-
@Override
public void visit(String attributeName, Object attributeValue) {
Object newValue = attributeValue;
Object existingValue = this.attributes.get(this.attributeName);
if (existingValue != null) {
newValue = ObjectUtils.addObjectToArray((Object[]) existingValue, newValue);
- }
- else {
+ } else {
Class<?> arrayClass = newValue.getClass();
if (Enum.class.isAssignableFrom(arrayClass)) {
while (arrayClass.getSuperclass() != null && !arrayClass.isEnum()) {
@@ -88,8 +88,7 @@ class RecursiveAnnotationArrayVisitor extends AbstractRecursiveAnnotationVisitor
public void visitEnd() {
if (!this.allNestedAttributes.isEmpty()) {
this.attributes.put(this.attributeName, this.allNestedAttributes.toArray(new AnnotationAttributes[0]));
- }
- else if (!this.attributes.containsKey(this.attributeName)) {
+ } else if (!this.attributes.containsKey(this.attributeName)) {
Class<? extends Annotation> annotationType = this.attributes.annotationType();
if (annotationType != null) {
try {
@@ -101,8 +100,7 @@ class RecursiveAnnotationArrayVisitor extends AbstractRecursiveAnnotationVisitor
}
this.attributes.put(this.attributeName, Array.newInstance(elementType, 0));
}
- }
- catch (NoSuchMethodException ex) {
+ } catch (NoSuchMethodException ex) {
// Corresponding attribute method not found: cannot expose empty array.
}
}
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationAttributesVisitor.java b/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationAttributesVisitor.java
index dc8b935d1a..ae233a0b2f 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationAttributesVisitor.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/annotation/RecursiveAnnotationAttributesVisitor.java
@@ -1,27 +1,29 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.annotation;
-import org.springframework.asm.AnnotationVisitor;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.Nullable;
/**
- * {@link AnnotationVisitor} to recursively visit annotation attributes.
+ * {@link org.springframework.asm.AnnotationVisitor} to recursively visit annotation attributes.
*
* <p>Note: This class was ported to Grails 7 from Spring Framework 5.3 as it was
* removed in Spring 6 without a public replacement.
@@ -38,7 +40,6 @@ class RecursiveAnnotationAttributesVisitor extends AbstractRecursiveAnnotationVi
protected final String annotationType;
-
public RecursiveAnnotationAttributesVisitor(
String annotationType, AnnotationAttributes attributes, @Nullable ClassLoader classLoader) {
@@ -46,7 +47,6 @@ class RecursiveAnnotationAttributesVisitor extends AbstractRecursiveAnnotationVi
this.annotationType = annotationType;
}
-
@Override
public void visitEnd() {
AnnotationUtils.registerDefaultValues(this.attributes);
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/GroovyTransformOrder.groovy b/grails-common/src/main/groovy/org/apache/grails/common/compiler/GroovyTransformOrder.groovy
index 88804912f3..9e1bf73eeb 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/GroovyTransformOrder.groovy
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/GroovyTransformOrder.groovy
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * https://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler
@@ -23,6 +25,7 @@ import groovy.transform.CompileStatic
*/
@CompileStatic
interface GroovyTransformOrder {
+
static final int HIGHEST_PRIORITY = Integer.MAX_VALUE
static final int HIGHEST_STARTING_PRIORITY = HIGHEST_PRIORITY - 1000000
static final int DECREMENT_PRIORITY = -5
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/AnnotationMetadataReader.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/AnnotationMetadataReader.java
index 98a5342bde..e7e536e02c 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/AnnotationMetadataReader.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/AnnotationMetadataReader.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * https://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
@@ -36,6 +38,7 @@ import java.io.InputStream;
* @since 3.1.13
*/
public class AnnotationMetadataReader implements MetadataReader {
+
private final Resource resource;
private final ClassMetadata classMetadata;
@@ -44,18 +47,20 @@ public class AnnotationMetadataReader implements MetadataReader {
/**
* Reads only the annotation names from a class resource
- * @param resource The resource
+ *
+ * @param resource The resource
* @param classLoader The classloader
* @throws IOException
*/
public AnnotationMetadataReader(Resource resource, ClassLoader classLoader) throws IOException {
this(resource, classLoader, false);
}
+
/**
* Constructs a new annotation metadata reader
*
- * @param resource The resource
- * @param classLoader The classloader
+ * @param resource The resource
+ * @param classLoader The classloader
* @param readAttributeValues Whether to read the attributes in addition or just the annotation class names
* @throws IOException
*/
@@ -64,22 +69,18 @@ public class AnnotationMetadataReader implements MetadataReader {
ClassReader classReader;
try {
classReader = new ClassReader(is);
- }
- catch (IllegalArgumentException ex) {
+ } catch (IllegalArgumentException ex) {
throw new IOException("ASM ClassReader failed to parse class file - " +
"probably due to a new Java class file version that isn't supported yet: " + resource, ex);
- }
- finally {
+ } finally {
is.close();
}
-
AnnotationMetadataReadingVisitor visitor;
- if(readAttributeValues) {
+ if (readAttributeValues) {
visitor = new AnnotationMetadataReadingVisitor(classLoader);
- }
- else {
+ } else {
visitor = new AnnotationMetadataReadingVisitor(classLoader) {
@Override
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) {
@@ -97,7 +98,6 @@ public class AnnotationMetadataReader implements MetadataReader {
this.resource = resource;
}
-
@Override
public Resource getResource() {
return this.resource;
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Attribute.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Attribute.java
index 356d618d19..d57befba9b 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Attribute.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Attribute.java
@@ -1,31 +1,20 @@
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2011 INRIA, France Telecom
- * All rights reserved.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
@@ -40,11 +29,6 @@ import org.springframework.asm.Label;
*/
class Attribute {
- /**
- * The type of this attribute.
- */
- public final String type;
-
/**
* The raw value of this attribute, used only for unknown attributes.
*/
@@ -55,11 +39,15 @@ class Attribute {
*/
Attribute next;
+ /**
+ * The type of this attribute.
+ */
+ private final String type;
+
/**
* Constructs a new empty attribute.
*
- * @param type
- * the type of the attribute.
+ * @param type the type of the attribute.
*/
protected Attribute(final String type) {
this.type = type;
@@ -88,7 +76,7 @@ class Attribute {
* Returns the labels corresponding to this attribute.
*
* @return the labels corresponding to this attribute, or <tt>null</tt> if
- * this attribute is not a code attribute that contains labels.
+ * this attribute is not a code attribute that contains labels.
*/
protected Label[] getLabels() {
return null;
@@ -100,63 +88,56 @@ class Attribute {
* corresponding to the <tt>len</tt> bytes starting at the given offset, in
* the given class reader.
*
- * @param cr
- * the class that contains the attribute to be read.
- * @param off
- * index of the first byte of the attribute's content in
- * {@link ClassReader#b cr.b}. The 6 attribute header bytes,
- * containing the type and the length of the attribute, are not
- * taken into account here.
- * @param len
- * the length of the attribute's content.
- * @param buf
- * buffer to be used to call {@link ClassReader#readUTF8
- * readUTF8}, {@link ClassReader#readClass(int,char[]) readClass}
- * or {@link ClassReader#readConst readConst}.
- * @param codeOff
- * index of the first byte of code's attribute content in
- * {@link ClassReader#b cr.b}, or -1 if the attribute to be read
- * is not a code attribute. The 6 attribute header bytes,
- * containing the type and the length of the attribute, are not
- * taken into account here.
- * @param labels
- * the labels of the method's code, or <tt>null</tt> if the
- * attribute to be read is not a code attribute.
+ * @param cr the class that contains the attribute to be read.
+ * @param off index of the first byte of the attribute's content in
+ * {@link ClassReader#b cr.b}. The 6 attribute header bytes,
+ * containing the type and the length of the attribute, are not
+ * taken into account here.
+ * @param len the length of the attribute's content.
+ * @param buf buffer to be used to call {@link ClassReader#readUTF8
+ * readUTF8}, {@link ClassReader#readClass(int, char[]) readClass}
+ * or {@link ClassReader#readConst readConst}.
+ * @param codeOff index of the first byte of code's attribute content in
+ * {@link ClassReader#b cr.b}, or -1 if the attribute to be read
+ * is not a code attribute. The 6 attribute header bytes,
+ * containing the type and the length of the attribute, are not
+ * taken into account here.
+ * @param labels the labels of the method's code, or <tt>null</tt> if the
+ * attribute to be read is not a code attribute.
* @return a <i>new</i> {@link Attribute} object corresponding to the given
- * bytes.
+ * bytes.
*/
protected Attribute read(final ClassReader cr, final int off,
final int len, final char[] buf, final int codeOff,
final Label[] labels) {
Attribute attr = new Attribute(type);
attr.value = new byte[len];
- System.arraycopy(cr.b, off, attr.value, 0, len);
+ System.arraycopy(cr.getB(), off, attr.value, 0, len);
return attr;
}
+ public String getType() {
+ return type;
+ }
+
/**
* Returns the byte array form of this attribute.
*
- * @param cw
- * the class to which this attribute must be added. This
- * parameter can be used to add to the constant pool of this
- * class the items that corresponds to this attribute.
- * @param code
- * the bytecode of the method corresponding to this code
- * attribute, or <tt>null</tt> if this attribute is not a code
- * attributes.
- * @param len
- * the length of the bytecode of the method corresponding to this
- * code attribute, or <tt>null</tt> if this attribute is not a
- * code attribute.
- * @param maxStack
- * the maximum stack size of the method corresponding to this
- * code attribute, or -1 if this attribute is not a code
- * attribute.
- * @param maxLocals
- * the maximum number of local variables of the method
- * corresponding to this code attribute, or -1 if this attribute
- * is not a code attribute.
+ * @param cw the class to which this attribute must be added. This
+ * parameter can be used to add to the constant pool of this
+ * class the items that corresponds to this attribute.
+ * @param code the bytecode of the method corresponding to this code
+ * attribute, or <tt>null</tt> if this attribute is not a code
+ * attributes.
+ * @param len the length of the bytecode of the method corresponding to this
+ * code attribute, or <tt>null</tt> if this attribute is not a
+ * code attribute.
+ * @param maxStack the maximum stack size of the method corresponding to this
+ * code attribute, or -1 if this attribute is not a code
+ * attribute.
+ * @param maxLocals the maximum number of local variables of the method
+ * corresponding to this code attribute, or -1 if this attribute
+ * is not a code attribute.
* @return the byte array form of this attribute.
*/
protected ByteVector write(final ClassWriter cw, final byte[] code,
@@ -185,27 +166,22 @@ class Attribute {
/**
* Returns the size of all the attributes in this attribute list.
*
- * @param cw
- * the class writer to be used to convert the attributes into
- * byte arrays, with the {@link #write write} method.
- * @param code
- * the bytecode of the method corresponding to these code
- * attributes, or <tt>null</tt> if these attributes are not code
- * attributes.
- * @param len
- * the length of the bytecode of the method corresponding to
- * these code attributes, or <tt>null</tt> if these attributes
- * are not code attributes.
- * @param maxStack
- * the maximum stack size of the method corresponding to these
- * code attributes, or -1 if these attributes are not code
- * attributes.
- * @param maxLocals
- * the maximum number of local variables of the method
- * corresponding to these code attributes, or -1 if these
- * attributes are not code attributes.
+ * @param cw the class writer to be used to convert the attributes into
+ * byte arrays, with the {@link #write write} method.
+ * @param code the bytecode of the method corresponding to these code
+ * attributes, or <tt>null</tt> if these attributes are not code
+ * attributes.
+ * @param len the length of the bytecode of the method corresponding to
+ * these code attributes, or <tt>null</tt> if these attributes
+ * are not code attributes.
+ * @param maxStack the maximum stack size of the method corresponding to these
+ * code attributes, or -1 if these attributes are not code
+ * attributes.
+ * @param maxLocals the maximum number of local variables of the method
+ * corresponding to these code attributes, or -1 if these
+ * attributes are not code attributes.
* @return the size of all the attributes in this attribute list. This size
- * includes the size of the attribute headers.
+ * includes the size of the attribute headers.
*/
final int getSize(final ClassWriter cw, final byte[] code, final int len,
final int maxStack, final int maxLocals) {
@@ -223,27 +199,21 @@ class Attribute {
* Writes all the attributes of this attribute list in the given byte
* vector.
*
- * @param cw
- * the class writer to be used to convert the attributes into
- * byte arrays, with the {@link #write write} method.
- * @param code
- * the bytecode of the method corresponding to these code
- * attributes, or <tt>null</tt> if these attributes are not code
- * attributes.
- * @param len
- * the length of the bytecode of the method corresponding to
- * these code attributes, or <tt>null</tt> if these attributes
- * are not code attributes.
- * @param maxStack
- * the maximum stack size of the method corresponding to these
- * code attributes, or -1 if these attributes are not code
- * attributes.
- * @param maxLocals
- * the maximum number of local variables of the method
- * corresponding to these code attributes, or -1 if these
- * attributes are not code attributes.
- * @param out
- * where the attributes must be written.
+ * @param cw the class writer to be used to convert the attributes into
+ * byte arrays, with the {@link #write write} method.
+ * @param code the bytecode of the method corresponding to these code
+ * attributes, or <tt>null</tt> if these attributes are not code
+ * attributes.
+ * @param len the length of the bytecode of the method corresponding to
+ * these code attributes, or <tt>null</tt> if these attributes
+ * are not code attributes.
+ * @param maxStack the maximum stack size of the method corresponding to these
+ * code attributes, or -1 if these attributes are not code
+ * attributes.
+ * @param maxLocals the maximum number of local variables of the method
+ * corresponding to these code attributes, or -1 if these
+ * attributes are not code attributes.
+ * @param out where the attributes must be written.
*/
final void put(final ClassWriter cw, final byte[] code, final int len,
final int maxStack, final int maxLocals, final ByteVector out) {
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ByteVector.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ByteVector.java
index d3f08fdb14..f035c2d74f 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ByteVector.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ByteVector.java
@@ -1,31 +1,20 @@
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2011 INRIA, France Telecom
- * All rights reserved.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
@@ -59,8 +48,7 @@ class ByteVector {
* Constructs a new {@link ByteVector ByteVector} with the given initial
* size.
*
- * @param initialSize
- * the initial size of the byte vector to be constructed.
+ * @param initialSize the initial size of the byte vector to be constructed.
*/
public ByteVector(final int initialSize) {
data = new byte[initialSize];
@@ -70,8 +58,7 @@ class ByteVector {
* Puts a byte into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
- * @param b
- * a byte.
+ * @param b a byte.
* @return this byte vector.
*/
public ByteVector putByte(final int b) {
@@ -88,10 +75,8 @@ class ByteVector {
* Puts two bytes into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
- * @param b1
- * a byte.
- * @param b2
- * another byte.
+ * @param b1 a byte.
+ * @param b2 another byte.
* @return this byte vector.
*/
ByteVector put11(final int b1, final int b2) {
@@ -110,8 +95,7 @@ class ByteVector {
* Puts a short into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
- * @param s
- * a short.
+ * @param s a short.
* @return this byte vector.
*/
public ByteVector putShort(final int s) {
@@ -130,10 +114,8 @@ class ByteVector {
* Puts a byte and a short into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
- * @param b
- * a byte.
- * @param s
- * a short.
+ * @param b a byte.
+ * @param s a short.
* @return this byte vector.
*/
ByteVector put12(final int b, final int s) {
@@ -153,8 +135,7 @@ class ByteVector {
* Puts an int into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
- * @param i
- * an int.
+ * @param i an int.
* @return this byte vector.
*/
public ByteVector putInt(final int i) {
@@ -175,8 +156,7 @@ class ByteVector {
* Puts a long into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
- * @param l
- * a long.
+ * @param l a long.
* @return this byte vector.
*/
public ByteVector putLong(final long l) {
@@ -203,8 +183,7 @@ class ByteVector {
* Puts an UTF8 string into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
- * @param s
- * a String whose UTF8 encoded length must be less than 65536.
+ * @param s a String whose UTF8 encoded length must be less than 65536.
* @return this byte vector.
*/
public ByteVector putUTF8(final String s) {
@@ -244,15 +223,12 @@ class ByteVector {
* bytes before the encoded characters, if there is space for that (i.e. if
* this.length - i - 2 >= 0).
*
- * @param s
- * the String to encode.
- * @param i
- * the index of the first character to encode. The previous
- * characters are supposed to have already been encoded, using
- * only one byte per character.
- * @param maxByteLength
- * the maximum byte length of the encoded string, including the
- * already encoded characters.
+ * @param s the String to encode.
+ * @param i the index of the first character to encode. The previous
+ * characters are supposed to have already been encoded, using
+ * only one byte per character.
+ * @param maxByteLength the maximum byte length of the encoded string, including the
+ * already encoded characters.
* @return this byte vector.
*/
ByteVector encodeUTF8(final String s, int i, int maxByteLength) {
@@ -302,13 +278,10 @@ class ByteVector {
* Puts an array of bytes into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
- * @param b
- * an array of bytes. May be <tt>null</tt> to put <tt>len</tt>
+ * @param b an array of bytes. May be <tt>null</tt> to put <tt>len</tt>
* null bytes into this byte vector.
- * @param off
- * index of the fist byte of b that must be copied.
- * @param len
- * number of bytes of b that must be copied.
+ * @param off index of the fist byte of b that must be copied.
+ * @param len number of bytes of b that must be copied.
* @return this byte vector.
*/
public ByteVector putByteArray(final byte[] b, final int off, final int len) {
@@ -325,9 +298,8 @@ class ByteVector {
/**
* Enlarge this byte vector so that it can receive n more bytes.
*
- * @param size
- * number of additional bytes that this byte vector should be
- * able to receive.
+ * @param size number of additional bytes that this byte vector should be
+ * able to receive.
*/
private void enlarge(final int size) {
int length1 = 2 * data.length;
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ClassReader.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ClassReader.java
index e7afd73883..e8fe05c607 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ClassReader.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/ClassReader.java
@@ -1,35 +1,25 @@
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2011 INRIA, France Telecom
- * All rights reserved.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
import org.springframework.asm.*;
+
import java.io.IOException;
import java.io.InputStream;
@@ -43,13 +33,22 @@ import java.io.InputStream;
* @author Eugene Kuleshov
*/
class ClassReader {
+
+ /**
+ * Flag to skip the debug information in the class. If this flag is set the
+ * debug information of the class is not visited, i.e. the
+ * {@link MethodVisitor#visitLocalVariable visitLocalVariable} and
+ * {@link MethodVisitor#visitLineNumber visitLineNumber} methods will not be
+ * called.
+ */
+ public static final int SKIP_DEBUG = 2;
+
/**
* Pseudo access flag to distinguish between the synthetic attribute and the
* synthetic access flag.
*/
static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000;
-
/**
* The type of CONSTANT_Class constant pool items.
*/
@@ -130,22 +129,18 @@ class ClassReader {
*/
static final boolean ANNOTATIONS = true;
-
- /**
- * Flag to skip the debug information in the class. If this flag is set the
- * debug information of the class is not visited, i.e. the
- * {@link MethodVisitor#visitLocalVariable visitLocalVariable} and
- * {@link MethodVisitor#visitLineNumber visitLineNumber} methods will not be
- * called.
- */
- public static final int SKIP_DEBUG = 2;
-
/**
* The class to be parsed. <i>The content of this array must not be
* modified. This field is intended for {@link Attribute} sub classes, and
* is normally not needed by class generators or adapters.</i>
*/
- public final byte[] b;
+ private final byte[] b;
+
+ /**
+ * Start index of the class header information (access, name...) in
+ * {@link #b b}.
+ */
+ private final int header;
/**
* The start index of each constant pool item in {@link #b b}, plus one. The
@@ -170,43 +165,49 @@ class ClassReader {
private final int maxStringLength;
/**
- * Start index of the class header information (access, name...) in
- * {@link #b b}.
+ * Constructs a new {@link ClassReader} object.
+ *
+ * @param b the bytecode of the class to be read.
*/
- public final int header;
+ private ClassReader(final byte[] b) {
+ this(b, 0, b.length);
+ }
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
+ /**
+ * Constructs a new {@link ClassReader} object.
+ *
+ * @param is an input stream from which to read the class.
+ * @throws IOException if a problem occurs during reading.
+ */
+ public ClassReader(final InputStream is) throws IOException {
+ this(readClass(is, false));
+ }
/**
* Constructs a new {@link ClassReader} object.
*
- * @param b
- * the bytecode of the class to be read.
+ * @param name the binary qualified name of the class to be read.
+ * @throws IOException if an exception occurs during reading.
*/
- private ClassReader(final byte[] b) {
- this(b, 0, b.length);
+ public ClassReader(final String name) throws IOException {
+ this(readClass(ClassLoader.getSystemResourceAsStream(name.replace('.', '/') + ".class"), true));
}
/**
* Constructs a new {@link ClassReader} object.
*
- * @param b
- * the bytecode of the class to be read.
- * @param off
- * the start offset of the class data.
- * @param len
- * the length of the class data.
+ * @param b the bytecode of the class to be read.
+ * @param off the start offset of the class data.
+ * @param len the length of the class data.
*/
public ClassReader(final byte[] b, final int off, final int len) {
this.b = b;
// checks the class version
- /* SPRING PATCH: REMOVED FOR FORWARD COMPATIBILITY WITH JDK 9
+ /* SPRING PATCH: REMOVED FOR FORWARD COMPATIBILITY WITH JDK 9
if (readShort(off + 6) > Opcodes.V1_8) {
throw new IllegalArgumentException();
}
- */
+ */
// parses the constant pool
items = new int[readUnsignedShort(off + 8)];
int n = items.length;
@@ -254,13 +255,20 @@ class ClassReader {
header = index;
}
+ public byte[] getB() {
+ return b;
+ }
+
+ public int getHeader() {
+ return header;
+ }
+
/**
* Returns the class's access flags (see {@link Opcodes}). This value may
* not reflect Deprecated and Synthetic flags when bytecode is before 1.5
* and those flags are represented by attributes.
*
* @return the class access flags
- *
* @see ClassVisitor#visit(int, int, String, String, String, String[])
*/
public int getAccess() {
@@ -272,7 +280,6 @@ class ClassReader {
* {@link Type#getInternalName() getInternalName}).
*
* @return the internal class name
- *
* @see ClassVisitor#visit(int, int, String, String, String, String[])
*/
public String getClassName() {
@@ -285,8 +292,7 @@ class ClassReader {
* super class is {@link Object}.
*
* @return the internal name of super class, or <tt>null</tt> for
- * {@link Object} class.
- *
+ * {@link Object} class.
* @see ClassVisitor#visit(int, int, String, String, String, String[])
*/
public String getSuperName() {
@@ -298,8 +304,7 @@ class ClassReader {
* {@link Type#getInternalName() getInternalName}).
*
* @return the array of internal names for all implemented interfaces or
- * <tt>null</tt>.
- *
+ * <tt>null</tt>.
* @see ClassVisitor#visit(int, int, String, String, String, String[])
*/
public String[] getInterfaces() {
@@ -316,49 +321,15 @@ class ClassReader {
return interfaces;
}
-
-
-
-
- /**
- * Constructs a new {@link ClassReader} object.
- *
- * @param is
- * an input stream from which to read the class.
- * @throws IOException
- * if a problem occurs during reading.
- */
- public ClassReader(final InputStream is) throws IOException {
- this(readClass(is, false));
- }
-
- /**
- * Constructs a new {@link ClassReader} object.
- *
- * @param name
- * the binary qualified name of the class to be read.
- * @throws IOException
- * if an exception occurs during reading.
- */
- public ClassReader(final String name) throws IOException {
- this(readClass(
- ClassLoader.getSystemResourceAsStream(name.replace('.', '/')
- + ".class"), true));
- }
-
/**
* Reads the bytecode of a class.
*
- * @param is
- * an input stream from which to read the class.
- * @param close
- * true to close the input stream after reading.
+ * @param is an input stream from which to read the class.
+ * @param close true to close the input stream after reading.
* @return the bytecode read from the given input stream.
- * @throws IOException
- * if a problem occurs during reading.
+ * @throws IOException if a problem occurs during reading.
*/
- private static byte[] readClass(final InputStream is, boolean close)
- throws IOException {
+ private static byte[] readClass(final InputStream is, boolean close) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
@@ -403,8 +374,7 @@ class ClassReader {
* . This class is the one specified in the constructor (see
* {@link #ClassReader(byte[]) ClassReader}).
*
- * @param classVisitor
- * the visitor that must visit this class.
+ * @param classVisitor the visitor that must visit this class.
*/
public void accept(final ClassVisitor classVisitor, final int flags) {
accept(classVisitor, new Attribute[0], flags);
@@ -415,20 +385,17 @@ class ClassReader {
* This class is the one specified in the constructor (see
* {@link #ClassReader(byte[]) ClassReader}).
*
- * @param classVisitor
- * the visitor that must visit this class.
- * @param attrs
- * prototypes of the attributes that must be parsed during the
- * visit of the class. Any attribute whose type is not equal to
- * the type of one the prototypes will not be parsed: its byte
- * array value will be passed unchanged to the ClassWriter.
- * <i>This may corrupt it if this value contains references to
- * the constant pool, or has syntactic or semantic links with a
- * class element that has been transformed by a class adapter
- * between the reader and the writer</i>.
- */
- public void accept(final ClassVisitor classVisitor,
- final Attribute[] attrs, final int flags) {
+ * @param classVisitor the visitor that must visit this class.
+ * @param attrs prototypes of the attributes that must be parsed during the
+ * visit of the class. Any attribute whose type is not equal to
+ * the type of one the prototypes will not be parsed: its byte
+ * array value will be passed unchanged to the ClassWriter.
+ * <i>This may corrupt it if this value contains references to
+ * the constant pool, or has syntactic or semantic links with a
+ * class element that has been transformed by a class adapter
+ * between the reader and the writer</i>.
+ */
+ public void accept(final ClassVisitor classVisitor, final Attribute[] attrs, final int flags) {
int u = header; // current offset in the class file
char[] c = new char[maxStringLength]; // buffer used to read strings
@@ -480,25 +447,20 @@ class ClassReader {
}
} else if (SIGNATURES && "Signature".equals(attrName)) {
signature = readUTF8(u + 8, c);
- } else if (ANNOTATIONS
- && "RuntimeVisibleAnnotations".equals(attrName)) {
+ } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) {
anns = u + 8;
- } else if (ANNOTATIONS
- && "RuntimeVisibleTypeAnnotations".equals(attrName)) {
+ } else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) {
tanns = u + 8;
} else if ("Deprecated".equals(attrName)) {
access |= Opcodes.ACC_DEPRECATED;
} else if ("Synthetic".equals(attrName)) {
- access |= Opcodes.ACC_SYNTHETIC
- | ACC_SYNTHETIC_ATTRIBUTE;
+ access |= Opcodes.ACC_SYNTHETIC | ACC_SYNTHETIC_ATTRIBUTE;
} else if ("SourceDebugExtension".equals(attrName)) {
int len = readInt(u + 4);
sourceDebug = readUTF(u + 8, len, new char[len]);
- } else if (ANNOTATIONS
- && "RuntimeInvisibleAnnotations".equals(attrName)) {
+ } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) {
ianns = u + 8;
- } else if (ANNOTATIONS
- && "RuntimeInvisibleTypeAnnotations".equals(attrName)) {
+ } else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) {
itanns = u + 8;
} else if ("BootstrapMethods".equals(attrName)) {
int[] bootstrapMethods = new int[readUnsignedShort(u + 8)];
@@ -508,8 +470,7 @@ class ClassReader {
}
context.bootstrapMethods = bootstrapMethods;
} else {
- Attribute attr = readAttribute(attrs, attrName, u + 8,
- readInt(u + 4), c, -1, null);
+ Attribute attr = readAttribute(attrs, attrName, u + 8, readInt(u + 4), c, -1, null);
if (attr != null) {
attr.next = attributes;
attributes = attr;
@@ -519,32 +480,27 @@ class ClassReader {
}
// visits the class declaration
- classVisitor.visit(readInt(items[1] - 7), access, name, signature,
- superClass, interfaces);
+ classVisitor.visit(readInt(items[1] - 7), access, name, signature, superClass, interfaces);
// visits the source and debug info
- if ((flags & SKIP_DEBUG) == 0
- && (sourceFile != null || sourceDebug != null)) {
+ if ((flags & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebug != null)) {
classVisitor.visitSource(sourceFile, sourceDebug);
}
// visits the outer class
if (enclosingOwner != null) {
- classVisitor.visitOuterClass(enclosingOwner, enclosingName,
- enclosingDesc);
+ classVisitor.visitOuterClass(enclosingOwner, enclosingName, enclosingDesc);
}
// visits the class annotations and type annotations
if (ANNOTATIONS && anns != 0) {
for (int i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) {
- v = readAnnotationValues(v + 2, c, true,
- classVisitor.visitAnnotation(readUTF8(v, c), true));
+ v = readAnnotationValues(v + 2, c, true, classVisitor.visitAnnotation(readUTF8(v, c), true));
}
}
if (ANNOTATIONS && ianns != 0) {
for (int i = readUnsignedShort(ianns), v = ianns + 2; i > 0; --i) {
- v = readAnnotationValues(v + 2, c, true,
- classVisitor.visitAnnotation(readUTF8(v, c), false));
+ v = readAnnotationValues(v + 2, c, true, classVisitor.visitAnnotation(readUTF8(v, c), false));
}
}
@@ -555,22 +511,17 @@ class ClassReader {
/**
* Reads the values of an annotation and makes the given visitor visit them.
*
- * @param v
- * the start offset in {@link #b b} of the values to be read
- * (including the unsigned short that gives the number of
- * values).
- * @param buf
- * buffer to be used to call {@link #readUTF8 readUTF8},
- * {@link #readClass(int,char[]) readClass} or {@link #readConst
- * readConst}.
- * @param named
- * if the annotation values are named or not.
- * @param av
- * the visitor that must visit the values.
+ * @param v the start offset in {@link #b b} of the values to be read
+ * (including the unsigned short that gives the number of
+ * values).
+ * @param buf buffer to be used to call {@link #readUTF8 readUTF8},
+ * {@link #readClass(int, char[]) readClass} or {@link #readConst
+ * readConst}.
+ * @param named if the annotation values are named or not.
+ * @param av the visitor that must visit the values.
* @return the end offset of the annotation values.
*/
- private int readAnnotationValues(int v, final char[] buf,
- final boolean named, final AnnotationVisitor av) {
+ private int readAnnotationValues(int v, final char[] buf, final boolean named, final AnnotationVisitor av) {
int i = readUnsignedShort(v);
v += 2;
if (named) {
@@ -591,21 +542,16 @@ class ClassReader {
/**
* Reads a value of an annotation and makes the given visitor visit it.
*
- * @param v
- * the start offset in {@link #b b} of the value to be read
- * (<i>not including the value name constant pool index</i>).
- * @param buf
- * buffer to be used to call {@link #readUTF8 readUTF8},
- * {@link #readClass(int,char[]) readClass} or {@link #readConst
- * readConst}.
- * @param name
- * the name of the value to be read.
- * @param av
- * the visitor that must visit the value.
+ * @param v the start offset in {@link #b b} of the value to be read
+ * (<i>not including the value name constant pool index</i>).
+ * @param buf buffer to be used to call {@link #readUTF8 readUTF8},
+ * {@link #readClass(int, char[]) readClass} or {@link #readConst
+ * readConst}.
+ * @param name the name of the value to be read.
+ * @param av the visitor that must visit the value.
* @return the end offset of the annotation value.
*/
- private int readAnnotationValue(int v, final char[] buf, final String name,
- final AnnotationVisitor av) {
+ private int readAnnotationValue(int v, final char[] buf, final String name, final AnnotationVisitor av) {
int i;
if (av == null) {
switch (b[v] & 0xFF) {
@@ -656,15 +602,13 @@ class ClassReader {
v += 2;
break;
case '@': // annotation_value
- v = readAnnotationValues(v + 2, buf, true,
- av.visitAnnotation(name, readUTF8(v, buf)));
+ v = readAnnotationValues(v + 2, buf, true, av.visitAnnotation(name, readUTF8(v, buf)));
break;
case '[': // array_value
int size = readUnsignedShort(v);
v += 2;
if (size == 0) {
- return readAnnotationValues(v - 2, buf, false,
- av.visitArray(name));
+ return readAnnotationValues(v - 2, buf, false, av.visitArray(name));
}
switch (this.b[v++] & 0xFF) {
case 'B':
@@ -724,8 +668,7 @@ class ClassReader {
case 'F':
float[] fv = new float[size];
for (i = 0; i < size; i++) {
- fv[i] = Float
- .intBitsToFloat(readInt(items[readUnsignedShort(v)]));
+ fv[i] = Float.intBitsToFloat(readInt(items[readUnsignedShort(v)]));
v += 3;
}
av.visit(name, fv);
@@ -734,8 +677,7 @@ class ClassReader {
case 'D':
double[] dv = new double[size];
for (i = 0; i < size; i++) {
- dv[i] = Double
- .longBitsToDouble(readLong(items[readUnsignedShort(v)]));
+ dv[i] = Double.longBitsToDouble(readLong(items[readUnsignedShort(v)]));
v += 3;
}
av.visit(name, dv);
@@ -744,22 +686,22 @@ class ClassReader {
default:
v = readAnnotationValues(v - 3, buf, false, av.visitArray(name));
}
+ default:
+ // do nothing
+ break;
}
return v;
}
-
/**
* Returns the label corresponding to the given offset. The default
* implementation of this method creates a label for the given offset if it
* has not been already created.
*
- * @param offset
- * a bytecode offset in a method.
- * @param labels
- * the already created labels, indexed by their offset. If a
- * label already exists for offset this method must not create a
- * new one. Otherwise it must store the new label in this array.
+ * @param offset a bytecode offset in a method.
+ * @param labels the already created labels, indexed by their offset. If a
+ * label already exists for offset this method must not create a
+ * new one. Otherwise it must store the new label in this array.
* @return a non null Label, which must be equal to labels[offset].
*/
protected Label readLabel(int offset, Label[] labels) {
@@ -803,55 +745,44 @@ class ClassReader {
/**
* Reads an attribute in {@link #b b}.
*
- * @param attrs
- * prototypes of the attributes that must be parsed during the
- * visit of the class. Any attribute whose type is not equal to
- * the type of one the prototypes is ignored (i.e. an empty
- * {@link Attribute} instance is returned).
- * @param type
- * the type of the attribute.
- * @param off
- * index of the first byte of the attribute's content in
- * {@link #b b}. The 6 attribute header bytes, containing the
- * type and the length of the attribute, are not taken into
- * account here (they have already been read).
- * @param len
- * the length of the attribute's content.
- * @param buf
- * buffer to be used to call {@link #readUTF8 readUTF8},
- * {@link #readClass(int,char[]) readClass} or {@link #readConst
- * readConst}.
- * @param codeOff
- * index of the first byte of code's attribute content in
- * {@link #b b}, or -1 if the attribute to be read is not a code
- * attribute. The 6 attribute header bytes, containing the type
- * and the length of the attribute, are not taken into account
- * here.
- * @param labels
- * the labels of the method's code, or <tt>null</tt> if the
- * attribute to be read is not a code attribute.
+ * @param attrs prototypes of the attributes that must be parsed during the
+ * visit of the class. Any attribute whose type is not equal to
+ * the type of one the prototypes is ignored (i.e. an empty
+ * {@link Attribute} instance is returned).
+ * @param type the type of the attribute.
+ * @param off index of the first byte of the attribute's content in
+ * {@link #b b}. The 6 attribute header bytes, containing the
+ * type and the length of the attribute, are not taken into
+ * account here (they have already been read).
+ * @param len the length of the attribute's content.
+ * @param buf buffer to be used to call {@link #readUTF8 readUTF8},
+ * {@link #readClass(int, char[]) readClass} or {@link #readConst
+ * readConst}.
+ * @param codeOff index of the first byte of code's attribute content in
+ * {@link #b b}, or -1 if the attribute to be read is not a code
+ * attribute. The 6 attribute header bytes, containing the type
+ * and the length of the attribute, are not taken into account
+ * here.
+ * @param labels the labels of the method's code, or <tt>null</tt> if the
+ * attribute to be read is not a code attribute.
* @return the attribute that has been read, or <tt>null</tt> to skip this
- * attribute.
+ * attribute.
*/
- private Attribute readAttribute(final Attribute[] attrs, final String type,
- final int off, final int len, final char[] buf, final int codeOff,
- final Label[] labels) {
+ private Attribute readAttribute(final Attribute[] attrs, final String type, final int off, final int len, final char[] buf, final int codeOff, final Label[] labels) {
for (int i = 0; i < attrs.length; ++i) {
- if (attrs[i].type.equals(type)) {
+ if (attrs[i].getType().equals(type)) {
return attrs[i].read(this, off, len, buf, codeOff, labels);
}
}
return new Attribute(type).read(this, off, len, null, -1, null);
}
-
/**
* Reads a byte value in {@link #b b}. <i>This method is intended for
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
- * @param index
- * the start index of the value to be read in {@link #b b}.
+ * @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readByte(final int index) {
@@ -863,8 +794,7 @@ class ClassReader {
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
- * @param index
- * the start index of the value to be read in {@link #b b}.
+ * @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readUnsignedShort(final int index) {
@@ -877,8 +807,7 @@ class ClassReader {
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
- * @param index
- * the start index of the value to be read in {@link #b b}.
+ * @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public short readShort(final int index) {
@@ -891,14 +820,12 @@ class ClassReader {
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
- * @param index
- * the start index of the value to be read in {@link #b b}.
+ * @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readInt(final int index) {
byte[] b = this.b;
- return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
- | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
+ return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
}
/**
@@ -906,8 +833,7 @@ class ClassReader {
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
- * @param index
- * the start index of the value to be read in {@link #b b}.
+ * @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public long readLong(final int index) {
@@ -921,12 +847,10 @@ class ClassReader {
* is intended for {@link Attribute} sub classes, and is normally not needed
* by class generators or adapters.</i>
*
- * @param index
- * the start index of an unsigned short value in {@link #b b},
- * whose value is the index of an UTF8 constant pool item.
- * @param buf
- * buffer to be used to read the item. This buffer must be
- * sufficiently large. It is not automatically resized.
+ * @param index the start index of an unsigned short value in {@link #b b},
+ * whose value is the index of an UTF8 constant pool item.
+ * @param buf buffer to be used to read the item. This buffer must be
+ * sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 item.
*/
public String readUTF8(int index, final char[] buf) {
@@ -939,19 +863,18 @@ class ClassReader {
return s;
}
index = items[item];
- return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf);
+ String utf8Item = readUTF(index + 2, readUnsignedShort(index), buf);
+ strings[item] = utf8Item;
+ return utf8Item;
}
/**
* Reads UTF8 string in {@link #b b}.
*
- * @param index
- * start offset of the UTF8 string to be read.
- * @param utfLen
- * length of the UTF8 string to be read.
- * @param buf
- * buffer to be used to read the string. This buffer must be
- * sufficiently large. It is not automatically resized.
+ * @param index start offset of the UTF8 string to be read.
+ * @param utfLen length of the UTF8 string to be read.
+ * @param buf buffer to be used to read the string. This buffer must be
+ * sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 string.
*/
private String readUTF(int index, final int utfLen, final char[] buf) {
@@ -986,6 +909,10 @@ class ClassReader {
cc = (char) ((cc << 6) | (c & 0x3F));
st = 1;
break;
+
+ default:
+ // do nothing
+ break;
}
}
return new String(buf, 0, strLen);
@@ -996,12 +923,10 @@ class ClassReader {
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
- * @param index
- * the start index of an unsigned short value in {@link #b b},
- * whose value is the index of a class constant pool item.
- * @param buf
- * buffer to be used to read the item. This buffer must be
- * sufficiently large. It is not automatically resized.
+ * @param index the start index of an unsigned short value in {@link #b b},
+ * whose value is the index of a class constant pool item.
+ * @param buf buffer to be used to read the item. This buffer must be
+ * sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified class item.
*/
public String readClass(final int index, final char[] buf) {
@@ -1016,14 +941,12 @@ class ClassReader {
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
- * @param item
- * the index of a constant pool item.
- * @param buf
- * buffer to be used to read the item. This buffer must be
- * sufficiently large. It is not automatically resized.
+ * @param item the index of a constant pool item.
+ * @param buf buffer to be used to read the item. This buffer must be
+ * sufficiently large. It is not automatically resized.
* @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double},
- * {@link String}, {@link Type} or {@link Handle} corresponding to
- * the given constant pool item.
+ * {@link String}, {@link Type} or {@link Handle} corresponding to
+ * the given constant pool item.
*/
public Object readConst(final int item, final char[] buf) {
int index = items[item];
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Context.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Context.java
index 2ad9692aa0..004cb36c04 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Context.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/Context.java
@@ -1,31 +1,20 @@
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2011 INRIA, France Telecom
- * All rights reserved.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
@@ -143,4 +132,4 @@ class Context {
* The stack values of the latest stack map frame that has been parsed.
*/
Object[] stack;
-}
\ No newline at end of file
+}
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/TypePath.java b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/TypePath.java
index f2510b12aa..5c71a2f702 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/TypePath.java
+++ b/grails-common/src/main/groovy/org/apache/grails/common/compiler/asm/TypePath.java
@@ -1,35 +1,23 @@
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2011 INRIA, France Telecom
- * All rights reserved.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.compiler.asm;
-
/**
* The path to a type argument, wildcard bound, array element type, or static
* inner type within an enclosing type.
@@ -42,25 +30,25 @@ class TypePath {
* A type path step that steps into the element type of an array type. See
* {@link #getStep getStep}.
*/
- public final static int ARRAY_ELEMENT = 0;
+ public static final int ARRAY_ELEMENT = 0;
/**
* A type path step that steps into the nested type of a class type. See
* {@link #getStep getStep}.
*/
- public final static int INNER_TYPE = 1;
+ public static final int INNER_TYPE = 1;
/**
* A type path step that steps into the bound of a wildcard type. See
* {@link #getStep getStep}.
*/
- public final static int WILDCARD_BOUND = 2;
+ public static final int WILDCARD_BOUND = 2;
/**
* A type path step that steps into a type argument of a generic type. See
* {@link #getStep getStep}.
*/
- public final static int TYPE_ARGUMENT = 3;
+ public static final int TYPE_ARGUMENT = 3;
/**
* The byte array where the path is stored, in Java class file format.
@@ -75,11 +63,9 @@ class TypePath {
/**
* Creates a new type path.
*
- * @param b
- * the byte array containing the type path in Java class file
- * format.
- * @param offset
- * the offset of the first byte of the type path in 'b'.
+ * @param b the byte array containing the type path in Java class file
+ * format.
+ * @param offset the offset of the first byte of the type path in 'b'.
*/
TypePath(byte[] b, int offset) {
this.b = b;
@@ -98,11 +84,10 @@ class TypePath {
/**
* Returns the value of the given step of this path.
*
- * @param index
- * an index between 0 and {@link #getLength()}, exclusive.
+ * @param index an index between 0 and {@link #getLength()}, exclusive.
* @return {@link #ARRAY_ELEMENT ARRAY_ELEMENT}, {@link #INNER_TYPE
- * INNER_TYPE}, {@link #WILDCARD_BOUND WILDCARD_BOUND}, or
- * {@link #TYPE_ARGUMENT TYPE_ARGUMENT}.
+ * INNER_TYPE}, {@link #WILDCARD_BOUND WILDCARD_BOUND}, or
+ * {@link #TYPE_ARGUMENT TYPE_ARGUMENT}.
*/
public int getStep(int index) {
return b[offset + 2 * index + 1];
@@ -113,10 +98,9 @@ class TypePath {
* into. This method should only be used for steps whose value is
* {@link #TYPE_ARGUMENT TYPE_ARGUMENT}.
*
- * @param index
- * an index between 0 and {@link #getLength()}, exclusive.
+ * @param index an index between 0 and {@link #getLength()}, exclusive.
* @return the index of the type argument that the given step is stepping
- * into.
+ * into.
*/
public int getStepArgument(int index) {
return b[offset + 2 * index + 2];
@@ -126,9 +110,8 @@ class TypePath {
* Converts a type path in string form, in the format used by
* {@link #toString()}, into a TypePath object.
*
- * @param typePath
- * a type path in string form, in the format used by
- * {@link #toString()}. May be null or empty.
+ * @param typePath a type path in string form, in the format used by
+ * {@link #toString()}. May be null or empty.
* @return the corresponding TypePath object, or null if the path is empty.
*/
public static TypePath fromString(final String typePath) {
@@ -138,7 +121,7 @@ class TypePath {
int n = typePath.length();
ByteVector out = new ByteVector(n);
out.putByte(0);
- for (int i = 0; i < n;) {
+ for (int i = 0; i < n; ) {
char c = typePath.charAt(i++);
if (c == '[') {
out.put11(ARRAY_ELEMENT, 0);
diff --git a/grails-common/src/main/groovy/org/apache/grails/common/properties/PropertyFileUtils.groovy b/grails-common/src/main/groovy/org/apache/grails/common/properties/PropertyFileUtils.groovy
index 24a0fb7f1d..deeb3fa277 100644
--- a/grails-common/src/main/groovy/org/apache/grails/common/properties/PropertyFileUtils.groovy
+++ b/grails-common/src/main/groovy/org/apache/grails/common/properties/PropertyFileUtils.groovy
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * https://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.grails.common.properties
diff --git a/grails-console/build.gradle b/grails-console/build.gradle
index e2d0cc792d..49191ea869 100644
--- a/grails-console/build.gradle
+++ b/grails-console/build.gradle
@@ -69,4 +69,5 @@ apply {
from rootProject.layout.projectDirectory.file('gradle/java-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/publish-config.gradle')
+ from rootProject.layout.projectDirectory.file('gradle/style-enforcement-config.gradle')
}
\ No newline at end of file
diff --git a/grails-console/src/main/groovy/grails/ui/command/GrailsApplicationContextCommandRunner.groovy b/grails-console/src/main/groovy/grails/ui/command/GrailsApplicationContextCommandRunner.groovy
index 7f28f5024a..353e881e81 100644
--- a/grails-console/src/main/groovy/grails/ui/command/GrailsApplicationContextCommandRunner.groovy
+++ b/grails-console/src/main/groovy/grails/ui/command/GrailsApplicationContextCommandRunner.groovy
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * https://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package grails.ui.command
@@ -26,7 +28,6 @@ import org.grails.build.parsing.CommandLineParser
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.context.ConfigurableApplicationContext
-
/**
* @author Graeme Rocher
* @since 3.0
@@ -89,7 +90,7 @@ class GrailsApplicationContextCommandRunner extends DevelopmentGrailsApplication
*
* @param args The first argument is the Command name, the last argument is the Application class name
*/
- public static void main(String[] args) {
+ static void main(String[] args) {
if(args.size() > 1) {
Class applicationClass = null
String className = args.last()
diff --git a/grails-console/src/main/groovy/grails/ui/console/GrailsSwingConsole.groovy b/grails-console/src/main/groovy/grails/ui/console/GrailsSwingConsole.groovy
index 6846ee5e2f..ece40afdc6 100644
--- a/grails-console/src/main/groovy/grails/ui/console/GrailsSwingConsole.groovy
+++ b/grails-console/src/main/groovy/grails/ui/console/GrailsSwingConsole.groovy
@@ -27,7 +27,6 @@ import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.io.ResourceLoader
import org.springframework.util.ClassUtils
-
/**
* The Grails console runs Grails embedded within a Swing console instead of within a container like Tomcat
*
@@ -38,7 +37,7 @@ import org.springframework.util.ClassUtils
class GrailsSwingConsole extends GrailsApp {
static {
- System.setProperty("java.awt.headless", "false");
+ System.setProperty("java.awt.headless", "false")
}
GrailsSwingConsole(Class<?>... sources) {
@@ -59,7 +58,6 @@ class GrailsSwingConsole extends GrailsApp {
}
}
-
/**
... 32913 lines suppressed ...