Why must JSR303 custom annotation's constrain group default to empty array? - bean-validation

I'm writing a custom validator for a specific constrain group (not Default), but the runtime gives me the below error.
I'm just curious why they need the default values to be empty. Appreciate if you can share your opinion. Thanks :)
xxx.model.validation.CustomValidation contains Constraint annotation, but the groups parameter default value is not the empty array.
StackTrace: org.hibernate.validator.metadata.ConstraintHelper.assertGroupsParameterExists(ConstraintHelper.java:335)
org.hibernate.validator.metadata.ConstraintHelper.isConstraintAnnotation(ConstraintHelper.java:282)

I can't figure out in which scenario it can be useful to bind a constraint to a specific group.
A group is used for partial validation (and sequence validation). If you have 10 fields in a class you can mark 8 of them with A and 2 with B. Then you can decide to validate only the fields in the A group or in the B group. Conversely you want that #MyConstraint belongs to a specific group named C. It makes no sense. A group is more or less a name used to distinguish some fields from others in the same class. It has no absolute meaning. Groups are useful in validation not in constraint definition, they are related to fields not to constraints.
Furthermore if you hide the group name in the constraint definition you may run into errors because you can think that the fields are validated all togheter.
#Email
private String mail;
#Password
private String pass;
#VAT
private String vatCode;
Are you able to see if there is a partial validation?
EDIT
In relation to the second comment:
Suppose you have a class with 5 fields with no constraint at all. Three of them are integers. If you want to validate the sum of these three fields you have to create a class-level constraint as you suggest. In this way your custom annotation is applied to the class not to fields so, how can you define groups on fields?
Instead, you may use something like this:
#Sum(min = 250, fields = {"length", "width", "height"})
public class MyClass {
private String type;
private String code;
private int length;
private int width;
private int height;
...
}

Related

Java reflection to set static final field fails after previous reflection

In Java, it turns out that field accessors get cached, and using accessors has side-effects. For example:
class A {
private static final int FOO = 5;
}
Field f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
f.getInt(null); // succeeds
Field mf = Field.class.getDeclaredField("modifiers" );
mf.setAccessible(true);
f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.setInt(null, 6); // fails
whereas
class A {
private static final int FOO = 5;
}
Field mf = Field.class.getDeclaredField("modifiers" );
mf.setAccessible(true);
f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.setInt(null, 6); // succeeds
Here's the relevant bit of the stack trace for the failure:
java.lang.IllegalAccessException: Can not set static final int field A.FOO to (int)6
at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)
at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:100)
at sun.reflect.UnsafeQualifiedStaticIntegerFieldAccessorImpl.setInt(UnsafeQualifiedStaticIntegerFieldAccessorImpl.java:129)
at java.lang.reflect.Field.setInt(Field.java:949)
These two reflective accesses are of course happening in very different parts of my code base, and I don't really want to change the first to fix the second. Is there any way to change the second reflective access to ensure it succeeds in both cases?
I tried looking at the Field object, and it doesn't have any methods that seem like they would help. In the debugger, I noticed overrideFieldAccessor is set on the second Field returned in the first example and doesn't see the changes to the modifiers. I'm not sure what to do about it, though.
If it makes a difference, I'm using openjdk-8.
If you want the modifier hack (don't forget it is a total hack) to work, you need to change the modifiers private field before the first time you access the field.
So, before you do f.getInt(null);, you need to do:
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
The reason is that only one internal FieldAccessor object is created for each field of a class (*), no matter how many different actual java.lang.reflect.Field objects you have. And the check for the final modifier is done once when it constructs the FieldAccessor implementation in the UnsafeFieldAccessorFactory.
When it is determined you can't access final static fields (because, the setAccessible override doesn't works but non-static final fields, but not for static final fields), it will keep failing for every subsequent reflection, even through a different Field object, because it keeps using the same FieldAccessor.
(*) barring synchronization issues; as the source code for Field mentions in a comment:
// NOTE that there is no synchronization used here. It is correct
(though not efficient) to generate more than one FieldAccessor for a
given Field.

Unique constraint at field in collection

is it possible to make this validation:
class Man {
#Unique
String name;
}
class Order {
#Valid
List<Man> manCollection;
}
where is unique logic is: every item in collection manCollection is unique.
You could make this snippet ambiguous just by adding a Customer class that contains a List of Orders:
class Man {
#Unique
String name;
}
class Order {
#Valid
List<Man> manCollection;
}
class Customer {
#Valid
List<Order> orderCollection;
}
Then one couldn't possibly know whether the Man objects must be unique within a given Order or within a given Customer (or both).
So I don't think it's possible with this exact syntax, regardless of what the Bean Validation APIs allow.
What you could do is move the annotation to manCollection, e.g. #UniqueMen List<Man> manCollection;, and implement a ConstraintValidator<List<Man>>.
If it's useful to you, you could even make a more generic #UniqueContent annotation, but that would be much more complex. You would need to pass the target type as a parameter (#UniqueContent(target = Man.class)) and write a validator that parses annotations on the target class in its initialize method. Be careful to use some caching mechanism, though, because annotation parsing is quite slow.

