Spring Data Neo4j dynamic properties and Maps as value - neo4j

In my #RelationshipEntity I have defined the following dynamic properties:
#Properties(prefix = "property", allowCast = true)
private Map<Long, Object> properties;
Under the different Long keys I need to store Map<String, Object> object.
Everything works fine in case I store only the one Map<String, Object> object under the one Long key, for example on Neo4j level the following code:
Map<String, Object> valueProperties1 = new HashMap<>();
valueProperties1.put("active", true);
valueProperties1.put("selfEvaluation", 5);
valueProperties1.put("experience", "practical");
properties.put(1L, valueProperties1);
translates to the following Neo4j properties:
{
"property.1.active": true,
"property.1.selfEvaluation": 3,
"property.1.experience": "practical"
}
So far everything works fine.
But when I try to select this relationship entity, for example by the following Spring Data Neo4j repository method:
#Query("MATCH (d:Decision)-[drc:HAS_VALUE_ON]->(ch:Characteristic) WHERE d.id = {decisionId} AND ch.id = {characteristicId} RETURN d, ch, drc")
RelationshipValue findByDecisionOnCharacteristic(#Param("decisionId") Long decisionId, #Param("characteristicId") Long characteristicId);
it fails with the following exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Error mapping GraphModel to instance of com.decisionwanted.domain.model.neo4j.decision.characteristic.value.RelationshipValue; nested exception is org.neo4j.ogm.exception.core.MappingException: Error mapping GraphModel to instance of com.decisionwanted.domain.model.neo4j.decision.characteristic.value.RelationshipValue
at org.springframework.data.neo4j.transaction.SessionFactoryUtils.convertOgmAccessException(SessionFactoryUtils.java:126)
at org.springframework.data.neo4j.repository.support.SessionBeanDefinitionRegistrarPostProcessor.translateExceptionIfPossible(SessionBeanDefinitionRegistrarPostProcessor.java:71)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy156.findByDecisionOnCharacteristic(Unknown Source)
at com.decisionwanted.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.findByDecisionOnCharacteristic(RelationshipValueDaoImpl.java:175)
at com.decisionwanted.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.create(RelationshipValueDaoImpl.java:41)
at com.decisionwanted.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$FastClassBySpringCGLIB$$5a98b507.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at com.decisionwanted.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$EnhancerBySpringCGLIB$$7cb25ddb.create(<generated>)
at com.decisionwanted.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:119)
at com.decisionwanted.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:60)
at com.decisionwanted.domain.dao.decision.characteristic.value.ValueDaoImpl$$FastClassBySpringCGLIB$$db4e63af.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at com.decisionwanted.domain.dao.decision.characteristic.value.ValueDaoImpl$$EnhancerBySpringCGLIB$$2ce1d2d3.create(<generated>)
at com.decisionwanted.domain.DecisionCharacteristicIT.testMultivaluedCharacteristicValue(DecisionCharacteristicIT.java:313)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.neo4j.ogm.exception.core.MappingException: Error mapping GraphModel to instance of com.decisionwanted.domain.model.neo4j.decision.characteristic.value.RelationshipValue
at org.neo4j.ogm.context.GraphEntityMapper.mapEntities(GraphEntityMapper.java:205)
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:132)
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:88)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.lambda$executeAndMap$1(ExecuteQueriesDelegate.java:124)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:539)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:523)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.executeAndMap(ExecuteQueriesDelegate.java:120)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:90)
at org.neo4j.ogm.session.Neo4jSession.query(Neo4jSession.java:414)
at sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:131)
at com.sun.proxy.$Proxy112.query(Unknown Source)
at org.springframework.data.neo4j.repository.query.GraphQueryExecution$SingleEntityExecution.execute(GraphQueryExecution.java:74)
at org.springframework.data.neo4j.repository.query.GraphRepositoryQuery.doExecute(GraphRepositoryQuery.java:77)
at org.springframework.data.neo4j.repository.query.AbstractGraphRepositoryQuery.execute(AbstractGraphRepositoryQuery.java:51)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:590)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:578)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 66 more
Caused by: java.lang.UnsupportedOperationException: Only String and Enum allowed to be keys, got class java.lang.Long
at org.neo4j.ogm.typeconversion.MapCompositeConverter.keyInstanceFromString(MapCompositeConverter.java:190)
at org.neo4j.ogm.typeconversion.MapCompositeConverter.putToMap(MapCompositeConverter.java:143)
at org.neo4j.ogm.typeconversion.MapCompositeConverter.toEntityAttribute(MapCompositeConverter.java:133)
at org.neo4j.ogm.typeconversion.MapCompositeConverter.toEntityAttribute(MapCompositeConverter.java:40)
at org.neo4j.ogm.context.GraphEntityMapper.getCompositeProperties(GraphEntityMapper.java:252)
at org.neo4j.ogm.context.GraphEntityMapper.createRelationshipEntity(GraphEntityMapper.java:393)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationshipEntity(GraphEntityMapper.java:351)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationships(GraphEntityMapper.java:325)
at org.neo4j.ogm.context.GraphEntityMapper.mapEntities(GraphEntityMapper.java:201)
... 91 more
What am I doing wrong and how to fix it ?

The documentation mentions
Supported types for keys in the Map are String and Enum.
This is the same message that can be found in your logs:
Caused by: java.lang.UnsupportedOperationException: Supported types for keys in the Map are String and Enum.
Still I am not sure why it is working in the first place. Is it possible that you did not load the entity back when saving it in the first case?
I do get the error even with a single long keyed entry.

Related

Jenkinsfile using groovy classes not working when using lists

I'm writing a simple pipeline using Jenkinsfile to test classes and interfaces in Groovy but often I stock in situations that Jenkins return errors that not make any sense. For example, the next code implements a simple builder pattern:
class Configuration implements Serializable {
ArrayList credentials
}
class ConfigurationBuilder implements Serializable {
Configuration configuration
ConfigurationBuilder() {
configuration = new Configuration()
}
ConfigurationBuilder withCredentials(ArrayList credentials) {
configuration.credentials = credentials
return this
}
Configuration build() {
return configuration
}
}
node("commons") {
ConfigurationBuilder builder = new ConfigurationBuilder()
Configuration conf = builder.withCredentials(['test']).build()
echo conf.credentials
}
The code above return this error when run-it on Jenkins:
java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received class java.util.ArrayList
at org.jenkinsci.plugins.structs.describable.DescribableModel.coerce(DescribableModel.java:492)
at org.jenkinsci.plugins.structs.describable.DescribableModel.buildArguments(DescribableModel.java:409)
at org.jenkinsci.plugins.structs.describable.DescribableModel.instantiate(DescribableModel.java:329)
at org.jenkinsci.plugins.structs.describable.DescribableModel.instantiate(DescribableModel.java:272)
at org.jenkinsci.plugins.workflow.steps.StepDescriptor.newInstance(StepDescriptor.java:202)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:262)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:176)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
at sun.reflect.GeneratedMethodAccessor346.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:158)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:156)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:160)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:130)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
Caused: java.lang.IllegalArgumentException: Could not instantiate {message=[test]} for org.jenkinsci.plugins.workflow.steps.EchoStep
Any idea what's wrong?
I tried to implement it in the simplest way possible thinking that it was some limitation of Jenkins!
You passed an ArrayList to an echo step. This step accepts only values of type String.
java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received class java.util.ArrayList
You can fix this error by calling conf.credentials.toString()
node("commons") {
ConfigurationBuilder builder = new ConfigurationBuilder()
Configuration conf = builder.withCredentials(['test']).build()
echo conf.credentials.toString()
}

grails 3.2.6 fails to initialise test data "is not a domain class or GORM has not been initialized correctly"

