Cannot invoke method on null object groovy ошибка

Because this code:

if (!conf.contains('homepage')) { list << conf.trim() }

does not return anything when the condition is not met. There’s no else to this if. If you add an else returning a meaningful value, you’ll avoid the exception.

The ternary operator, on the other hand, does return a value whether or not the condition is met so this code:

conf.contains('homepage') ? list : list << conf.trim()

returns an actual object even if conf does contain 'homepage'

To see why this is a problem, take a look at what the inject method does.

To quote the Javadoc:

Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used.

Now, let’s take a look at a slightly modified example. I added a println to see what the closure parameters become:

 ['homepages/gg','a','b','c','d'].inject([]) { list, conf -> println "[$list, $conf]"; if (!conf.contains('homepage')) { list << conf.trim() } }

Running this yields:

[[], homepages/gg]
[null, a]
Exception thrown

java.lang.NullPointerException: Cannot invoke method leftShift() on null object

    at ConsoleScript9$_run_closure2.doCall(ConsoleScript9:2)

    at ConsoleScript9.run(ConsoleScript9:2)

The first call takes the empty array that you pass as the single Object parameter and the first element of the list, namely "homepages/gg". This gets passed to the if expression. Because the first element, "homepages/gg" does indeed contain the string "homepage", the if condition is evaluated to false. Because there is no else, nothing is returned.

The nothing, represented by a null reference, returned by the first evaluation of the closure is used in the second evaluation, along with the next element of the list.

conf is now equal to "a» and list is equal to null. Further on, you use the << left shift operator on the null list (list << conf.trim()).

Hence the exception.

Here’s a version equivalent to the one that works:

['homepages/gg','a','b','c','d'].inject([]) { list, conf ->  if (!conf.contains('homepage')) { list << conf.trim() } else list }

The output is as expected:

===> [a, b, c, d]

I have tried versions 2.8 and 2.9 and keep running into the same issue. Some of the Junit 12 parameterized test classes fail with the below error when running on teamcity build server. I was also able to replicate this when running locally using command line. Project is maven based and using surefire plugin version 19.1. Here is the error:

java.lang.NullPointerException: Cannot invoke method select() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at com.jayway.restassured.internal.proxy.RestAssuredProxySelector.select(RestAssuredProxySelector.groovy:38)
…. (there are more lines of code so do let me know if you require them)
Sample code below where I had to omit some stuff. I have confirmed the getUserId() and url are correct as I get values when printing. First suite of the tests work fine but later in the build process, tests error out with the above message. There is no proxy setup and the url has SSL. Please let me know if you need anymore information. I have tried using RestAssured.baseURI to set url as well as specification which had no effect.

private static RequestSpecification spec;
String url = «https://….»;
public void restAssuredSetup(){
spec = new RequestSpecBuilder().setBaseUri(url + «/api»).build();
RestAssured.useRelaxedHTTPSValidation();
}
public void resetAllStandards() {
RestAssured.given().spec(spec).delete(«/MasteryTestingApi/» + getUserId());
}

@before
public void setup(){
resetAllStandards();
……
..
}

I’m trying to get some attributes from an object and save them to different variables, yet I keep getting this error when testing on Insight Script Console:

GroovyInsightException: Cannot invoke method getObjectAttributeValueBeans() on null object’

I add the object key to the «Object Key» field but it still sees it as a null object. Does this have to do with my code or does Insight not recognize the key I have inserted?

Here is the code I am testing:

import groovy.json.*
import groovyx.net.http.ContentType
import com.atlassian.jira.issue.*
import com.atlassian.jira.component.ComponentAccessor
import org.joda.time.format.*
import java.lang.String
import java.text.SimpleDateFormat
import org.apache.log4j.*

//Inicialize object & object attributes
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass(«com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade»));
def objectTypeAttributeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass(«com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeAttributeFacade»))
def objectAttributeBeanFactory = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass(«com.riadalabs.jira.plugins.insight.services.model.factory.ObjectAttributeBeanFactory»));

//Load object attributes
def key = objectFacade.loadObjectAttributeBean(object.getId(), 1448).getObjectAttributeValueBeans()[0].getValue(); //The id of the attribute
def name = objectFacade.loadObjectAttributeBean(object.getId(), 1449).getObjectAttributeValueBeans()[0].getValue();
def ti = objectFacade.loadObjectAttributeBean(object.getId(), 1463).getObjectAttributeValueBeans()[0].getValue();
def ta = objectFacade.loadObjectAttributeBean(object.getId(), 1464).getObjectAttributeValueBeans()[0].getValue();
def loc = objectFacade.loadObjectAttributeBean(object.getId(), 3981).getObjectAttributeValueBeans()[0].getValue();
def dinc = objectFacade.loadObjectAttributeBean(object.getId(), 4002).getObjectAttributeValueBeans()[0].getValue();
def dfim = objectFacade.loadObjectAttributeBean(object.getId(), 4003).getObjectAttributeValueBeans()[0].getValue();
def org = objectFacade.loadObjectAttributeBean(object.getId(), 4063).getObjectAttributeValueBeans()[0].getValue();
def notes = objectFacade.loadObjectAttributeBean(object.getId(), 4066).getObjectAttributeValueBeans()[0].getValue();

return key;

1 answer

1 accepted

Suggest an answer

People on a hot air balloon lifted by Community discussions

Still have a question?

Get fast answers from people who know.

Was this helpful?

Thanks!

Gradle Forums

Loading

From Grails documentation:

The save method returns null if validation failed and the instance was not persisted, or the instance itself if successful. This lets you use “Groovy truth” (null is considered false) to write code like the following:

http://grails.org/doc/latest/ref/Domain%20Classes/save.html

To see what the validation error is:

Use:

 save(failOnError:true

Same goes for merge():

merge(failOnError:true)

especially if you use the pattern:

obj = object.merge(failOnError:true)

obj.save(failOnError:true)

Full StackTrace:

java.lang.NullPointerException: Cannot invoke method save() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:77)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:32)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at [SERVICE NAME].save([SERVICE NAME].groovy:32)

Published
September 8, 2013September 8, 2013

Возможно, вам также будет интересно:

  • Canon 2900 ошибка e100 0000
  • Canon 2520 ошибка e000000 как сбросить
  • Canon 2400 ошибка 5в00 сбросить
  • Canon 237 ошибка связи с картриджем
  • Canon 1500 ошибка печатающей головки

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии