How to create a custom annotated validation that has a param in spring boot? [duplicate] - spring

This question already has an answer here:
How to use an annotation element inside a custom constraint validator
(1 answer)
Closed 4 months ago.
Is it possible to pass a value when using a custom annotated validation? The logic is different depending on the param value. In the example below, the chill room may require the key-value pairs to include "snack" : "" with max length 10, min length 1 similar to the #Size(min = 1, max = 10). I'm implementing the ConstraintValidator and set up the interface.
i.e.
#ConcertValidation(dressingRoom = "chill")
private List<Map<String, String>> json;

Inside the initialize method of the ConstraintValidator implementation, you can capture the value from annotation. For example:
class ConcertValidator implements ConstraintValidator<ConcertValidation, List<Map<String, String>>> {
String dressingRoom;
#Override
public void initialize(ConcertValidation constraintAnnotation) {
dressingRoom = constraintAnnotation.dressingRoom();
}
#Override
public boolean isValid(List<Map<String, String>> value, ConstraintValidatorContext context) {
boolean isValid = false;
//TODO implement your logic depending on dressingRoom value
return isValid;
}
}

In the interface for the validator, include:
//default code
pubilc #interface ConcertValidation{
// default code
String dressingRoom() default "";
}
In the validator class, you must initialize the params you want to pass to use them in your logic for the isValid() method;
// global variables
private String dressingRoom;
#Override
public void initialize(ConcertValidation concertValidationConstraint){
this.dressingRoom = concertValidationConstraint.dressingRoom();
}
Whenever you use the custom annotation validation, just pass the params.
#ConcertValidation(dressingRoom = "chill")
private List<Map<String, String>> json;

Related

Spring Boot/Java Mapping Enum Values to RequestParam [duplicate]

This question already has answers here:
Spring's #RequestParam with Enum
(9 answers)
Closed 3 years ago.
I have an Enum like below
public enum Customer {
RETAIL("retail"),
FREELANCER("FreeLancer"),
MARKET("market"),
PUBLICATION("publication");
private String contentType;
private static final Map<String,Customer> contentTypeMap;
public String getContentType(){
return this.contentType;
}
static {
Map<String,Customer> map = new ConcurrentHashMap<>();
for(Customer type : Customer.values ()){
map.put (type.getContentType (),type);
}
contentTypeMap = map;
}
Customer(String contentType){
this.contentType=contentType;
}
public static Customer getContentType(String contentType){
return contentTypeMap.get (contentType);
}
}
This enum represents the type of customer.
We have an API that return the customer details
#RequestMapping(value="/getData", method=RequestMethod.GET, produces="application/json")
public BatchResponse triggerBatchJob(
#RequestParam(value="updateFrom", required=false) #DateTimeFormat(pattern="yyyyMMdd") String updateFrom,
#RequestParam(value="updateTo", required=false) #DateTimeFormat(pattern="yyyyMMdd") String updateTo,
#RequestParam(value="customerType") (VALIDATE_HERE)String customerType) {
// ...
}
I need to validate the customerType value to be the ones present in the Enum, Is there a way to validate the same with the method declaration as I have done in the case of date rather than method body by using getContentType method or something.
Please help.
Change your method to following:
#RequestMapping(value="/getData", method=RequestMethod.GET, produces="application/json")
public BatchResponse triggerBatchJob(
#RequestParam(value="updateFrom", required=false) #DateTimeFormat(pattern="yyyyMMdd") String updateFrom,
#RequestParam(value="updateTo", required=false) #DateTimeFormat(pattern="yyyyMMdd") String updateTo,
#RequestParam(value="customerType") CustomerType customerType) {
// ...
}
i.e. customerType type should be CustomerType not String. Now only values those match enum will be mapped.
Note:- The values will have to be provided is specific format i.e. enum name itself e.g. in your case FREELANCER,RETAIL, PUBLICATION etc values should be passed in request.
Edit
As requested by OP below is customizing the enum handling from String:
Add #initBinder in the controller and add following method:
#InitBinder
public void initBinder(final WebDataBinder webdataBinder) {
webdataBinder.registerCustomEditor(Customer.class, new CustomerConverter());
}
and declare a converter class as below:
import java.beans.PropertyEditorSupport;
public class CustomerConverter extends PropertyEditorSupport{
public void setAsText(final String text) throws IllegalArgumentException {
System.out.println("--->"+Customer.getContentType(text));
setValue(Customer.getContentType(text));
}¡¡
}
Added System.out.println to show that value is interpreted and printed as expected.
A simple null check will do
Customer customer = Customer.getContentType(customerType);
if (customer == null) {
throw new Exception("Invalid Customer type");// use validation exception
}

