Throwing null pointer exception when accessing property of the domain object - grails

Inside a controller i just test these two lines. RaceRegistration domain has a property compositeEvent. So, i access the Registration domain first and then access the compositeevent using .compositeEvent.
println (RaceRegistration.get(r.toLong()))
println (RaceRegistration.get(r.toLong())).compositeEvent
The following error is thrown. As you can see the first print succeeds i.e it gets the Registration domain but the second println fails. My question is why is it throwing null pointer when we are certain that the RaceRegistration domain was accessed successfully.
com.runnercard.registration.RaceRegistration : 8
ERROR errors.GrailsExceptionResolver: NullPointerException occurred when processing request: [POST] /roadrace/message/sendEmail - parameters:
I appreciate any help. Thanks!

Null is null. Don't doubt this: it is true.
The 'void' println expression evaluates to null and the failing code is roughly equivalent to the following:
x = println (RaceRegistration.get(r.toLong()))
// x is null - so the following results in a NullPointerException
x.compositeEvent
It is probable that the parenthesis is merely in the wrong spot (or even over-specified):
println (RaceRegistration.get(r.toLong()).compositeEvent)
// -or
println RaceRegistration.get(r.toLong()).compositeEvent

Related

Grails wrong evaluation of expression

I wrote a function in my service class where I evaluate a passed parameters from controller but Grails is returning wrong evaluation results.
def list(String q,String qval,String srt,String ord){
log.debug("q==="+q)
log.debug("qval==="+qval)
log.debug("srt==="+srt)
log.debug("order==="+ord)
all these debug statements print null as expected. Now
boolean qvalbool=qval?.trim()
log.debug("qvalbool===>>"+qvalbool) prints true!!!
!StringUtils.isEmpty(q) && !StringUtils.isEmpty(qval) returns true!!
both statements should return false while they are returning true what is going on with this? any ideas?
I'm using grails 2.4.2
Evan Wong's comment is very likely correct that you're seeing a string containing the word null.
Often when Groovy prints out values it's not apparent what their type is.
groovy:000> null
===> null
groovy:000> 'null'
===> null
Also in Groovy the expression null + '' evaluates to the String 'null'.
That would be an easy way to change the value of this parameter so it contains the string 'null'.

Breeze: Cannot read property 'xxx' of null?

I understand there are a few similar questions (e.g. here), but they all seem to be in different context. This is what I see in my chrome console:
Unhandled rejection reasons (should be empty):
["TypeError: Cannot read property 'compound' of null…://localhost:1476/Scripts/breeze.debug.js:234:15)", joinBy: function, equals: function, indexByKey: function, getByKey: function, sortOn: function]
I could see this error in my debugger at failed(error):
return manager.executeQuery(query).then(succeeded).fail(failed);
function failed(error) {
logger.logError(error);
}
For a specific object, it happens most of time, but no always (maybe one out of 10 is okay). The query from server returns without exception. As I figured, it seems to be related to the query with a specific include of table. However, in fact, in this case, the included table doesn't have any related entry yet (if there is an entry, it doesn't seem to have any problem). Any idea?
Okay, I accidentally found out what has caused this error. It is metadatastore post-construction initializer like
manager.metadataStore.registerEntityTypeCtor("Result", Result, initialize);
// constructor
function Result() {
}
// post-construction initializer
function initialize(result) {
result.cmpName = result.cs.compound.name;
}
where result.cs could be null sometimes.
Too bad the error message didn't provide any clue.

Strange behavior of gorm finder

In a controller I have this finder
User.findByEmail('test#test.com')
And works.
Works even if I write
User.findByEmail(null)
But if i write
User.findByEmail(session.email)
and session.email is not defined (ergo is null) it throw exception
groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []
Is this behavior right?
If i evaluate "session.email" it give me null so I think it must work as it do when I write
User.findByEmail(null)
Even more strange....
If I run this code in groovy console:
import myapp.User
User.findByEmail(null)
It return a user that has null email but if I run the same code a second time it return
groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []
You can't use standard findBySomething dynamic finders to search for null values, you need to use the findBySomethingIsNull version instead. Try
def user = (session.email ? User.findByEmail(session.email)
: User.findByEmailIsNull())
Note that even if User.findByEmail(null) worked correctly every time, it would not necessarily give you the correct results on all databases as a findBySomething(null) would translate to
WHERE something = null
in the underlying SQL query, and according to the SQL spec null is not equal to anything else (not even to null). You have to use something is null in SQL to match null values, which is what findBySomethingIsNull() translates to.
You could write a static utility method in the User class to gather this check into one place
public static User byOptEmail(val) {
if(val == null) {
return User.findByEmailIsNull()
}
User.findByEmail(val)
}
and then use User.byOptEmail(session.email) in your controllers.
Jeff Brown from grails nabble forum has identified my problem. It's a GORM bug. see jira
More info on this thread
This jira too
I tried with debugger and it looks it should be working, as you write. Maybe the groovy itself is a little bit confused here, try to help it this way:
User.findByEmail( session['email'] )

