How to handle a NullPointerException? - java

I'm quite new to Java and stuck with handling NullPointerException -
I have a method as follows in order to build a HTTP Request as follows -
``
public static Http.Request Requester(String pingpoint) {
final String endPoint = URLBuilder.constructPing(pingpoint);
return BackendHttpRequest
.GET()
.pingURL(endPoint)
.build();
}
``
I don't want users to provide -
"~" - A tilde as an input
null - No null input
If user provides either of the above inputs we need to handle them as a NullPointerException.
What I'm trying to do -
``
public static Http.Request Requester(String pingpoint) {
try {
if(pingpoint != && pingpoint.equals("~")) {
final String endPoint = URLBuilder.constructPing(pingpoint);
return BackendHttpRequest
.GET()
.pingURL(endPoint)
.build();
}
} catch(NullPointerException e) {
System.out.println("NullPointerException thrown!");
}
}
``
However, Intellij is point to an error at the very end of curly braces to return a value of HTTP Request. I'm not sure what to return.
Any teachings on this will be really helpful! Thanks in advance.

probably you want to throw exception, like this:
public static Http.Request Requester(String pingpoint) {
if (pingpoint == null || pingpoint.equals("~"))
throw new NullPointerException();
final String endPoint = URLBuilder.constructPing(pingpoint);
return BackendHttpRequest.GET().pingURL(endPoint).build();
}

Related

Entity from Optional Object (Java 8)

I am having some issue while trying to pull an entity out of an ArrayList that holds and Optional. When I do a breakpoint I get the return below the code. I know I am close but lack the knowledge on how to pull the GrandClientDataCore#9463 out of the data being returned to me.
Edited to add the previous line before the for loop.
Error occured: java.util.Optional cannot be cast to net.glmhc.dmhwebservices.entities.GrandClientDataCores.
List<GrandClientDataCores> grandClientDataCoresList = getGrandClientDataCoreList(submitMode, grandClientDataCoreId);
for (GrandClientDataCores grandClientDataCores : grandClientDataCoresList) {
CDCPAErrors request = new CDCPAErrors();
request.setI(this.service.getRequestInfo(grandClientDataCores, submitMode, staff));
logToFile(outDir, String.format("req_%s.xml", new Object[] {grandClientDataCores}), request);
CDCPAErrorsResponse response = (CDCPAErrorsResponse)
getWebServiceTemplate().marshalSendAndReceive(getWebServiceUri(), request,
(WebServiceMessageCallback) new SoapActionCallback("http://tempuri.org/CDCPAErrors"));
logToFile(outDir, String.format("res_%s.xml", new Object[] {grandClientDataCoreId}), response);
DmhServicesCdcResponse responseObj = getResponse(submitMode, response);
this.service.saveResponse(grandClientDataCores, submitMode, responseObj, staff);
responses.add(responseObj);
}
This is the getGrandClientDataCoreList
protected List<GrandClientDataCores> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
List<GrandClientDataCores> grandClientDataCoresList;
try {
grandClientDataCoresList = (List<GrandClientDataCores>) this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
} catch ( Exception ex) {
throw new Exception(ex);
}
if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
throw new NoDataException("No CDC record to validate.");
}
return grandClientDataCoresList;
}
You have to invoke get() on the optional to retrieve its value. You cannot just cast Optional<T> to something else. According to the debug image, the declaration of grandClientDataCoresList looked like this:
List<Optional<GrandClientDataCores>> grandClientDataCoresList ...
Therefore you need something like this:
for (Optional<GrandClientDataCores> gcdcOpt: grandClientDataCoresList) {
GrandClientDataCores gcdc = gcdcOpt.get();
....
values in grandClientDataCores are of type Optional<GrandClientDataCores>.
Your actual error is here:
protected List<GrandClientDataCores> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
List<GrandClientDataCores> grandClientDataCoresList;
try {
grandClientDataCoresList = (List<GrandClientDataCores>) this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This cast is invalid
} catch ( Exception ex) {
throw new Exception(ex);
}
if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
throw new NoDataException("No CDC record to validate.");
}
return grandClientDataCoresList;
}
You will find that the actual type returned by this.service.getGrandClientDataCoreList is List<Optional<GrandClientDataCores>> so you must update your code accordingly, in a number of places. For starters...
protected List<Optional<GrandClientDataCores>> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
List<Optional<GrandClientDataCores>> grandClientDataCoresList;
try {
grandClientDataCoresList = this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
} catch ( Exception ex) {
throw new Exception(ex);
}
if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
throw new NoDataException("No CDC record to validate.");
}
return grandClientDataCoresList;
}
and everywhere that you invoke this method.
use the "get()" function of Optional, which will retrieve the object itself.
pay attention it will throw an exception if no object was populated into this Optional.
GrandClientDataCores values in List are wrapped with Optional, so you have to check if value present:
grandClientDataCores.isPresent()
and if it is then just get it:
grandClientDataCores.get();
Alternatively, you can do something like that:
grandClientDataCores.orElse(new GrandClientDataCores())
And I recommend to read this

