This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Am writing spring boot rest api to fetch records from elastic search by id. While am getting response from elastic search few keys having null object.
So, how I can do the null check while setting value for Product (POJO class).
Am handling this exception with the below line of code, but still the error is persisting product.setExpiration_date(sourceAsMap.get("expiration_date").toString() != null ? sourceAsMap.get("expiration_date").toString() : "");.
Am not sure whether my approach is correct or not.
Please find the full code below.
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest);
} catch (IOException e) {
e.getLocalizedMessage();
}
// read the response
String productName = null;
Product product = null;
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
// get each hit as a Map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
product=new Product();
product.setName(sourceAsMap.get("name").toString());
product.setCatalog_id(sourceAsMap.get("catalog_id").toString());
product.setCode(sourceAsMap.get("code").toString());
product.setExpiration_date(sourceAsMap.get("expiration_date").toString() != null ?
sourceAsMap.get("expiration_date").toString() : ""); // Error throwing in this line.
product.setIs_visible(sourceAsMap.get("is_visible").toString());
}
Please find my error below :
2018-05-23 22:59:13.216 ERROR 9948 --- [nio-8594-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 java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.sun.searchengine.dao.ProductDao.getProductById(ProductDao.java:105) ~[classes/:na]
at com.sun.searchengine.controller.ProductController.getProductById(ProductController.java:24) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
When you check for null element don't need call a method on them.
sourceAsMap.get("expiration_date").toString() != null ?
sourceAsMap.get("expiration_date").toString() : ""
becomes
sourceAsMap.get("expiration_date") != null ?
sourceAsMap.get("expiration_date").toString() : ""
Otherwise you are calling to string on a null
Related
In my XPages app I am trying to set an Item as Authors type but I get an unexpected key cannot be 0 message:
java.lang.IllegalArgumentException: key cannot be 0
at org.openntf.domino.impl.DominoReferenceCache.put(DominoReferenceCache.java:148)
at org.openntf.domino.impl.WrapperFactory.recacheLotusObject(WrapperFactory.java:316)
at org.openntf.domino.impl.BaseThreadSafe.setDelegate(BaseThreadSafe.java:75)
at org.openntf.domino.impl.Item.resurrect(Item.java:1064)
at org.openntf.domino.impl.Base.getDelegate(Base.java:475)
at org.openntf.domino.impl.Item.getFlagSet(Item.java:105)
at org.openntf.domino.impl.Item.isNames(Item.java:629)
at org.openntf.domino.impl.Item.hasFlag(Item.java:1086)
at org.openntf.domino.impl.Item.isReadersNamesAuthors(Item.java:1101)
at org.openntf.domino.impl.Item.setAuthors(Item.java:731)
at org.acme.projectx.dao.MatterDominoDAO.setAccessFields(MatterDominoDAO.java:1875)
Here is where I am trying to set the property:
matter.setCommAuthors(getAuthorsCommittee(matter));
if (null != matter.getCommAuthors()) {
fieldName = "CommAuthors";
doc.replaceItemValue(fieldName, matter.getCommAuthors());
Item authorFieldCommittee = doc.replaceItemValue(fieldName, matter.getCommAuthors());
authorFieldCommittee.setAuthors(true);
}
Anyone has a clue why the error message pops up?
Currently I get the following output from code run
Caused by: java.lang.NullPointerException
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:227)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:256)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:560)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:514)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1192)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1132)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:219)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:312)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3189)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2114)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:937)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:443)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:394)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.parse(HtmlUnitNekoDOMBuilder.java:760)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:158)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:112)
at com.gargoylesoftware.htmlunit.javascript.host.Element.parseHtmlSnippet(Element.java:868)
at com.gargoylesoftware.htmlunit.javascript.host.Element.setInnerHTML(Element.java:920)
at com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.setInnerHTML(HTMLElement.java:676)
at sun.reflect.GeneratedMethodAccessor17.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:188)
... 30 more
The above ... 30 more means that I do not know the line of my code that causes the problem. How can I get the full stack trace.
Also, if it does not seem to be running any of my catch statements with printStackTrace, but if I turn off logging with the below command
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
**Have put in my full code below as suggested by the comments below . Did not put in the actual URL though**
import com.gargoylesoftware.htmlunit.html.*;
import java.io.File;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class download_to_send_to_stackoverflow
{
public static void main(String args[])
{
String url = "did not want to include the actual web site ";
HtmlPage page = null;
WebClient webClient = new WebClient();
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true); // tried making false - but didnt work
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setTimeout(30000);
webClient.setJavaScriptTimeout(30000); //e.g. 50s
webClient.waitForBackgroundJavaScript(15000) ; // added 2017/1/24
webClient.waitForBackgroundJavaScriptStartingBefore(30000) ; // added 2017/1/24
try
{
page = webClient.getPage( url );
savePage_just_html(page );
}
catch( Exception e )
{
System.out.println( "Exception thrown:----------------------------------------" + e.getMessage() );
e.printStackTrace();
}
}
protected static String savePage_just_html(HtmlPage page)
{
try
{
File saveFolder = new File("spool/_");
page.save(saveFolder); // this is the line causing the error with limit stack trace
}
catch ( Exception e )
{
System.out.println( "IOException was thrown: ---------------------------------- " + e.getMessage() );
e.printStackTrace();
}
return "file.html";
}
}
------------------------------------------------------
page.save(saveFolder); above is the problem line. if I take it out I dont get the limited statcktrace errors but I also dont save the html page - which I want to do
- The question is - why does this line only print a limited stacktrace
The "Caused by" means that this is a nested exception.
The "... 30 more" in a nested exception stacktrace means that those 30 lines are the same as in the primary exception.
So just look at the primary stacktrace to see those stack frames.
Apparently your exception stacktraces are being generated in a way that is suppressing (or removing) the primary exception stacktrace. This is puzzling, but it is probably being done by one of the unit testing libraries that you are using.
Getting to the bottom of this will probably involve you either debugging whatever it is that is generating the stacktrace, or writing a minimal reproducible example so that someone else can debug it.
Getting org.apache.solr.common.SolrException: java.lang.IllegalArgumentException: Invalid path string "//10.52.21.4:8021/solr" caused by empty node name specified #1 while trying to connect to solr client.
Full Logs:
org.apache.solr.common.SolrException: java.lang.IllegalArgumentException: Invalid path string "//10.52.21.4:8021/solr" caused by empty node name specified #1
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:171)
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:117)
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:107)
at org.apache.solr.common.cloud.ZkStateReader.<init>(ZkStateReader.java:277)
at org.apache.solr.client.solrj.impl.ZkClientClusterStateProvider.connect(ZkClientClusterStateProvider.java:140)
at org.apache.solr.client.solrj.impl.CloudSolrClient.connect(CloudSolrClient.java:383)
at org.apache.solr.client.solrj.impl.CloudSolrClient.requestWithRetryOnStaleState(CloudSolrClient.java:805)
at org.apache.solr.client.solrj.impl.CloudSolrClient.request(CloudSolrClient.java:793)
at org.apache.solr.client.solrj.SolrRequest.process(SolrRequest.java:178)
at org.apache.solr.client.solrj.SolrRequest.process(SolrRequest.java:195)
I am getting the error while trying to execute below block of code:
String solrUrl="http://10.52.21.4:8021/solr/";
ArrayList<String> fields = new ArrayList<String>();
CollectionAdminResponse response = ( CollectionAdminResponse ) request.process( new CloudSolrClient.Builder().withZkHost( solrUrl ).build() );
fields = ( ArrayList<String> ) response.getResponse().get( "collections" );
Anybody please help with the problem.
I am trying to fire the rule. However, I am getting following exception:
java.lang.RuntimeException: Unexpected global [map]
at org.drools.core.impl.StatefulKnowledgeSessionImpl.setGlobal(StatefulKnowledgeSessionImpl.java:1163)
at com.senselytics.inference.rule.RulesEngineStreamMode.init(RulesEngineStreamMode.java:72)
at com.senselytics.inference.rule.RulesEngineStreamMode.<init>(RulesEngineStreamMode.java:34)
at com.senselytics.inference.mq.MessageReceiverHandler.<init>(MessageReceiverHandler.java:15)
at com.senselytics.inference.mq.MessageReceiverHandler.getInstance(MessageReceiverHandler.java:22)
at com.senselytics.RulesEngineTest.testThreshhold(RulesEngineTest.java:33)
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 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:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
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:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Code:
System.setProperty("drools.dialect.java.strict", "false");
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
Map<String, TagEvent> map = RulesEngineDAO.selectAllConfigDetails();
for (TagEvent tagEvent : map.values()) {
kbuilder.add(ResourceFactory.newReaderResource(TagEventRuleBuilder
.buildRuleFromTemplate(tagEvent)), ResourceType.DRL);
}
Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
KieBaseConfiguration kbaseConfiguration = KnowledgeBaseFactory
.newKnowledgeBaseConfiguration();
kbaseConfiguration.setOption(EventProcessingOption.STREAM);
final KnowledgeBase kbase = KnowledgeBaseFactory
.newKnowledgeBase(kbaseConfiguration);
kbase.addKnowledgePackages(pkgs);
KieSessionConfiguration sessionConf = KnowledgeBaseFactory
.newKnowledgeSessionConfiguration();
sessionConf.setOption(ClockTypeOption.get("realtime"));
ksession = kbase.newStatefulKnowledgeSession(sessionConf, null);
Map<String, TagEvent> globalMap = RulesEngineDAO.selectAllConfigDetails();
ksession.setGlobal("map", globalMap);
new Thread() {
#Override
public void run() {
ksession.fireUntilHalt();
}
}.start();
I am calling above code for making the session. Every thing is fine and am able to get the knowledge session. However, on the line
ksession.setGlobal("map", globalMap);
, above exception is thrown.
Am using the template for generation of DRL file and DRL file is getting generated also. In the template and generated DRL file:
global java.util.Map<String,TagEvent> map;
I am not really able to figure out why this error is coming up when running the code.
By using following code snippet :
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if( errors.size() > 0 )
{
for( KnowledgeBuilderError error : errors )
{
System.err.println( "Errors : "+error );
}
throw new IllegalArgumentException( "Could not parse knowledge." );
}
Now I am getting following errors:
Errors : [46,4]: [ERR 102] Line 46:4 mismatched input 'then' in rule "Count Values"
Errors : [0,0]: Parser returned a null Package
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : [46,4]: [ERR 102] Line 46:4 mismatched input 'then' in rule "Count Values"
Errors : [0,0]: Parser returned a null Package
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
DRL:
package com.senselytics.inference.rule.counter;
import java.util.HashMap;
import com.senselytics.inference.rule.*;
import com.senselytics.inference.vo.*;
import com.senselytics.inference.vo.TagEvent;
import com.senselytics.inference.vo.TagEventTimeTracker;
import com.senselytics.inference.vo.TagEventMetadata;
global java.util.Map<String,TagEvent> map;
declare TagEvent
#role( event )
#timestamp( tagTime )
#expires( 1s )
end
declare TagEventMetadata
#role( event )
end
declare TagEventTimeTracker
#role( event )
end
rule "Out Of Range Check -LOW"
dialect "java"
when
$tagEvent : TagEvent( status==Status.WITHIN_RANGE, tagValue != null,map.get($tagEvent.getTagName())!=null, tagValue<=((TagEvent)map.get($tagEvent.getTagName())).getMinThreshold())
then
System.out.println("Out Of Range Check -LOW");
modify( $tagEvent ) { setStatus( Status.OUT_OF_RANGE_LOW ) };
end;
rule "Out Of Range Check - HIGH"
dialect "java"
when
$tagEvent : TagEvent( status==Status.WITHIN_RANGE, tagValue != null, map.get($tagEvent.getTagName())!=null, tagValue >= ((TagEvent)map.get($tagEvent.getTagName())).getMaxThreshold() )
then
System.out.println("Out Of Range Check - HIGH");
modify( $tagEvent ) { setStatus( Status.OUT_OF_RANGE_HIGH ) };
end;
rule "Trigger Threshold Alert"
dialect "java"
when
$tagEvent : TagEvent( status!=null, status!=Status.WITHIN_RANGE )
then
FileWriter.writer("Out Of Range Check : "+$tagEvent);
end;
rule "Count Values"
dialect "java"
when
accumulate ( TagEvent( tagName.equals("GSA_SI11151"), status!=Status.WITHIN_RANGE )
then
FileWriter.writer("Counter Threshold Reached : " + $cnt ) ;
end
Thanks
um trying to instrument a method to do the following task.
Task - Create a Map and insert values to the map
Adding System.out.println lines wouldn't cause any exception. But when i add the line to create the Map, it throws a cannotCompileException due to a missing ;. When i print the final string it doesn't seem to miss any. What am i doing wrong here.
public void createInsertAt(CtMethod method, int lineNo, Map<String,String> parameterMap)
throws CannotCompileException {
StringBuilder atBuilder = new StringBuilder();
atBuilder.append("System.out.println(\"" + method.getName() + " is running\");");
atBuilder.append("java.util.Map<String,String> arbitraryMap = new java.util.HashMap<String,String>();");
for (Map.Entry<String,String> entry : parameterMap.entrySet()) {
}
System.out.println(atBuilder.toString());
method.insertAt(1, atBuilder.toString());
}
String obtained by printing the output of string builder is,
System.out.println("prepareStatement is
running");java.util.Map arbitraryMap = new
java.util.HashMap();
Exception received is,
javassist.CannotCompileException: [source error] ; is missing
at javassist.CtBehavior.insertAt(CtBehavior.java:1207)
at javassist.CtBehavior.insertAt(CtBehavior.java:1134)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.createInsertAt(InstrumentationClassTransformer.java:126)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.instrumentMethod(InstrumentationClassTransformer.java:100)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.transform(InstrumentationClassTransformer.java:37)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:424)
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
at org.wso2.das.javaagent.instrumentation.Agent.premain(Agent.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:382)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:397)
Caused by: compile error: ; is missing
at javassist.compiler.Parser.parseDeclarationOrExpression(Parser.java:594)
at javassist.compiler.Parser.parseStatement(Parser.java:277)
at javassist.compiler.Javac.compileStmnt(Javac.java:567)
at javassist.CtBehavior.insertAt(CtBehavior.java:1186)
... 15 more
(Is there any way to debug these kind of issues.) Some help please.....
Javassist's compiler doesn't support generics. Either remove or comment them out:
.append("java.util.Map arbitraryMap = new java.util.HashMap();")
or
.append("java.util.Map/*<String,String>*/ arbitraryMap = new java.util.HashMap/*<String,String>*/();")
The latter is useful as comment for yourself only, of course, it has no special meaning for Javassist.