All of the generated controller tests for my Grails 3.1.8 application fail only when trying to delete a domain instance.
The error is:
java.lang.NullPointerException: Cannot invoke method fire() on null object
at gov.usda.fs.forecast.traits.UpdateMetadataTrait$Trait$Helper.afterDelete(UpdateMetadataTrait.groovy:30)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201)
at org.grails.datastore.gorm.events.DomainEventListener.invokeEvent(DomainEventListener.java:259)
at org.grails.datastore.gorm.events.DomainEventListener.afterDelete(DomainEventListener.java:176)
at org.grails.datastore.gorm.events.DomainEventListener.onPersistenceEvent(DomainEventListener.java:96)
at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:47)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:166)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:138)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:381)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:335)
at org.grails.datastore.mapping.engine.EntityPersister.firePostDeleteEvent(EntityPersister.java:340)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.deleteEntity(NativeEntryEntityPersister.java:131)
at org.grails.datastore.mapping.engine.EntityPersister.delete(EntityPersister.java:262)
at org.grails.datastore.mapping.core.AbstractSession.delete(AbstractSession.java:728)
at org.grails.datastore.gorm.GormInstanceApi.delete_closure9(GormInstanceApi.groovy:268)
at groovy.lang.Closure.call(Closure.java:426)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:310)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:37)
at org.grails.datastore.gorm.GormInstanceApi.delete(GormInstanceApi.groovy:267)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.delete(GormEntity.groovy:194)
at gov.usda.fs.forecast.InvoiceStatusController.$tt__delete(InvoiceStatusController.groovy:91)
at gov.usda.fs.forecast.InvoiceStatusController.delete_closure4(InvoiceStatusController.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at grails.transaction.GrailsTransactionTemplate$2.doInTransaction(GrailsTransactionTemplate.groovy:96)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.execute(GrailsTran
Here is the test code:
void "Test that the delete action deletes an instance if it exists"() {
when:"The delete action is called for a null instance"
request.contentType = FORM_CONTENT_TYPE
request.method = 'DELETE'
controller.delete(null)
then:"A 404 is returned"
response.redirectedUrl == '/invoiceStatus/index'
flash.message != null
when:"A domain instance is created"
response.reset()
populateValidParams(params)
def invoiceStatus = new InvoiceStatus(params).save(flush: true)
then:"It exists"
InvoiceStatus.count() == 1
// The test fails when issuing the delete
when:"The domain instance is passed to the delete action"
controller.delete(invoiceStatus)
then:"The instance is deleted"
InvoiceStatus.count() == 0
response.redirectedUrl == '/invoiceStatus/index'
flash.message != null
}
I get the same error on every generated test in the same spot. Any clues would be greatly appreciated.
Related
I am checking if my user has entered the same password twice in controller:
if(params.password1 != "" || params.password2 != "") {
// change password
if(params.password1 != params.password2) {
user.errors.rejectValue('password', 'noMatch')
}
user.password = params.password1
}
if (user.errors.errorCount > 0 || !user.save()) {
println user.errors.errorCount
render(view: "edituser", model: [userInstance: user])
return
}
I get the correct user error count displayed in console so my if-clause works and Grails does not re-validate the object by using double pipe.
When I have a look into my GSP I get the following message:
grails.validation.ValidationErrors: 0 errors
It seams like Grails clears all errors or uses an other object. It's curious, because my custom validator in my domain class works fine...
I do not understand clearly the code behind the "assert". Please tell me what does those mean.
I already put the params attribute above my code . I did not describe detail.
void testSave() {
controller.save()
println 'testSave() from Controller'
assert model.serviceAccountInstance != null
assert view == '/serviceAccount/create'
response.reset()
populateValidParams(params)
controller.save()
println params.passWord
assert response.redirectedUrl == '/serviceAccount/show/1'
assert controller.flash.message != null
assert ServiceAccount.count() == 1
}
Than you for your answer.
I am trying to redirect a page after a g:uploadForm has submitted.
my g:uploadForm action is save.
the save is as follows:
#Transactional
def save(DesignCategory designCategoryInstance) {
if (designCategoryInstance == null) {
notFound()
return
}
if (designCategoryInstance.hasErrors()) {
respond designCategoryInstance.errors, view: 'create'
return
}
def disotypeFile = request.getFile('disotype1')
if(!disotypeFile.empty){
print('here')
def fname = disotypeFile.getOriginalFilename()
def fileAtt = new FileAttachment()
fileAtt.originalFilename = fname
fileAtt.newFilename = "disotype-"
fileAtt.fileURI = '/Users/work/Desktop/files/' + fileAtt.newFilename
disotypeFile.transferTo(new File(fileAtt.fileURI))
response.sendError(200, 'Done')
fileAtt.save(flush: true)
designInstance.disotype = fileAtt;
}
designCategoryInstance.save flush: true, failOnError:true
flash.message = message(code: 'default.created.message', args: [message(code: 'designCategoryInstance.label', default: 'DesignCategory'), designCategoryInstance.id])
redirect designCategoryInstance
}
This gives the following error:
Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.. Stacktrace follows:
Message: Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.
This does work if i take out the
def disotypeFile = request.getFile('disotype1')
but obviously I cannot get the file.
any ideas?
Try to remove line:
response.sendError(200, 'Done')
I'm having a slightly frustrating problem dealing with a service. As the title states, I'm getting a null reference error on an object when used as a parameter. When I check intelliJ using step-through functionality, there is an object with correct values being passed to each service/function. Am I missing something?
View :
<g:canAddSupervisor performanceReview="${performanceReview}">
do stuff...
</g:canAddSupervisor>
GateTagLib.groovy
class GateTagLib {
def canAddSupervisor = { attrs, body ->
Person viewer = springSecurityService.currentUser as Person
PerformanceReview review = attrs["performanceReview"]
if (performanceReviewShowGateService.canShowAddSupervisorButton(viewer, review)) {
out << body()
}
}
}
PerformanceReviewShowGateService.groovy
class PerformanceReviewShowGateService {
def performanceReviewStatusGateService
boolean canShowAddSupervisorButton(Person viewer, PerformanceReview review) {
if (!performanceReviewStatusGateService.isStatusFinalizedOrComplete(review) && isViewerAdminOrHR(viewer)) {
true
} else {
false
}
}
PerformanceReviewStatusGateService.groovy
boolean isStatusFinalizedOrComplete(PerformanceReview review) {
def statusName = review.performanceReviewStatus.name
(statusName == "Finalized" || statusName == "Complete")
}
Stacktrace :
2014-01-10 15:19:58,018 [http-bio-8080-exec-7] ERROR errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [GET] /PerformanceEvaluations/performanceReview/323
Cannot invoke method isStatusFinalizedOrComplete() on null object. Stacktrace follows:
org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error processing GroovyPageView: Error executing tag <g:render>: Error executing tag <g:canAddSupervisor>: Cannot invoke method isStatusFinalizedOrComplete() on null object
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at net.bull.javamelody.JspWrapper.invoke(JspWrapper.java:117)
at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:231)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:197)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:171)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <g:render>: Error executing tag <g:canAddSupervisor>: Cannot invoke method isStatusFinalizedOrComplete() on null object
at C__Users_per245_PerformanceReview_grails_app_views_performanceReview_show_gsp$_run_closure2.doCall(show.gsp:37)
at C__Users_per245_PerformanceReview_grails_app_views_performanceReview_show_gsp.run(show.gsp:136)
... 9 more
Caused by: org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <g:canAddSupervisor>: Cannot invoke method isStatusFinalizedOrComplete() on null object
at C__Users_per245_PerformanceReview_grails_app_views_performanceReview__evaluationListTemplate_gsp.run(_evaluationListTemplate.gsp:184)
... 11 more
Caused by: java.lang.NullPointerException: Cannot invoke method isStatusFinalizedOrComplete() on null object
at com.example.performanceevaluations.PerformanceReviewShowGateService$$EOSZwaTu.canShowAddSupervisorButton(PerformanceReviewShowGateService.groovy:71)
at com.example.performanceevaluations.GateTagLib$_closure6$$EOSZwaUW.doCall(GateTagLib.groovy:68)
... 12 more
I am using grails,and i have web application.in which when call for update user profile,then i have service for it,in which i set current user properties by request parameters
user.properties = params (params-request parameters),
and in my user domain class i have onChange method(of audit plugins).
So when this method called after setting properties to user profile when control goes to user domain onChange method it gives error
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.web.User#3].
I am still finding solution how to update row.
Thanks in advance.
//userController update method -
def user = User.get(params.id)
user.properties = params
user.save(flush:true)
//and in user domain onChange method-
def onChange = { oldMap,newMap ->
try{
Msg.append("Your profile has been updated successfully with the following changes: ");
oldMap.each({ key, oldVal ->
if(oldVal != newMap[key]) {
if(key =="firstName" || key =="gender" || key =="lastName" || key =="phoneNo" || key =="city"){
Msg.append(" * $key changed from $oldVal to " + newMap[key])
}
}
sendMail(Msg,newMap.email)
})
}
}
After sending email it gives an error.
I think if you try to set all the fields on the user object, then it will work:
def user = User.get(params.id)
user.refresh()
user.firstName= params.firstName
user.lastName= params.lastName
user.gender= params.gender
user.phno= params.phno
user.city= params.city
if(user.save(flush:true, failOnError:true)){
// Now send success email
}
Now it should work.
I think your params map is having id as a property and on setting
user.properties = params
It tries to set id for the user object, that's why you are getting the issue.