Is this a redundant NullPointerException catch?

Below Spring REST code returns List for a given ticketId.
Could a NullPointerException be thrown in this code ?
NullPointerException explicitly caught in TicketController:
catch (NullPointerException nullPointerException) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, nullPointerException.getMessage(), nullPointerException);
}
The thinking may have been when checking for null on the ticket id:
if (ticketId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticket id cannot be null");
}
the expectation is that a NullPointerException would be thrown but instead a ResponseStatusException is thrown ?
If the variable ticketId is a path parameter it can never be null as hit the base url / without a ticketId I receive:
There was an unexpected error (type=Method Not Allowed, status=405).
Entire source:
#RestController
public class TicketController {
private final TicketServiceImpl ticketServiceImpl;
public TicketController(TicketServiceImpl ticketServiceImpl) {
this.ticketServiceImpl = ticketServiceImpl;
}
#GetMapping(path = "/{ticketId}")
public ResponseEntity<List<TicketResponse>> getTicketsById(
#PathVariable("ticketId") final Long ticketId) {
try {
final List<TicketResponse> ticketsById = ticketServiceImpl.getAll(ticketId);
return new ResponseEntity<>(ticketsById, HttpStatus.OK);
}
catch (NullPointerException nullPointerException) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, nullPointerException.getMessage(), nullPointerException);
}
catch (TicketNotFoundException ticketNotFoundException) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Ticket id not found",
ticketNotFoundException);
}
}
}
#Service
public class TicketServiceImpl implements TicketService {
private final TicketRepository ticketRepository;
public TicketServiceImpl(TicketRepository ticketRepository) {
this.ticketRepository = ticketRepository;
}
#Override
public List<TicketResponse> getAll(Long ticketId) {
final List<TicketResponse> ticketResponselist = ticketRepository.findData(ticketId);
if (ticketId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticket id cannot be null");
}
else if (ticketResponselist.size() == 0) {
throw new TicketNotFoundException("ticket not found");
}
else {
return ticketResponselist;
}
}
}
#Repository
public interface TicketRepository {
public List<TicketResponse> findData(Long ticketId);
}
The if (ticketId == null) check should happen before the ticketRepository.findData(ticketId); is called.
Otherwise, the validation doesn't make sense.
Also, as a side note, catching NullPointerException is a bad practice. The reason is that having a null pointer exception thrown is mostly a sign of a coding smell. The code should be null-safe, by either using e.g. Optional or having a proper validation at the method level. In this case, it would be at the route level (which is the external input). From that point onward, if the validation is set, you're dealing with non nullable id.
This is also somehow related to returning null from a method, which is also a bad practice, since it requires a check in every method which then uses the returned value. This would pollute the code, will introduce a new level of abstraction, and will generally lead to nasty bugs.
NullPointerException check is not required in this case.
Side note : Its better to use the super type when passing as a method parameter until and unless you are pretty sure that no exception will be thrown instead of yours.

Java Spring #GetMapping not found

