Grails: How to reference Service itself and use it in Java? - grails

A SomeService is defined and in a closure it is passed to a Java class:
package somepackage
class SomeService{
...
def process(){
...
//here, how to reference [thisService]? this keyword?
//I tried this keyword, but an exception occurs
JavaClass javaObject = new JavaClass(thisService, otherParams)
...
}
...
}
Exception is thrown when using this referring to SomeService:
Groovyc: java.lang.NoClassDefFoundError: somepackage/SomeService
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethods(Class.java:1791)
at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:318)
at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:263)
at org.codehaus.groovy.ast.ClassNode.getUnresolvedSuperClass(ClassNode.java:957)
at org.codehaus.groovy.ast.ClassNode.getUnresolvedSuperClass(ClassNode.java:952)
at org.codehaus.groovy.ast.ClassNode.getSuperClass(ClassNode.java:946)
at org.codehaus.groovy.ast.ClassNode.isDerivedFrom(ClassNode.java:889)
at org.codehaus.groovy.classgen.AsmClassGenerator.assignmentCastAndVisit(AsmClassGenerator.java:4049)
at org.codehaus.groovy.classgen.AsmClassGenerator.evaluateEqual(AsmClassGenerator.java:4002)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitDeclarationExpression(AsmClassGenerator.java:1468)
at org.codehaus.groovy.ast.expr.DeclarationExpression.visit(DeclarationExpression.java:53)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitAndAutoboxBoolean(AsmClassGenerator.java:4111)
at org.codehaus.groovy.classgen.AsmClassGenerator.evaluateExpression(AsmClassGenerator.java:1437)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitReturnStatement(AsmClassGenerator.java:1398)
at org.codehaus.groovy.ast.stmt.ReturnStatement.visit(ReturnStatement.java:47)
at org.codehaus.groovy.ast.CodeVisitorSupport.visitBlockStatement(CodeVisitorSupport.java:35)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitBlockStatement(ClassCodeVisitorSupport.java:165)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitBlockStatement(AsmClassGenerator.java:728)
at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClassCodeContainer(ClassCodeVisitorSupport.java:101)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitConstructorOrMethod(ClassCodeVisitorSupport.java:112)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitStdMethod(AsmClassGenerator.java:616)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitConstructorOrMethod(AsmClassGenerator.java:591)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitMethod(ClassCodeVisitorSupport.java:123)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitMethod(AsmClassGenerator.java:686)
at org.codehaus.groovy.ast.ClassNode.visitContents(ClassNode.java:1039)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClass(ClassCodeVisitorSupport.java:50)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitClass(AsmClassGenerator.java:276)
at org.codehaus.groovy.control.CompilationUnit$12.call(CompilationUnit.java:748)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:942)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:519)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:497)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:474)
at org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper.compile(GroovyCompilerWrapper.java:54)
at org.jetbrains.groovy.compiler.rt.DependentGroovycRunner.runGroovyc(DependentGroovycRunner.java:80)
at org.jetbrains.groovy.compiler.rt.GroovycRunner.main(GroovycRunner.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121)
Caused by: java.lang.ClassNotFoundException: entrust.EnTrustService
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 43 more
My question is: how to reference the service itself to other classes? if this is applicable, is this problem related to the calling class being Java class other than groovy class?

You can get a reference to someService bean from ApplicationContext as:
class SomeService{
def grailsApplication
def process(){
...
//here, how to reference [thisService]? this keyword?
//I tried this keyword, but an exception occurs
JavaClass javaObject =
new JavaClass(grailsApplication.mainContext.someService, otherParams)
...
}
}
Doing this, the control goes out of the proxy and fetches the bean from the context. This same principle is applied in transactions or any aspects (AOP) related transition from one method to other in the same service class. Here is an example.

Related

org.neo4j.ogm.context.GraphEntityMapper throwing IllegalArgumentException: Can not set Double field to java.math.BigDecimal

