How can I prevent a null RequestParam raising an exception? - spring

I'm working in a Spring Boot environnement using Kotlin. I made a controller with a method annotated with #GetMapping. This method have some parameters of type #RequestParam declared as Double type. If I try to call my method without providing these parameters, my code raises the following exception:
java.lang.IllegalStateException: Optional double parameter 'latitude' is present but cannot be translated into a null value due to being declared as a primitive type.
I assume that the parameters have default value (probably 0.0), but Kotlin need an object which can be null, so the exception is raised.
All works fine if I provide the parameters, but I want my code working if no parameters are provided.
How can I avoid this exception?
Here's how my controller looks like:
#RestController
#RequestMapping("/api/stations")
class StationController {
#GetMapping
fun findAll(#RequestParam(value = "latitude", required = false) currentLatitude: Double,
#RequestParam(value = "longitude", required = false) currentLongitude: Double): ResponseEntity<List<Entity>> {
//Method body
}

Maybe the following part of the documentation regarding basic types will help you:
On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed.
Your guess might be correct then. Try using Double? and it should be ok.

Related

How do Specifications with Spring Data JPA really work?

For example, I have helper class with Specifications. Here is the example of one:
public static Specification<Player> filterByName(String name) {
return ((root, query, criteriaBuilder) ->
name == null ? null : criteriaBuilder.like(root.get("name"), "%" + name + "%"));
}
I use them later to call Repository. I don't understand how objects of root, query, criteriaBuiler "appear" in he method above if the are not being created by me.
I do appreciate your answer a lot!
This happens because from your declaration your method has to return an object implementing the Specification interface that contains the abstract toPredicate method having three parameters. What Java compiler does is the type inference of the returned value and of the three arguments from the lambda expression assigning type to them according to the toPredicate method's declaration, ending this process with success.

Decompose incoming JSON to Objects by fields with Spring MVC

I need to decompose my incoming JSON by fields in me REST Controller with Spring Boot.
My request body:
{
"text": "my text",
"myEnum": "VALUE1"
}
And my controller:
#PatchMapping("/{id}")
Object updateEntity(#PathVariable Long id, String text, MyEnum myEnum) {
/* ... */
}
#RequestParam doesn't work because it's just for query string params, #RequestBody doesn't work too because it handle whole body. But I need decompose incoming body by fields and inject into controller. I know what I can use Map <String, String> for this, but I would like validate my incoming fields, and I have the fields with difference types. And I don't want to create one class by incoming body for each controller.
If I haven't misunderstood your requirement, the usual way to deal with incoming JSON is to define a class that reflects your expected input, and make that the controller method parameter annotated as RequestBody.
Spring Boot, by default, uses Jackson to deserialize to your class, and so if you use matching property names then you won't need any special annotations or setup. I think enums will be handled by default, as are other types (though you may need to provide some guidance for strings representing dates or timestamps). Any bad value will fail deserialisation, which I think you can handle in ControllerAdvice (though you'll want to double check that)

mocking a method with parameter as LIST type

I want to mock the below mentioned method.
public class MockClass {
public boolean ToBeMocked(Cinput, Coutput, List<CIOChain<Cinput, Coutput>>)
}
What should be in place of ?? in below mentioned code ?
Easymock.expect(MockClassObject.ToBeMocked(Cinput.class, Coutput.class, ??)).andReturn(true);
At the Class level, all List interfaces are the same regardless of the generic type, due to type erasure; they are only different at compile time.
So it's just List.class in place of ??.
That is,
Easymock.expect(MockClassObject.ToBeMocked(Cinput.class, Coutput.class, List.class)).
andReturn(true);
In the scope of mocking, you should really be specifying the objects that you expect to be passed to that method, like:
Easymock.expect(MockClassObject.ToBeMocked(cInputObj, cOutputObj, listObj)).
andReturn(true);
If for some reason you can't do that, you can use isA/anyObject variants:
Easymock.expect(MockClassObject.ToBeMocked(isA(Cinput.class), isA(Coutput.class), isA(List.class))).
andReturn(true);

What is the difference between Collections from casted from a HashMap over entryset() and casted ArrayList for Jackson?

I am developing a Spring Rest application. One of my methods is that:
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody
Collection<Configuration> getConfigurationInJSON() {
Collection<Configuration> confList = new ArrayList<Configuration>();
...
I fill my confList and send it for GET request, it works. However when I want to keep that confList in a HashMap and send it after got it's entrySet as like that:
#RequestMapping(method = RequestMethod.GET)
public
#ResponseBody
Collection<Configuration> getAllConfigurationsInJSON() {
return configurationMap.values();
}
It gives me 406 error, so it means there is a wrong. What are the differences between that collections and why the second one is not same with first example?
For the sake of simplicity, can you just copy the values() collection?
new ArrayList<Configuration>(configurationMap.values());
Only thing that comes to my mind is that Spring expects mutable collection, but don't really understand why. Hard to say without debugging, try enabling org.springframework.web full logging.
The obvious difference is that configurationMap.values() is a Set.
You need to check if the JSON marshaller expects a List to be returned and is not able to marshal Set instances, as the marshaller will check the actual type of the returned value instead of the declared return type of the method, which is Collection.
By the way, isn't there any clue in the logs about this ?

Groovy validation problem

I have a groovy system configured using tomcat and Oracle 10g.
I have a groovy class which defines an follows: (reduced version)
class ChangeTicket {
static constraints = {
chngNr(nullable:false)
}
String chngNr
}
My controller has defined a save method:
if (changeTicketInstance.validate() && !changeTicketInstance.hasErrors() && changeTicketInstance.save()) {
flash.message = "changeTicket.created"
...
}
As far as I know the save method calls by default the validate method in order to
know if the constraints are fullfilled or not therefore the validate method call is redundant. Anyway, when the save is performed an exception will be thrown if the field chngNr is NULL.
In fact the field cannot be empty (NULL) because I've defined the constraint (nullable:false).
What am I doing wrong here?
Thanks in advance,
Luis
The validate call should fail if chngNr is NULL. Some databases do not consider an empty string ("") null (HSQL). If you are binding chngNr to changeTicketInstance using params from a form it is getting assigned an empty string as a value and in that case you would want your constraint to be:
chngNr(blank:false)
Also, save() wont throw an Exception unless you use save(flush:true). Hibernate queues up the changes and, unless you flush, wont throw an actual exception.
try this:
chngName(blank:false,nullable:false)
:-)

Resources