I write two functions #GetMapping in one class. Function getProcessImage is working but Function hello is not working.
NOT FOUND 404
I write two functions #GetMapping in one class. Function getProcessImage is working but Function hello is not working. It is not found 404.
#GetMapping(value = "/{processInsID}/{containerId}")
public ServiceResponse<String> getProcessImage(#PathVariable("processInsID") long procInstId,
#PathVariable("containerId") String containerId) {
AuthenticationInfo bpmAuthenInfo = new AuthenticationInfo(env.getProperty("jbpm.url"),
env.getProperty("jbpm.username"), env.getProperty("jbpm.password"), "");
String result = jbpmService.getImageProcessInProgess(bpmAuthenInfo, containerId, procInstId);
try {
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_SUCCESS,
Constant.ServiceResponse.MSG_SUCCESS, result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_ERROR, e.getMessage(), null);
}
}
#GetMapping(value = "/image/")
public ServiceResponse<String> hello() {
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_ERROR,"okok", null);
}
Either you need to change your getMapping to /image (i.e remove / ) or you need to add image/ in your url path.I suggest you to remove / in your code as /image

Bad return type in method reference: Cannot convert Employee to Optional<U>

I am trying to write a lambda function that gets employee location preference and have the code sample below.
But for my lambda function I get a compilation error at flatMap(this::buildEmployeeGeolocation)
saying Bad return type in method reference: cannot convert com.abc.EmployeeGeolocation to java.util.Optional<U>.
What am I missing here?
public Optional<EmployeeGeolocation> getEmployee(final SessionId sessionId) {
return Optional.ofNullable(employeePreferencesStore.getEmployeeAccountPreferences(sessionId))
.map(preferences -> preferences.getPreference(PreferenceKey.Location))
.filter(StringUtils::isNotBlank)
.map(this::readEmployeelocation)
.flatMap(this::buildEmployeeGeolocation);
}
private Optional<EncryptedGeolocation> readEmployeeLocation(#NonNull final String encryptedGeolocation) {
try {
return Optional.ofNullable(objectMapper.readValue(encryptedGeolocation, EmployeeGeolocation.class));
} catch (final IOException e) {
log.error("Error while reading the encrypted geolocation");
throw new RuntimeException(e);
}
}
private EmployeeGeolocation buildEmployeeGeolocation(#NonNull final EncryptedGeolocation unditheredEncryptedGeolocation) {
return EmployeeGeolocation.builder()
.latitude(10.0)
.longitude(10.0)
.accuracy(1.0)
.locationType(ADDRESS)
.build();
}
It seems like what you really need to do is swap the map and flatMap. Change the code
.map(this::readEmployeeLocation)
.flatMap(this::buildEmployeeGeolocation);
to
.flatMap(this::readEmployeeLocation) // since you already have an Optional<String>
.map(this::buildEmployeeGeolocation); // above results in Optional<EncryptedGeolocation>
Important: Inferred from the code Optional.ofNullable(...).map(...).filter(StringUtils::isNotBlank), that it would result in an Optional<String> until this operation.

Is this a bad practice?

Is the following code considered a bad practice? Do you think it can be done otherwise?
The goal is to always update the status, either with success (i.e invocation to service.invoke(id);returns normally ) or with failure...
#Autowired
private Service service;
public void onMessage(Message message) {
String id = null;
String status = "FAILED";
try {
id = ((TextMessage) message).getText();
status = service.invoke(id); //can throw unchecked exception
} catch (final JMSException e) {
throw new RuntimeException(e);
} finally {
if (StringUtils.isNumeric(id)) {
service.update(id, status);
}
}
}
It depends on your Use-case, whether you have to perform a step or not based on previous step. Using finally may execute your second step regardless what exception you may receive.
I would recommend having the second step outside try...catch block so that you'll update only when you have got any exception you've Expected and continue to your second step, else, your method will throw and exit.
i think you should not use implementation of message listener , you should wire them independent of spring tech . just pojo based . use <jms:listener-container > with <jms:listener>

Categories

Resources