i've created a simple grails app with latest v3.2.6. created a Authors and Book classes in grails-app/domain.
book class in grails-app/domain looks like this ( i have a books class also )
package org.softwood
//Author has many books logical model
class Author {
String name
Collection books
//static hasMany = [books:Book]
static constraints = {
books nullable:true
}
}
and book domain class for completeness
package org.softwood
class Book {
String title
Author author
//static belongsTo = [author:Author]
static constraints = {
author nullable:true
}
}
I started app - no errors and tried to use grails console to create a instance of Author and got an error like this
java.lang.IllegalStateException: Either class [org.softwood.Author] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.
so i edited BootStrap.groovy to try and create one at startup like this. Why does it not brought up Gorm correctly?
import org.softwood.*
class BootStrap {
def init = { servletContext ->
environments {
development{
createDevData()
}
test {}
production {}
}
}
def destroy = {
}
def createDevData() {
Author a = new Author(name:"will")
def res = a.save (flush:true, failOnExit:true)
assert res
assert Author.get(1).name == "will"
}
}
this errors when i start the app with same message, stack trace as follows
java.lang.IllegalStateException: Either class [org.softwood.Author] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.
at org.grails.datastore.gorm.GormEnhancer.stateException(GormEnhancer.groovy:387)
at org.grails.datastore.gorm.GormEnhancer.findInstanceApi(GormEnhancer.groovy:273)
at org.grails.datastore.gorm.GormEnhancer.findInstanceApi(GormEnhancer.groovy:270)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.currentGormInstanceApi(GormEntity.groovy:1326)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:151)
at org.grails.datastore.gorm.GormEntity$Trait$Helper$save.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:133)
at org.softwood.Author.save(Author.groovy)
at org.softwood.Author.save(Author.groovy)
at org.grails.datastore.gorm.GormEntity$save.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 test.BootStrap.createDevData(BootStrap.groovy:21)
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.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:1024)
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:158)
at test.BootStrap$_closure1$_closure3$_closure4.doCall(BootStrap.groovy:10)
at test.BootStrap$_closure1$_closure3$_closure4.doCall(BootStrap.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.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:1024)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:408)
at grails.util.Environment$EnvironmentBlockEvaluator.execute(Environment.java:529)
at grails.util.Environment.executeForEnvironment(Environment.java:510)
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:485)
at org.grails.web.servlet.boostrap.DefaultGrailsBootstrapClass.callInit(DefaultGrailsBootstrapClass.java:62)
at org.grails.web.servlet.context.GrailsConfigUtils.executeGrailsBootstraps(GrailsConfigUtils.java:65)
at org.grails.plugins.web.servlet.context.BootStrapClassRunner.onStartup(BootStrapClassRunner.groovy:53)
at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:256)
at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
at grails.boot.GrailsApp.run(GrailsApp.groovy:388)
at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
at grails.boot.GrailsApp$run.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:133)
at test.Application.main(Application.groovy:8)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
try with this
package org.softwood
//Author has many books logical model
class Author {
String name
//Collection books
static hasMany = [books:Book]
static constraints = {
books nullable:true // you may not need this.
}
}

ContextNotActiveException: WELD-001303: No active contexts for scope type org.apache.deltaspike.core.api.scope.GroupedConversationScoped