Upgraded existing API to use Neo4j 4.3.3 and neo4j-ogm-http-driver to 3.2.25. spring-boot-starter-data-neo4j is 2.3.4.Release. Now if I try to create/fetch a relationship with one of the attribute as Double using org.springframework.data.repository CrudRepository.save() and org.springframework.data.neo4j.repository Neo4jRepository.findById(), it throws below error:
Found relationship type: OWNS to map to RelationshipEntity: RelationshipEntityName
2021-08-21 00:25:14.780 ERROR 3556 --- [nio-8303-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Error mapping GraphModel; nested exception is org.neo4j.ogm.exception.core.MappingException: Error mapping GraphModel] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Double field RelationshipEntityName.percentage to java.math.BigDecimal
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at org.neo4j.ogm.metadata.FieldInfo.lambda$write$0(FieldInfo.java:352)
at java.security.AccessController.doPrivileged(Native Method)
at org.neo4j.ogm.metadata.FieldInfo.write(FieldInfo.java:349)
at org.neo4j.ogm.metadata.FieldInfo.write(FieldInfo.java:383)
at org.neo4j.ogm.context.GraphEntityMapper.writeProperty(GraphEntityMapper.java:305)
at org.neo4j.ogm.context.GraphEntityMapper.setProperties(GraphEntityMapper.java:268)
at org.neo4j.ogm.context.GraphEntityMapper.createRelationshipEntity(GraphEntityMapper.java:409)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationshipEntity(GraphEntityMapper.java:354)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationships(GraphEntityMapper.java:330)
at org.neo4j.ogm.context.GraphEntityMapper.mapContentOf(GraphEntityMapper.java:158)
at org.neo4j.ogm.context.GraphEntityMapper.lambda$map$2(GraphEntityMapper.java:115)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:117)
at org.neo4j.ogm.context.GraphRowModelMapper.map(GraphRowModelMapper.java:60)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.lambda$executeAndMap$1(ExecuteQueriesDelegate.java:165)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:590)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:564)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.executeAndMap(ExecuteQueriesDelegate.java:150)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:117)
at org.neo4j.ogm.session.Neo4jSession.query(Neo4jSession.java:425)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.lambda$invoke$1(SharedSessionCreator.java:121)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invokeInTransaction(SharedSessionCreator.java:159)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:123)
at com.sun.proxy.$Proxy88.query(Unknown Source)
at org.springframework.data.neo4j.repository.query.GraphQueryExecution$SingleEntityExecution.execute(GraphQueryExecution.java:64)
at org.springframework.data.neo4j.repository.query.GraphRepositoryQuery.doExecute(GraphRepositoryQuery.java:76)
at org.springframework.data.neo4j.repository.query.AbstractGraphRepositoryQuery.execute(AbstractGraphRepositoryQuery.java:57)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor$QueryMethodInvoker.invoke(QueryExecutorMethodInterceptor.java:195)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy111.findByResource(Unknown Source)
I tried changing the attribute percentage to Number, that does not throw the exception but percentage doesn't get saved.
I do not want to upgrade spring-boot-starter-data-neo4j to any major version at this point.
Upgrading to Spring-Data-Neo4j 6.x will again be big migration effort.
I am stuck now.
I found out the exact place where the error was coming from was neo4j.ogm.core files, I tried various versions of the jar but nothing worked.
Finally I resolved the problem by writing a custom converter as the implicit converter was not able to convert between Double and BigDecimal.
public class PercentageConverter implements AttributeConverter<Double, BigDecimal> {
#Override
public BigDecimal toGraphProperty(Double value) {
if (value == null) {
return null;
}
return new BigDecimal(value);
}
#Override
public Double toEntityAttribute(BigDecimal value) {
return value.doubleValue();
}
}
and annotate the entity attribute to use this converter
#Convert(PercentageConverter.class)
This resolved my error and now I can do all CRUD operations successfully

mapWith with hasMany giving error on run-app with Grails v3.3.5 working fine with Grails v3.2.11