Groovy give NPE on list.find call but only after a period of time

We have a chunk of code something like this
// semi-pseudo code
def result = someList.find { condition == true }
(someList may be null, but that is ok in groovy as null.find{…} works fine.)
This line of code is running in an action of a grails controller and deployed in production to a server. After a period of time (sometimes hours, sometimes longer) the above line of code will start throwing a NullPointerException — and once it starts throwing the NPE it always throws the NPE.
Through debugging we've proven that it works fine even when someList is null (up until we get the seemingly random first NPE)… also through debugging we were able to get a more detail stacktrace that indicated there error was in Groovy's MetaClassRegistryImpl.java line 214.
I've googled every combination I can think of to see if there are any known Groovy bugs but found nothing of value.
(It is using Grails 1.3.7, thus Groovy 1.7.8)
A JMeter script was setup to run through a series of site interactions that makes this problem semi-repeatable. The script will iterate through 50-100 series and then the error starts appearing - once the error appears it is always in error until the application is redeployed to the server (Glassfish).
Tracing through the groovy code it looks something like this:
//AbstractCallSite.java
public Object call(Object receiver, Object arg1) throws Throwable {
return call(receiver, ArrayUtil.createArray(arg1));
}
//PerInstancePojoMetaClassSite.java
public Object call(Object receiver, Object[] args) throws Throwable {
if (info.hasPerInstanceMetaClasses()) {
try {
return InvokerHelper.getMetaClass(receiver).invokeMethod(receiver, name, args);
} catch (GroovyRuntimeException gre) {
throw ScriptBytecodeAdapter.unwrap(gre);
}
} else {
return CallSiteArray.defaultCall(this, receiver, args);
}
}
//InvokerHelper.java
public static MetaClass getMetaClass(Object object) {
if (object instanceof GroovyObject)
return ((GroovyObject) object).getMetaClass();
else
return ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(object);
}
//MetaClassRegistryImpl.java
public MetaClass getMetaClass(Object obj) {
return ClassInfo.getClassInfo(obj.getClass()).getMetaClass(obj);
}
So it appears the NPE is on the obj.getClass() — if that's the case I'm a little baffled how it ever works when someList is null (but that is a separate topic).
FWIW, we are not doing any class or instance level meta-class coding of our own on someList.
Is there a bug in Groovy or what could we possibly be doing wrong to cause a (random) NPE deep in Groovy code?
UPDATE—
The observation is that someList is being set to a 'java null' instead of a 'groovy null' (NullObject). The object is coming from a map (flow context) via a flow in a controller action...
class SomeController {
def someActionFlow = {
action {
def someList = flow.someList
}
}
}
The case in question is when flow.someList has never been set it should always be null (groovy null). flow is just a map so it is the same as doing flow.get('someList')
The above code works fine for an unknown number of iterations and then starts returning 'java nulls' instead of 'groovy nulls'.
I'm going to hazard a guess that it's dependent on how someList is created. That is, if it's created in Groovy as
def someList = null
Then Groovy assigns the NullObject to the variable. However, if the value is returned from some other Java component as a real Java null, then it will throw the NPE. Going further, there might be some optimization in Groovy/Java/JVM where callsite caching is causing it to always return NPE.
Then again, this is just a wild guess.
Fixed: Similarly to GROOVY-5248 (call site caching missing null check), add a receiver null check to avoid NPEs under certain circumstances
commit 641c6a8d4b6b3046f4d8a1a2ac5f08f1f2769f0f

Asserting return type of MVC Controller Action

How can you assert that an expected type is returned when it is wrapped up in a System.RuntimeType?
As part of a larger unit test to verify that an action has the correct parameters and action filters assigned I'm asserting against a populated instance of MethodInfo. When I assert against "action.ReturnParameter" it fails as it's saying the type is System.RunTimeType. Whilst I understand that this is a wrapper around the expected type, I just can't seem to find a way to assert that the wrapped instance is of the expected type - the best method that I've come up with so far is to assert against name or full name, but that's horrible as it's just using "magic strings".
Can anyone help? As my Google searches haven't turned up anything useful, I'm guessing it's got a really easy solution, I'm just not seeing it.
The code is as follows:
[TestMethod]
public void CheckActionFilterSet()
{
MethodInfo action = new CustomerController((new MockHttpContext()).Object)
.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(mi => mi.Name.Equals("Search")).First();
Assert.That(action.ReturnParameter.ParameterType, Is.InstanceOf(typeof(ViewResult)), "View Result should be of expected type");
}
Exception message is:
View Result should be of expected type
Expected: instance of
<System.Web.Mvc.ViewResult>
But was:
<System.RuntimeType>
Just call the controller method and check the type of the object that is returned:
var result = new CustomerController((new MockHttpContext()).Object).Search(....);
Assert.That(result, Is.InstanceOf(typeof(ViewResult)), "View Result should be of expected type");
You can also check the values of ViewData / model if you want to...

Resources