Jackson #JsonFilter is not getting applied when used at field or method level

I am using Spring version 4.3.3 and Jackson version 2.8.3. I am trying to filter out specific fields from an entity bean based on some custom logic that is determined at runtime. The #JsonFilter seems ideal for this type of functionality. The problem is that when I put it at the field or method level, my custom filter never gets invoked. If I put it at the class level, it gets invoked just fine. I don't want to use it at the class level though since then I would need to separately maintain the list of hardcoded field names that I want to apply the logic to. As of Jackson 2.3, the ability to put this annotation at the field level is supposed to exist.
Here is the most basic custom filter without any custom logic yet:
public class MyFilter extends SimpleBeanPropertyFilter {
#Override
protected boolean include(BeanPropertyWriter beanPropertyWriter) {
return true;
}
#Override
protected boolean include(PropertyWriter propertyWriter) {
return true;
}
}
Then I have the Jackson ObjectMapper configuration:
public class MyObjectMapper extends ObjectMapper {
public MyObjectMapper () {
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("myFilter", new MyFilter());
setFilterProvider(filterProvider);
}
}
Then finally I have my entity bean:
#Entity
public class Project implements Serializable {
private Long id;
private Long version;
#JsonFilter("myFilter") private String name;
#JsonFilter("myFilter") private String description;
// getters and setters
}
If I move the #JsonFilter annotation to the class level where #Entity is, the filter at least gets invoked, but when it is at the field level like in the example here, it never gets invoked.
I have the same need but after examining the unit tests I discovered that this is not the use-case covered by annotating a field.
Annotating a field invokes a filter on the value of the field not the instance containing the field. For example, imagine you have to classes, A and B, where A contains a field of type B.
class A {
#JsonFilter("myFilter") B foo;
}
Jackson applies "myFilter" to the fields in B not in A. Since your example contains fields of type String, which has no fields, Jackson never invokes your filter.
I have a need to exclude certain fields based on the caller's permissions. For example, an employee's profile may contain his taxpayer id, which is considered sensitive information and should only be serialized if the caller is a member of the Payrole department. Since I'm using Spring Security, I wish to integrate Jackson with the current security context.
public class EmployeeProfile {
private String givenName;
private String surname;
private String emailAddress;
#VisibleWhen("hasRole('PayroleSpecialist')")
private String taxpayerId;
}
The most obvious way to do this is to Jackson's filter mechanism but it has a few limitations:
Jackson does not support nested filters so adding an access filter prohibits using filters for any other purpose.
One cannot add Jackson annotations to existing, third-party classes.
Jackson filters are not designed to be generic. The intent is to write a custom filter for each class you wish to apply filtering. For example, I you need to filter classes A and B, then you have to write an AFilter and a BFilter.
For my use-case, the solution is to use a custom annotation introspector in conjunction with a chaining filter.
public class VisibilityAnnotationIntrospector extends JacksonAnnotationIntrospector {
private static final long serialVersionUID = 1L;
#Override
public Object findFilterId(Annotated a) {
Object result = super.findFilterId(a);
if (null != result) return result;
// By always returning a value, we cause Jackson to query the filter provider.
// A more sophisticated solution will introspect the annotated class and only
// return a value if the class contains annotated properties.
return a instanceof AnnotatedClass ? VisibilityFilterProvider.FILTER_ID : null;
}
}
This is basically a copy SimpleBeanProvider that replaces calls to include with calls to isVisible. I'll probably update this to use a Java 8 BiPredicate to make the solution more general but works for now.
This class also takes another filter as an argument and will delegate to it the final decision on whether to serialize the field if the field is visible.
public class AuthorizationFilter extends SimpleBeanPropertyFilter {
private final PropertyFilter antecedent;
public AuthorizationFilter() {
this(null);
}
public AuthorizationFilter(final PropertyFilter filter) {
this.antecedent = null != filter ? filter : serializeAll();
}
#Deprecated
#Override
public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider provider, BeanPropertyWriter writer) throws Exception {
if (isVisible(bean, writer)) {
this.antecedent.serializeAsField(bean, jgen, provider, writer);
} else if (!jgen.canOmitFields()) { // since 2.3
writer.serializeAsOmittedField(bean, jgen, provider);
}
}
#Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception {
if (isVisible(pojo, writer)) {
this.antecedent.serializeAsField(pojo, jgen, provider, writer);
} else if (!jgen.canOmitFields()) { // since 2.3
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
#Override
public void serializeAsElement(Object elementValue, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception {
if (isVisible(elementValue, writer)) {
this.antecedent.serializeAsElement(elementValue, jgen, provider, writer);
}
}
private static boolean isVisible(Object pojo, PropertyWriter writer) {
// Code to determine if the field should be serialized.
}
}
I then add a custom filter provider to each instance of ObjectMapper.
#SuppressWarnings("deprecation")
public class VisibilityFilterProvider extends SimpleFilterProvider {
private static final long serialVersionUID = 1L;
static final String FILTER_ID = "dummy-filter-id";
#Override
public BeanPropertyFilter findFilter(Object filterId) {
return super.findFilter(filterId);
}
#Override
public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) {
if (FILTER_ID.equals(filterId)) {
// This implies that the class did not have an explict filter annotation.
return new AuthorizationFilter(null);
}
// The class has an explicit filter annotation so delegate to it.
final PropertyFilter antecedent = super.findPropertyFilter(filterId, valueToFilter);
return new VisibilityPropertyFilter(antecedent);
}
}
Finally, I have a Jackson module that automatically registers the custom annotaion introspector so I don't have to add it to each ObjectMapper instance manually.
public class FieldVisibilityModule extends SimpleModule {
private static final long serialVersionUID = 1L;
public FieldVisibilityModule() {
super(PackageVersion.VERSION);
}
#Override
public void setupModule(Module.SetupContext context) {
super.setupModule(context);
// Append after other introspectors (instead of before) since
// explicit annotations should have precedence
context.appendAnnotationIntrospector(new VisibilityAnnotationIntrospector());
}
}
There are more improvements that can be made and I still have more unit tests to write (e.g., handling arrays and collections) but this is the basic strategy I used.
You can try this approach for the same purpose:
#Entity
#Inheritance(
strategy = InheritanceType.SINGLE_TABLE
)
#DiscriminatorColumn(
discriminatorType = DiscriminatorType.STRING,
length = 2
)
#Table(
name = "project"
)
#JsonTypeInfo(
use = Id.CLASS,
include = As.PROPERTY,
property = "#class"
)
#JsonSubTypes({
#Type(
value = BasicProject.class,
name = "basicProject"
),
#Type(
value = AdvanceProject.class,
name = "advanceProject"
)})
public abstract class Project {
private Long id;
private Long version;
}
#Entity
#DiscriminatorValue("AD")
public class AdvanceProject extends Project {
private String name;
private String description;
}
#Entity
#DiscriminatorValue("BS")
public class BasicProject extends Project {
private String name;
}
I don't think you will make it work. I was trying and these are results of my investigation, maybe it will be helpful.
First of all, as #Faron noticed, the #JsonFilterannotation is applied for the class being annotated not a field.
Secondly, I see things this way. Let's imagine, somewhere in Jackson internals you are able to get the actual field. You can figure out if there is the annotation using Java Reflection API. You can even get the filter name. Then you get to the filter and pass the field value there. But it happens at runtime, how will you get the corresponding JsonSerializer of the field type if you decide to serialize the field? It is impossible because of type erasure.
The only alternative I see is to forget about dynamic logic. Then you can do the following things:
1) extend JacksonAnnotationIntrospector (almost the same as implement AnnotationIntrospector but no useless default code) overriding hasIgnoreMarker method. Take a look at this answer
2) criminal starts here. Kinda weird way taking into account your initial goal but still: extend BeanSerializerModifier and filter out fields there. An example can be found here. This way you can define serializer that actually doesn't serialize anything (again, I understand how strange it is but maybe one will find it helpful)
3) similar to the approach above: define useless serializer based on BeanDescription implementing ContextualSerializer's createContextual method. The example of this magic is here
Thanks to this really good blog, I was able to use #JsonView to filter out specific fields from an entity bean based on some custom logic that is determined at runtime.
Since the #JsonFilter does not apply for the fields within a class, I found this to be a cleaner workaround.
Here is the sample code:
#Data
#AllArgsConstructor
public class TestEntity {
private String a;
#JsonView(CustomViews.SecureAccess.class)
private Date b;
#JsonView(CustomViews.SecureAccess.class)
private Integer c;
private List<String> d;
}
public class CustomViews {
public static interface GeneralAccess {}
public static interface SecureAccess {}
public static class GeneralAccessClass implements GeneralAccess {}
public static class SecureAccessClass implements SecureAccess, GeneralAccess {}
public static Class getWriterView(final boolean hasSecureAccess) {
return hasSecureAccess
? SecureAccessClass.class
: GeneralAccessClass.class;
}
}
#Test
public void test() throws JsonProcessingException {
final boolean hasSecureAccess = false; // Custom logic resolved to a boolean value at runtime.
final TestEntity testEntity = new TestEntity("1", new Date(), 2, ImmutableList.of("3", "4", "5"));
final ObjectMapper objectMapper = new ObjectMapper().enable(MapperFeature.DEFAULT_VIEW_INCLUSION);
final String serializedValue = objectMapper
.writerWithView(CustomViews.getWriterView(hasSecureAccess))
.writeValueAsString(testEntity);
Assert.assertTrue(serializedValue.contains("a"));
Assert.assertFalse(serializedValue.contains("b"));
Assert.assertFalse(serializedValue.contains("c"));
Assert.assertTrue(serializedValue.contains("d"));
}