I have a domain class DomainA --
class DomainA {
String someString
static mapWith = "none"
}
I don't want to persist this domain so I am using mapWith property. And have its relation in DomainB in hasMany --
class DomainB {
String anotherString
static hasMany = [domainAs: DomainA]
}
This code is working fine with Grails v3.2.11 but giving following error with Grails v3.3.x.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'methodValidationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Unsatisfied dependency expressed through method 'methodValidationPostProcessor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastoreServiceRegistry': Cannot resolve reference to bean 'hibernateDatastore' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1071)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:225)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:703)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at grails.boot.GrailsApp.run(GrailsApp.groovy:84)
at grails.boot.GrailsApp.run(GrailsApp.groovy:393)
at grails.boot.GrailsApp.run(GrailsApp.groovy:380)
at grails.boot.GrailsApp$run.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at upgrade.Application.main(Application.groovy:8)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastoreServiceRegistry': Cannot resolve reference to bean 'hibernateDatastore' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:648)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getSingletonFactoryBeanForTypeCheck(AbstractAutowireCapableBeanFactory.java:927)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBean(AbstractAutowireCapableBeanFactory.java:804)
at org.springframework.beans.factory.support.AbstractBeanFactory.isTypeMatch(AbstractBeanFactory.java:564)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:432)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:206)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1267)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 40 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 49 common frames omitted
Caused by: java.lang.NullPointerException: null
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.getTableName(GrailsDomainBinder.java:1202)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.calculateTableForMany(GrailsDomainBinder.java:1155)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.bindCollectionTable(GrailsDomainBinder.java:1105)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.bindCollection(GrailsDomainBinder.java:1052)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder$CollectionType$1.create(GrailsDomainBinder.java:3463)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.createClassProperties(GrailsDomainBinder.java:1872)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.bindRootPersistentClassCommonValues(GrailsDomainBinder.java:1751)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.bindRoot(GrailsDomainBinder.java:1391)
at org.grails.orm.hibernate.cfg.GrailsDomainBinder.contribute(GrailsDomainBinder.java:165)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:275)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.grails.orm.hibernate.cfg.HibernateMappingContextConfiguration.buildSessionFactory(HibernateMappingContextConfiguration.java:276)
at org.grails.orm.hibernate.connections.HibernateConnectionSourceFactory.create(HibernateConnectionSourceFactory.java:86)
at org.grails.orm.hibernate.connections.AbstractHibernateConnectionSourceFactory.create(AbstractHibernateConnectionSourceFactory.java:39)
at org.grails.orm.hibernate.connections.AbstractHibernateConnectionSourceFactory.create(AbstractHibernateConnectionSourceFactory.java:23)
at org.grails.datastore.mapping.core.connections.AbstractConnectionSourceFactory.create(AbstractConnectionSourceFactory.java:64)
at org.grails.datastore.mapping.core.connections.AbstractConnectionSourceFactory.create(AbstractConnectionSourceFactory.java:52)
at org.grails.datastore.mapping.core.connections.ConnectionSourcesInitializer.create(ConnectionSourcesInitializer.groovy:24)
at org.grails.orm.hibernate.HibernateDatastore.<init>(HibernateDatastore.java:204)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1076)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 51 common frames omitted
I searched for its solution or any workaround but did not get anything.
Anyone have any idea how can I fix the issue. Thanks!
Note -- I am using Gradle v3.5.
As per the following comment by Ben Rhine on this issue this is not supported from Grails 3.x.
In looking into this issue this is improper usage of the mapWith static property. The issue is not really the mapWith property but that you have a hasMany on an un-persisted class as that is not supported.
While this may have worked previously (verified your described behavior works up through 3.2.13 with Gorm 6.0.x) it was not a feature, this does not work in Grails 3.3.x with Gorm 6.1.x as relationships such as hasMany will not work with un-persisted classes.
I would suggest you reconsider your relationship mapping and you may not even need mapWith when your done.

Grails / Gorm / Exception in thread "Thread-8" BUG! exception in phase 'semantic analysis' in source unit

