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]
 
     
    