Is it possible to drive the #Size "max" value from a properties file?

I'm using Spring 3.1.1.RELEASE. I have a model with the following attribute
import javax.validation.constraints.Size;
#Size(max=15)
private String name;
I validate the model in my controller my running
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(final Model model,
#Valid final MyForm myForm,
I would like to have the "15" value come from a properties file instead of hard-coded, but am unclear if that's possible or how its done. Any ideas?
This is not possible. The constant expression that you provide as a value for the max attribute is added at compile time. There is no way to change the value of an annotation at runtime. Setting it from a properties file you read is therefore not possible
What you can do instead is to create and register your own Validator for the your class that has that field. For example,
public class MyValidator implements Validator {
public void validate(Object target, Errors errors) {
MyObject obj = (MyObject) target;
int length = getProperties().get("max.size");
if (obj.name.length() > length) {
errors.rejectValue("name", "String length is bigger than " + length);
}
}
public boolean supports(Class<?> clazz) {
return clazz == MyOBject.class;
}
}
Take a look at Spring's validation framework.

How do you handle deserializing empty string into an Enum?

I am trying to submit a form from Ext JS 4 to a Spring 3 Controller using JSON. I am using Jackson 1.9.8 for the serialization/deserialization using Spring's built-in Jackson JSON support.
I have a status field that is initially null in the Domain object for a new record. When the form is submitted it generates the following json (scaled down to a few fields)
{"id":0,"name":"someName","status":""}
After submitted the following is seen in the server log
"nested exception is org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.blah.domain.StatusEnum from String value '': value not one of the declared Enum instance names"
So it appears that Jackson is expecting a valid Enum value or no value at all including an empty string. How do I fix this whether it is in Ext JS, Jackson or Spring?
I tried to create my own ObjectMapper such as
public class MyObjectMapper extends Object Mapper {
public MyObjectMapper() {
configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
}
}
and send this as a property to MappingJacksonMappingView but this didn't work. I also tried sending it in to MappingJacksonHttpMessageConverter but that didn't work. Side question: Which one should I be sending in my own ObjectMapper?
Suggestions?
The other thing you could do is create a specialized deserializer (extends org.codehaus.jackson.map.JsonDeserializer) for your particular enum, that has default values for things that don't match. What I've done is to create an abstract deserializer for enums that takes the class it deserializes, and it speeds this process along when I run into the issue.
public abstract class EnumDeserializer<T extends Enum<T>> extends JsonDeserializer<T> {
private Class<T> enumClass;
public EnumDeserializer(final Class<T> iEnumClass) {
super();
enumClass = iEnumClass;
}
#Override
public T deserialize(final JsonParser jp,
final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final String value = jp.getText();
for (final T enumValue : enumClass.getEnumConstants()) {
if (enumValue.name().equals(value)) {
return enumValue;
}
}
return null;
}
}
That's the generic class, basically just takes an enum class, iterates over the values of the enum and checks the next token to match any name. If they do it returns it otherwise return null;
Then If you have an enum MyEnum you'd make a subclass of EnumDeserializer like this:
public class MyEnumDeserializer extends EnumDeserializer<MyEnum> {
public MyEnumDeserializer() {
super(MyEnum.class);
}
}
Then wherever you declare MyEnum:
#JsonDeserialize(using = MyEnumDeserializer.class)
public enum MyEnum {
...
}
I'm not familiar with Spring, but just in case, it may be easier to handle that on the client side:
Ext.define('My.form.Field', {
extend: 'Ext.form.field.Text',
getSubmitValue: function() {
var me = this,
value;
value = me.getRawValue();
if ( value === '' ) {
return ...;
}
}
});
You can also disallow submitting empty fields by setting their allowBlank property to false.
Ended up adding defaults in the EXT JS Model so there is always a value. Was hoping that I didn't have to this but it's not that big of a deal.
I have the same issue. I am reading a JSON stream with some empty strings. I am not in control of the JSON stream, because it is from a foreign service. And I am always getting the same error message. I tried this here:
mapper.getDeserializationConfig().with(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
But without any effect. Looks like a Bug.

Cross field validation based on value

If we are build a custom JSR 303 validator, is there any way, we can pass field's value to the validator instead of the field's name?
Here is what I am doing..
I need to build a custom class level validation which validates this case..
There are two fields A & B where B is a date field. If A's value is 1, verify that B is not null and its value is future date.
Now I was able to build a validation with these requirements following this post. In the FutureDateValidator's isValid() method, I have checked whether A's value is 1 or not and then I checked the date validity.
#CustomFutureDate(first = "dateOption", second = "date", message = "This must be a future date.")
Now I have new set of fields C and D, where D is again the date field. This time I need to verify that D is a future date if C's value is 2. In this case I cannot use the validator I already implemented because it has the first field's value hard-coded. So how do I solve this issue to reuse the same validator for these two cases.
To not hardcode values 1/2 made it customizable:
#CustomFutureDate(first = "dateOption", firstValue = "1", second = "date", message = "This must be a future date.")
To make it work you need to modify #CustomFutureDate annotation:
public #interface CustomFutureDate {
String first();
String firstValue();
...
}
and implementation:
public class CustomFutureDateValidator implements ConstraintValidator<CustomFutureDate, Object> {
private String firstFieldName;
private String firstFieldValue;
...
#Override
public void initialize(final CustomFutureDate constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
firstFieldValue = constraintAnnotation.firstValue();
...
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
// use firstFieldValue member
...
}
}

Resources