Getting this exception in Gorm 6.1 with Grails 3.3.2:
Exception in thread "Thread-8" BUG! exception in phase 'semantic analysis' in source unit '/Users/emmanuj/projects/cleena/demo/src/main/groovy/com/emmanuj/cleena/UserService.groovy' unexpected NullpointerException
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1070)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:537)
at grails.boot.GrailsApp.compileGroovyFile(GrailsApp.groovy:313)
at grails.boot.GrailsApp.recompile(GrailsApp.groovy:299)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy:240)
at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:408)
at groovy.lang.Closure.run(Closure.java:495)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at org.grails.datastore.gorm.services.implementers.AbstractDetachedCriteriaServiceImplementor.doImplement(AbstractDetachedCriteriaServiceImplementor.groovy:79)
at org.grails.datastore.gorm.services.implementers.AbstractReadOperationImplementer.implement(AbstractReadOperationImplementer.groovy:62)
at org.grails.datastore.gorm.services.transform.ServiceTransformation.visitAfterTraitApplied(ServiceTransformation.groovy:278)
at org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation.visit(AbstractTraitApplyingGormASTTransformation.groovy:52)
at org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation.visit(AbstractTraitApplyingGormASTTransformation.groovy:42)
at org.grails.datastore.gorm.transform.AbstractGormASTTransformation.visit(AbstractGormASTTransformation.groovy:59)
at org.codehaus.groovy.transform.ASTTransformationVisitor.visitClass(ASTTransformationVisitor.java:134)
at org.codehaus.groovy.transform.ASTTransformationVisitor$2.call(ASTTransformationVisitor.java:178)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1065)
... 34 more
Steps To Reproduce
Create a new Grails 3.3.2 project
Create a domain class called User like below:
import grails.compiler.GrailsCompileStatic
#GrailsCompileStatic
class User {
String name
static constraints = {
}
}
And the Following Gorm Data Services Interface and class:
package com.emmanuj.cleena
/**
* DataService interface for user domain
*/
interface IUserService {
User get(Serializable id)
List<User> list(Map args)
Long count()
void delete(Serializable id)
User save(User user)
}
And an abstract class implementation:
#Slf4j
#Service(User)
abstract class UserService implements IUserService {
def grailsApplication
List<User> search(User currentUser, long radius, int offset, int max){
return []
}
def getZipcodes(String zipCode, long radius) {
return []
}
}
Run your grails app from the interactive prompt.
Make a change to UserService
Exception/Crash during recompile.
Groovy version is 2.4.13
I opened an issue on the github repo. Looks like a GORM Hibernate bug: https://github.com/grails/gorm-hibernate5/issues/72. But they've closed it as "won't fix". Not sure why...
Restarting the Grails server fixed the issue.
Below is the actual explanation -
I Created a class that was working fine and then I updated it to Associate another dependent class, and Grails threw this error.
The error simply means it cannot compile your already compiled class when it requires creating few more objects when server is running.

Grails Service can't create Sql instance