Java bean validation: Optional fields annotation

I would like to treat some fields as Optional, if the value is null or blank don't go with the checks of the other annotated constraints.
There is some way to achieve it!
Reading this tread Java bean validation: Enforce a #Pattern only when the property is not blank don't seems cover my needs.
Below an example to explain what I mean:
public class Test {
#Max(value=100) // <--mandatory
private int parA;
#Optional // <-Custom annotation telling "do not check other if null or blank"
#Range(min=10, max=200)
private int parB;
...
}
Now you can!
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#example-container-element-constraints-optional
public Optional<#Size(min=1, max=128) String> first_name = Optional.empty();
You cannot do what you want with Bean Validation. You cannot establish a "connection" between two constraints placed on a property. Also, if I understand correctly, your #Optional is not even a constraint annotation, but rather just a marker annotation. Note though, that all default constraints are implemented in a way that a constraint validates for null values. So in most cases you get what you want either way. In your example, you also have the problem that you are dealing with a primitive int. This will always have a value, so the range constraint would be evaluated either way.

Jsr303 specify group on association validation

I am facing an issue when validating object which has more than one relationship to bean of particular type but each of relationship must be validated in a different manner.
Composite class:
public class Composite{
#Valid
private Person insurer;
#Valid
private Person insured;
...(other properties)
private String foo;
}
Person class:
public class Person{
#NotNull(groups={Insurer.class,Insured.class})
private String name;
#NotNull(groups={Insurer.class,Insured.class})
private String surname;
...
#NotNull(groups={Insurer.class})
private String ssn;
}
So we have a single type Person which can represent insurer and insured. The problem is that when validating Composite i want to have insurer property to be validated with Insurer group and insured with Insured. Is there anyway it can be accomplished or i need to wait for https://hibernate.onjira.com/browse/BVAL-208 resolving...
To solve your issue in a standardized way you indeed have to wait for Bean Validation 1.1 which will address BVAL-208 (group translations).
In case your Person class also has a flag or some other criteria you could use to determine whether this person is an insurer or insured you could also use a custom class level constraints. The downside is that you are loosing some of the expressiveness of annotations, since you would have to do all validation yourself in the custom constraint validator implementation.
The other alternative (again you need a way to distinguish between insurer and insured) is to use the Hibernate Validator specific GroupSequenceProvider. This way you can keep your current configuration and you just would return the right group depending on the type of Person.

why and when to use properties

I am very confused with properties in asp.net.
I just don't understand why we use properties and when I should use them. Could anybody elaborate a little on this.
public class Customer
{
private int m_id = -1;
public int ID
{
set
{
m_id = value;
}
}
private string m_name = string.Empty;
public string Name
{
set
{
m_name = value;
}
}
public void DisplayCustomerData()
{
Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
}
}
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.
Taken From CSharp-Station
There are a couple of good reasons for it. The first is that you might need to add validation logic in your setter, or actually calculate the value in the getter.
Another reason is something to do with the IL code generated. If you are working on a large project that is spread over multiple assemblies then you can change the code behind your property without the application that uses your assembly having to recompile. This is because the "access point" of the property stays the same while allowing the implementation code behind it to be altered. I first read about this when I was looking into the point of automatic properties as I didnt see the point between those and a normal public variable.
It's easy.
All fields in class MUST be private (or protected). To show fields to another class yyou can use properties or get/set methods. Properties a shorter.
P.S. Don't declare write-only properties. It is worst practices.
Properties are a convenient way to encapsulate your classes' data.
Quoting from MSDN:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
Let's consider two common scenarios:
1) You want to expose the Name property without making it changeable from outside the class:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
}
2) You want to perform some checks, or run some code every time the data is accessed or set:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = (String.IsNullOrEmpty(value)) ? "DefaultName" : value;
}
}
see:
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
The most important reason is for validation purpose in setter and manipulation part can be implemented in get part.
For Ex.
Storing weekdays, which should be from 1-7, if we take normal variable and declare it as public, anyone can assign any value.
But in Properties setter you can control and validate.
The next one you can use it for tracking. That means, you can know how many times set and get functions has been called by clients (statistical purpose, may be not useful frequently).
Finally, you can control read only, write only and read/write for the properties according to your requirements.

Resources