I want to use DeltaSpike for CDI-based tests. I use a lot of GroupedConversationScoped Beans for my application and when I'm trying to test them, I always run into this failure:
org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type org.apache.deltaspike.core.api.scope.GroupedConversationScoped
at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:708)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:90)
at org.jboss.weld.bean.ContextualInstance.getIfExists(ContextualInstance.java:63)
at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:83)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.getInstance(ProxyMethodHandler.java:125)
at com.pass.project.generated.context.MainDataContext$Proxy$_$$_WeldClientProxy.setTestAttr(Unknown Source)
at com.pass.project.test.DeltaSpikeTest.main(DeltaSpikeTest.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner$ContainerAwareMethodInvoker.invokeMethod(CdiTestRunner.java:340)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner$ContainerAwareMethodInvoker.evaluate(CdiTestRunner.java:312)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner.runChild(CdiTestRunner.java:174)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner.runChild(CdiTestRunner.java:75)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner$BeforeClassStatement.evaluate(CdiTestRunner.java:366)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner$AfterClassStatement.evaluate(CdiTestRunner.java:392)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner.run(CdiTestRunner.java:141)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I can't figure why it's not active. That's my test
#RunWith(CdiTestRunner.class)
public class DeltaSpikeTest {
#Inject
private DlgListBoRoleFormBean dlgListBoRoleFormBean;
#Inject
private MainDataContext mainDataContext;
#Test
public void main() {
TblTestAttrListBeanList tbl = (TblTestAttrListBeanList) dlgListBoRoleFormBean.getTblTestAttr();
List<ContactpersonValueImpl> li = new ArrayList<>();
mainDataContext.setTestAttr(li);
{
ContactpersonValueImpl person = new ContactpersonValueImpl();
person.setName("Harald");
li.add(person);
}
{
ContactpersonValueImpl person = new ContactpersonValueImpl();
person.setName("Wilhelm");
li.add(person);
}
tbl.update();
Assert.assertTrue(tbl.getList().size() == 2);
Assert.assertTrue(tbl.getList().get(0).getName().equals("Harald"));
System.out.println(tbl.toString());
}
}
Every help is highly appreciated!
You just need to activate a (test-)window, because grouped-conversations are based on the window-context to support different windows. #Inject WindowContext and use the method activateWindow. Provide any value you like.
See the example provided by OS890:
https://github.com/os890/ee6-ds-demo/blob/master/src/test/java/org/os890/demo/ee6/test/PageBeanTest.java
If you ask such questions on their mailing-list, you get answers petty quickly.
#John:
You don't need to list it via that annotation in this case.
It looks like you may have over looked the #TestControl() annotation, which is meant to start a context. Pass startScopes = GroupedConversationScoped.class into that to get the right output.
You can read more here: http://deltaspike.apache.org/documentation/test-control.html

Freemarker doesn't work in StrutsSpringTestCase

Basically, I'm trying to run a simple unit test but cannot make it work when I use freemarker as the result type. Other types like jsp or redirectAction worked fine. What am I missing?
ForwardActionTest.java:
public class ForwardActionTest extends StrutsSpringTestCase {
....
public void testExecuteAction() throws Exception {
String output = executeAction("/home.do"); <--- Exception points here
...
}
}
struts.xml
<action name="home" class="forwardAction">
<result type="freemarker">templates/home.ftl</result>
</action>
templates/home.ftl
Hello! You are home!
Stacktrace:
javax.servlet.ServletException: Error code [500], Error: [Template /templates/home.ftl not found.]
at org.apache.struts2.StrutsTestCase.executeAction(StrutsTestCase.java:120)
at com.telus.ccs.survey.web.action.ForwardActionTest.testExecuteAction(ForwardActionTest.java:22)
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 junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

how to mock ServletActionContext.getRequest() using Mockito we are using Struts2

I tried something like this but still throwing NullPointerException
#RunWith(MockitoJUnitRunner.class)
public class MyActionTest extends BaseActionTestCase {
#Mock private ServletActionContext context;
#Mock
private serviceclass serviceMock;
#InjectMocks
private MyAction action;
#Test
public void testSave() throws Exception {
when(serviceMock.getTaskCode()).thenReturn("tc");
action.save();
verify(serviceMock).saveObject(any(Task.class));
}
posting stacktrace:
java.lang.NullPointerException
at org.apache.struts2.ServletActionContext.getRequest(ServletActionContext.java:112)
at com.princess.ilo.webapp.action.BaseAction.getRequest(BaseAction.java:176)
at com.princess.ilo.webapp.action.BaseAction.getSession(BaseAction.java:198)
at com.princess.ilo.webapp.action.BaseAction.getUser(BaseAction.java:206)
at com.princess.ilo.webapp.action.TaskAction.save(TaskAction.java:116)
at com.princess.ilo.webapp.action.TaskActionTest.testSave(TaskActionTest.java:97)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests
hm, I would say you still need to create the action object, like
#InjectMocks private MyAction action = new MyAction();
see http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html for some examples

Resources