How can I create an instance of class groovy.sql.Sql in a Grails service without using dataSource or anything GORM Hibernate related? In my Grails app, in my Service class when I try to create a Sql instance I get an exception:
Caused by: java.lang.ClassNotFoundException: org.postgresql.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java_lang_ClassLoader$loadClass$1.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at com.tav.admin.DbService.copyFileToTable(DbService.groovy:87)
Seems to be a class loading issue. Here is the service method.
long copyFileToTable(String sql, FileReader fileReader) {
println("System Class Loader: ${ClassLoader.getSystemClassLoader().getClass().getName()}")
println("Groovy Class Loader: ${Thread.currentThread().getContextClassLoader().getClass().getName()}")
Thread.currentThread().getContextClassLoader().loadClass(driverClassName)
ClassLoader.getSystemClassLoader().loadClass(driverClassName) // Note throws exception here!
props = new Properties()
props.setProperty('user', username)
props.setProperty('password', password)
PgConnection copyOperationConnection = (PgConnection) Sql.newInstance(url, props, driverClassName)
CopyManager copyManager = new CopyManager(copyOperationConnection)
return copyManager.copyIn(sql, fileReader)
}
Output:
System Class Loader: sun.misc.Launcher$AppClassLoader
Groovy Class Loader: groovy.lang.GroovyClassLoader
The PostgreSQL driver is registered with DriverManager. I can use the injected dataSource in my service but I need to create and new connection to the database unrelated to GORM Hibernate to use driver specific functionality (PostgreSQL CopyManager).
In DriverManager.isDriverAllowed()
Class.forName(driver.getClass().getName(), true, classLoader);
return null.
Version info: Grails 2.5.1, Java jdk1.7.0_79, Groovy 2.0.6
I have narrowed the problem down to the line of code below:
ClassLoader.getSystemClassLoader().loadClass(driverClassName) // Note throws exception here!
Seems like Groovy/Grails loads the JDBC driver using the GroovyClassLoader but when you try to get a connection from DriverManager.getConnection(), driver manager tries to load the JDBC driver using the System Class Loader. The system class loader seems unaware that the Groovy class loader has already loaded the class. It's like the DriverManager and the System Class loader are sandboxed away from the Groovy loaded classes.
In my case I have the same situation (use Sql without GORM) but with MySQL.
I declared a dataSource bean at resources.groovy :
beans{
"otherDataSource"(BasicDataSource) {
driverClassName = 'com.mysql.Driver'
username = 'xxx'
password = 'xxxx'
url = 'jdbc:blablabla'
}
}
And inject it at the service
class MyService{
def otherDataSource
void doIt(){
def sql = new Sql(otherDataSource)
}
}
In order to interface with PostgreSQL you need to have a suitable driver in the classpath as the stack trace says.
You need to have a dependency included or an external library bundled in a jar that will provide you with a package that implements the `javax.sql.*' interface.

NotSerializableException when shutting down glassfish

I get an NotSerializableException when shutting down Glassfish (3.1), due to an HtmlSelectOneMenu. I use HtmlSelectOneMenu in other controller beans, but they are not bound to the backing bean as this one. This happens only if there are sessions active on the server of course.
How can I avoid exception when starting/stopping Glassfish for the bounded JSF component ?
Controller Class
#ManagedBean
#SessionScoped
...
public class ActivityController implements Serializable {
..
private DataModel<MyObjcet> items = null;
private HtmlSelectOneMenu myMenu;
...
Exception
INFO: PWC2785: Cannot serialize session attribute activityController for session a4591e053e65effc743dade67eef
java.io.NotSerializableException: javax.faces.component.html.HtmlSelectOneMenu
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:2067)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1469)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at org.apache.catalina.session.StandardManager.writeSessions(StandardManager.java:699)
at org.apache.catalina.session.StandardManager.doUnloadToFile(StandardManager.java:618)
at org.apache.catalina.session.StandardManager.unload(StandardManager.java:589)
at org.apache.catalina.session.StandardManager.stop(StandardManager.java:879)
at org.apache.catalina.core.StandardContext.stop(StandardContext.java:5509)
at com.sun.enterprise.web.WebModule.stop(WebModule.java:529)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:1049)
at com.sun.enterprise.web.WebContainer.unloadWebModule(WebContainer.java:2191)
at com.sun.enterprise.web.WebContainer.unloadWebModule(WebContainer.java:2146)
at com.sun.enterprise.web.WebApplication.stop(WebApplication.java:151)
at org.glassfish.internal.data.EngineRef.stop(EngineRef.java:169)
at org.glassfish.internal.data.ModuleInfo.stop(ModuleInfo.java:302)
at org.glassfish.internal.data.ApplicationInfo.stop(ApplicationInfo.java:314)
at com.sun.enterprise.v3.server.ApplicationLifecycle.unload(ApplicationLifecycle.java:997)
at com.sun.enterprise.v3.server.ApplicationLifecycle.disable(ApplicationLifecycle.java:1952)
at com.sun.enterprise.v3.server.ApplicationLoaderService.stopApplication(ApplicationLoaderService.java:443)
at com.sun.enterprise.v3.server.ApplicationLoaderService.preDestroy(ApplicationLoaderService.java:411)
at com.sun.hk2.component.AbstractCreatorInhabitantImpl.dispose(AbstractCreatorInhabitantImpl.java:83)
at com.sun.hk2.component.SingletonInhabitant.release(SingletonInhabitant.java:81)
at com.sun.hk2.component.EventPublishingInhabitant.release(EventPublishingInhabitant.java:108)
at com.sun.hk2.component.LazyInhabitant.release(LazyInhabitant.java:133)
at com.sun.enterprise.v3.server.AppServerStartup.stop(AppServerStartup.java:415)
at com.sun.enterprise.glassfish.bootstrap.GlassFishImpl.stop(GlassFishImpl.java:88)
at com.sun.enterprise.v3.admin.StopServer.doExecute(StopServer.java:70)
at com.sun.enterprise.v3.admin.StopDomainCommand.execute(StopDomainCommand.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.run(CommandRunnerImpl.java:383)
Make it transient.
private transient HtmlSelectOneMenu myMenu;
This way the field will be skipped on (de)serialization. By the way, the DataModel is also not serializable.
On the other hand, binding components directly to the backing bean is in most cases a smell. You should consider looking (or asking) for an alternative approach which does not require binding components to the bean.

Resources