I am using spring-boot with hibernate validator
I have a controller annotated with #Validated and I want to validate all the params in my APIs.
One of the annotation is not working(I debugged and it just never being checked as if it is not annotated at all).
public MyResponse getPolicyCounters(#RequestBody #Valid MyRequest request) throws Exception {
The MyRequest class looks like this:
#Valid
public class MyRequest{
boolean shouldSumSubRules;
private #Valid RulesSelector rules;
The RuleSelector class is an interface and looks like this:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
#JsonSubTypes({
#JsonSubTypes.Type(value = RulesStaticList.class, name = "list"),
#JsonSubTypes.Type(value = RulesDynamicList.class, name = "criteria")
})
#Valid
public interface RulesSelector {
}
The RuleStaticList class looks like this:
#Valid
public class RulesStaticList extends ArrayList<#Valid RuleReference> implements RulesSelector {
}
The RuleRefrence class looks like this:
#JsonDeserialize(using = RuleReferenceDeserializer.class)
#Valid
public interface RuleReference {
RuleReferenceKind getKind();
}
final class RuleReferenceDeserializer extends StdDeserializer<RuleReference> {
public RuleReferenceDeserializer() {
super(RuleReference.class);
}
#Override
public RuleReference deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String fieldName = p.nextFieldName();
switch (fieldName) {
case "tag":
return p.readValueAs(RuleReferenceByTag.class);
case "special":
return p.readValueAs(RuleReferenceBySpecial.class);
default:
throw ctxt.wrongTokenException(p, RuleReference.class, JsonToken.FIELD_NAME, "");
}
}
}
I have 2 implementation for RuleReference one of them is RuleReferenceByTag and it looks like this:
#Valid
public class RuleReferenceByTag implements RuleReference {
#Size(max = 128)
private String tag;
public RuleReferenceKind getKind() { return RuleReferenceKind.Tag; }
}
I added #Valid annotation everywhere I could but it still does not work.
What am I missing?
Other annotation in with different classes it does work but I could not solve this problem :/
It's pretty like params in #RequestMapping annotation, which narrows down the matching methods with query parameters. Instead, I want to achieve this with body parameters (like JSON-format). Do I need to implement a custom #RequestMapping annotation?
YOu can achieve it using #RequestBody. It matches payload with names specified in code.
https://www.baeldung.com/spring-request-response-body
You just have to use #RequestBody. Note that this not only allows POJO, you can use it with a Map too.
With a POJO:
#RequestMapping(value="/",method = RequestMethod.POST)
public String doSomething(#RequestBody MyDto dto) {
return service.requestOTP(dto.getField1(), dto.getField2());
}
With a Map:
#RequestMapping(value="/",method = RequestMethod.POST)
public String doSomething(#RequestBody Map<String, Object> body) {
return service.requestOTP(body.get("field1").toString(), body.get("field2").toString());
}
NOTE: If you would like to validate properties of an object used with #RequestBody, you can add #Valid annotation. For instance, the following will cascade the validation on the model and the models sub model fields(if found).
public class MyDto {
#NotNull
#Valid
private String field1;
private String field2;
//getters and setters
}
#RequestMapping(value="/",method = RequestMethod.POST)
public String doSomething(**#Valid** #RequestBody MyDto dto) {
return service.requestOTP(dto.getField1(), dto.getField2());
}
Check here for a brave introduction for #Valid https://www.logicbig.com/tutorials/java-ee-tutorial/bean-validation/cascaded-validation.html
I am trying to have a REST endpoint create a subtype of Widget when POSTing to it,
here is the base class for all Widgets
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "widgetType")
#JsonSubTypes({
#JsonSubTypes.Type(value = TextWidget.class, name = WidgetType.Constants.TEXT),
#JsonSubTypes.Type(value = ImageWidget.class, name = WidgetType.Constants.IMAGE),
#JsonSubTypes.Type(value = IndicatorWidget.class, name = WidgetType.Constants.INDICATOR),
#JsonSubTypes.Type(value = MapWidget.class, name = WidgetType.Constants.MAP),
#JsonSubTypes.Type(value = ChartWidget.class, name = WidgetType.Constants.CHART)
})
#Data
#Slf4j
public abstract class Widget {
...
}
this is the WidgetType enum:
public enum WidgetType {
TEXT(Constants.TEXT),
IMAGE(Constants.IMAGE),
INDICATOR(Constants.INDICATOR),
MAP(Constants.MAP),
CHART(Constants.CHART);
private final String type;
WidgetType(final String type) {
this.type = type;
}
public static class Constants {
public static final String TEXT = "TEXT";
public static final String IMAGE = "IMAGE";
public static final String INDICATOR = "INDICATOR";
public static final String MAP = "MAP";
public static final String CHART = "CHART";
}
}
and this is my Spring endpoint:
#RequestMapping(method = RequestMethod.POST)
public Optional<Widget> createWidget(#Valid final Widget widget) {
...
}
when hitting that endpoint it throws this exception:
{
"timestamp": 1493029336774,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.beans.BeanInstantiationException",
"message": "Failed to instantiate [....models.Widget]: Is it an abstract class?; nested exception is java.lang.InstantiationException",
"path": "...."
}
skimming through few solutions for my problem, I might have to manually register the subtypes, I might be wrong, but I think there must be a way to make it work with annotations, maybe I am missing something?
problem solved,
I was annotating my classes with Jackson annotation and forgot that I was sending multipart POST requests, that wasn't even going to Jackson.
The solution is as simple as this:
#RequestMapping(method = RequestMethod.POST)
public Optional<Widget> createWidget(#RequestBody final Widget widget) {
...
}
I'm trying to distinguish between null values and not provided values when partially updating an entity with PUT request method in Spring Rest Controller.
Consider the following entity, as an example:
#Entity
private class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/* let's assume the following attributes may be null */
private String firstName;
private String lastName;
/* getters and setters ... */
}
My Person repository (Spring Data):
#Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}
The DTO I use:
private class PersonDTO {
private String firstName;
private String lastName;
/* getters and setters ... */
}
My Spring RestController:
#RestController
#RequestMapping("/api/people")
public class PersonController {
#Autowired
private PersonRepository people;
#Transactional
#RequestMapping(path = "/{personId}", method = RequestMethod.PUT)
public ResponseEntity<?> update(
#PathVariable String personId,
#RequestBody PersonDTO dto) {
// get the entity by ID
Person p = people.findOne(personId); // we assume it exists
// update ONLY entity attributes that have been defined
if(/* dto.getFirstName is defined */)
p.setFirstName = dto.getFirstName;
if(/* dto.getLastName is defined */)
p.setLastName = dto.getLastName;
return ResponseEntity.ok(p);
}
}
Request with missing property
{"firstName": "John"}
Expected behaviour: update firstName= "John" (leave lastName unchanged).
Request with null property
{"firstName": "John", "lastName": null}
Expected behaviour: update firstName="John" and set lastName=null.
I cannot distinguish between these two cases, sincelastName in the DTO is always set to null by Jackson.
Note:
I know that REST best practices (RFC 6902) recommend using PATCH instead of PUT for partial updates, but in my particular scenario I need to use PUT.
Another option is to use java.util.Optional.
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Optional;
#JsonInclude(JsonInclude.Include.NON_NULL)
private class PersonDTO {
private Optional<String> firstName;
private Optional<String> lastName;
/* getters and setters ... */
}
If firstName is not set, the value is null, and would be ignored by the #JsonInclude annotation. Otherwise, if implicitly set in the request object, firstName would not be null, but firstName.get() would be. I found this browsing the solution #laffuste linked to a little lower down in a different comment (garretwilson's initial comment saying it didn't work turns out to work).
You can also map the DTO to the Entity with Jackson's ObjectMapper, and it will ignore properties that were not passed in the request object:
import com.fasterxml.jackson.databind.ObjectMapper;
class PersonController {
// ...
#Autowired
ObjectMapper objectMapper
#Transactional
#RequestMapping(path = "/{personId}", method = RequestMethod.PUT)
public ResponseEntity<?> update(
#PathVariable String personId,
#RequestBody PersonDTO dto
) {
Person p = people.findOne(personId);
objectMapper.updateValue(p, dto);
personRepository.save(p);
// return ...
}
}
Validating a DTO using java.util.Optional is a little different as well. It's documented here, but took me a while to find:
// ...
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
// ...
private class PersonDTO {
private Optional<#NotNull String> firstName;
private Optional<#NotBlank #Pattern(regexp = "...") String> lastName;
/* getters and setters ... */
}
In this case, firstName may not be set at all, but if set, may not be set to null if PersonDTO is validated.
//...
import javax.validation.Valid;
//...
public ResponseEntity<?> update(
#PathVariable String personId,
#RequestBody #Valid PersonDTO dto
) {
// ...
}
Also might be worth mentioning the use of Optional seems to be highly debated, and as of writing Lombok's maintainer(s) won't support it (see this question for example). This means using lombok.Data/lombok.Setter on a class with Optional fields with constraints doesn't work (it attempts to create setters with the constraints intact), so using #Setter/#Data causes an exception to be thrown as both the setter and the member variable have constraints set. It also seems better form to write the Setter without an Optional parameter, for example:
//...
import lombok.Getter;
//...
#Getter
private class PersonDTO {
private Optional<#NotNull String> firstName;
private Optional<#NotBlank #Pattern(regexp = "...") String> lastName;
public void setFirstName(String firstName) {
this.firstName = Optional.ofNullable(firstName);
}
// etc...
}
There is a better option, that does not involve changing your DTO's or to customize your setters.
It involves letting Jackson merge data with an existing data object, as follows:
MyData existingData = ...
ObjectReader readerForUpdating = objectMapper.readerForUpdating(existingData);
MyData mergedData = readerForUpdating.readValue(newData);
Any fields not present in newData will not overwrite data in existingData, but if a field is present it will be overwritten, even if it contains null.
Demo code:
ObjectMapper objectMapper = new ObjectMapper();
MyDTO dto = new MyDTO();
dto.setText("text");
dto.setAddress("address");
dto.setCity("city");
String json = "{\"text\": \"patched text\", \"city\": null}";
ObjectReader readerForUpdating = objectMapper.readerForUpdating(dto);
MyDTO merged = readerForUpdating.readValue(json);
Results in {"text": "patched text", "address": "address", "city": null}
Note that text and city were patched (city is now null) and that address was left alone.
In a Spring Rest Controller you will need to get the original JSON data instead of having Spring deserialize it in order to do this. So change your endpoint like this:
#Autowired ObjectMapper objectMapper;
#RequestMapping(path = "/{personId}", method = RequestMethod.PATCH)
public ResponseEntity<?> update(
#PathVariable String personId,
#RequestBody JsonNode jsonNode) {
RequestDTO existingData = getExistingDataFromSomewhere();
ObjectReader readerForUpdating = objectMapper.readerForUpdating(existingData);
RequestDTO mergedData = readerForUpdating.readValue(jsonNode);
...
}
Use boolean flags as jackson's author recommends.
class PersonDTO {
private String firstName;
private boolean isFirstNameDirty;
public void setFirstName(String firstName){
this.firstName = firstName;
this.isFirstNameDirty = true;
}
public String getFirstName() {
return firstName;
}
public boolean hasFirstName() {
return isFirstNameDirty;
}
}
Actually,if ignore the validation,you can solve your problem like this.
public class BusDto {
private Map<String, Object> changedAttrs = new HashMap<>();
/* getter and setter */
}
First, write a super class for your dto,like BusDto.
Second, change your dto to extend the super class, and change the
dto's set method,to put the attribute name and value to the
changedAttrs(beacause the spring would invoke the set when the
attribute has value no matter null or not null).
Third,traversal the map.
I have tried to solve the same problem. I found it quite easy to use JsonNode as the DTOs. This way you only get what is submitted.
You will need to write a MergeService yourself that does the actual work, similar to the BeanWrapper. I haven't found an existing framework that can do exactly what is needed. (If you use only Json requests you might be able to use Jacksons readForUpdate method.)
We actually use another node type as we need the same functionality from "standard form submits" and other service calls. Additionally the modifications should be applied within a transaction inside something called EntityService.
This MergeService will unfortunately become quite complex, as you will need to handle properties, lists, sets and maps yourself :)
The most problematic piece for me was to distinguish between changes within an element of a list/set and modifications or replacements of lists/sets.
And also validation will not be easy as you need to validate some properties against another model (the JPA entities in my case)
EDIT - Some mapping code (pseudo-code):
class SomeController {
#RequestMapping(value = { "/{id}" }, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void save(
#PathVariable("id") final Integer id,
#RequestBody final JsonNode modifications) {
modifierService.applyModifications(someEntityLoadedById, modifications);
}
}
class ModifierService {
public void applyModifications(Object updateObj, JsonNode node)
throws Exception {
BeanWrapperImpl bw = new BeanWrapperImpl(updateObj);
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
Object valueToBeUpdated = node.get(fieldName);
Class<?> propertyType = bw.getPropertyType(fieldName);
if (propertyType == null) {
if (!ignoreUnkown) {
throw new IllegalArgumentException("Unkown field " + fieldName + " on type " + bw.getWrappedClass());
}
} else if (Map.class.isAssignableFrom(propertyType)) {
handleMap(bw, fieldName, valueToBeUpdated, ModificationType.MODIFY, createdObjects);
} else if (Collection.class.isAssignableFrom(propertyType)) {
handleCollection(bw, fieldName, valueToBeUpdated, ModificationType.MODIFY, createdObjects);
} else {
handleObject(bw, fieldName, valueToBeUpdated, propertyType, createdObjects);
}
}
}
}
Maybe too late for an answer, but you could:
By default, don't unset 'null' values. Provide an explicit list via query params what fields you want to unset. In such a way you can still send JSON that corresponds to your entity and have flexibility to unset fields when you need.
Depending on your use case, some endpoints may explicitly treat all null values as unset operations. A little bit dangerous for patching, but in some circumstances might be an option.
Another solution would be to imperatively deserialize the request body. By doing it, you will be able to collect user provided fields and selectively validate them.
So your DTO might look like this:
public class CatDto {
#NotBlank
private String name;
#Min(0)
#Max(100)
private int laziness;
#Max(3)
private int purringVolume;
}
And your controller can be something like this:
#RestController
#RequestMapping("/api/cats")
#io.swagger.v3.oas.annotations.parameters.RequestBody(
content = #Content(schema = #Schema(implementation = CatDto.class)))
// ^^ this passes your CatDto model to swagger (you must use springdoc to get it to work!)
public class CatController {
#Autowired
SmartValidator validator; // we'll use this to validate our request
#PatchMapping(path = "/{id}", consumes = "application/json")
public ResponseEntity<String> updateCat(
#PathVariable String id,
#RequestBody Map<String, Object> body
// ^^ no Valid annotation, no declarative DTO binding here!
) throws MethodArgumentNotValidException {
CatDto catDto = new CatDto();
WebDataBinder binder = new WebDataBinder(catDto);
BindingResult bindingResult = binder.getBindingResult();
List<String> patchFields = new ArrayList<>();
binder.bind(new MutablePropertyValues(body));
// ^^ imperatively bind to DTO
body.forEach((k, v) -> {
patchFields.add(k);
// ^^ collect user provided fields if you need
validator.validateValue(CatDto.class, k, v, bindingResult);
// ^^ imperatively validate user input
});
if (bindingResult.hasErrors()) {
throw new MethodArgumentNotValidException(null, bindingResult);
// ^^ this can be handled by your regular exception handler
}
// Here you can do normal stuff with your catDto.
// Map it to cat model, send to cat service, whatever.
return ResponseEntity.ok("cat updated");
}
}
No need for Optional's, no extra dependencies, your normal validation just works, your swagger looks good. The only problem is, you don't get proper merge patch on nested objects, but in many use cases that's not even required.
Probably to late but following code works for me to distinguish between null and not provided values
if(dto.getIban() == null){
log.info("Iban value is not provided");
}else if(dto.getIban().orElse(null) == null){
log.info("Iban is provided and has null value");
}else{
log.info("Iban value is : " + dto.getIban().get());
}
I currently facing an issue with the deserialization of json into an polymorphic type.
This is my controller which receives a RecommendedVirtualEditionParam.
#RequestMapping(
value = "/sortedEdition",
method = RequestMethod.POST,
headers = { "Content-type=application/json;charset=UTF-8"
})
public String getSortedRecommendedVirtualEdition(
Model model,
#RequestBody RecommendVirtualEditionParam params) {
//Do Stuff
}
RecommendedVirtualEditionParam is a container:
public class RecommendVirtualEditionParam {
private final String acronym;
private final String id;
private final Collection<Property> properties;
public RecommendVirtualEditionParam(
#JsonProperty("acronym") String acronym,
#JsonProperty("id") String id,
#JsonProperty("properties") Collection<Property> properties) {
this.acronym = acronym;
this.id = id;
this.properties = properties;
}
//Getters
}
Property is a polymorphic type and I believe it's the one giving my problems.
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = SpecificTaxonomyProperty.class, name = "specific-taxonomy")
})
public abstract class Property {
public Property() {
}
//Other methods
}
The sub type:
public class SpecificTaxonomyProperty extends Property {
private final String acronym;
private final String taxonomy;
public SpecificTaxonomyProperty(
#JsonProperty("acronym") String acronym,
#JsonProperty("taxonomy") String taxonomy) {
this.acronym = acronym;
this.taxonomy = taxonomy;
}
The json being send on requests:
{
acronym: "afs"
id: "167503724747"
properties: [
{
type: "specific-taxonomy",
acronym: "afs",
taxonomy: "afs"
}
]
}
When I run it like this I get a org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:149) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:180) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:95) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
I believe there is something wrong with with the way I setup my Property class that makes it unable to deserialize. Any has a clue and give me an hand?
I managed to fix my problem.
Before posting, I had looked around and a lot of answers pointed to the class I wanted to deserialize having multiple setters for the same attribute. I didn't pay much attention to it, since my attributes were final, I didn't have any setters for them.
https://stackoverflow.com/a/19444874/2364671
But I had a method called setUserWeight(RecommendedWeights weights) which didn't set any attributes of Property, but after renaming it, my problem was fixed.
I don't quiet understand the reason for this odd behavior and would love some light about it.