Questions around validation - java

I think this might possibly be answered elsewhere, but was getting lost in the context of other posts. So, decided to restate here. If anyone knows of this being already answered elsewhere, please point me in that direction. So, my questions.
I see JSR-303, JSR-349 and Hibernate Validator. What is the difference?
It seems to me that Hibernate Validator is a reference implementation of the JSR-303 spec, is that true?
Then what is 349?
If Hibernate Validator is a reference impl of the spec, are there other impl's of the spec?
Now some specifics of what I am looking for. I have done some reading about JSR-303 and I follow generally how the annotations work. My question is can I dynamically change the constraint values? Take the following for example:
public class Foo {
#Min(value = 18, message = "Age must be greater than or equal to 18")
#Max(value = 150, message = "Age must be less than or equal to 150")
int fooAge;
}
So, is there a way using the spec to feed the age constraints at runtime. So, lets say for some reason in one case I need the min to be 20 and max to be 100. In another case I need 10 and 50, etc. etc.
Thanks in advance for helping to clear this up for me.

303 is the JSR for Bean Validation 1.0. 349 is the JSR for Bean Validation 1.1.
The home page of the project says: "Hibernate Validator 5.x is the reference implementation Bean Validation 1.1!"
The JSR defines the specification. Hibernate validator is the reference implementation of this specification.
It seems not: http://beanvalidation.org/1.1/certified/
Yes, you can do that by assigning the constraints to validation groups, and activate one group or another depending on the use-case. See http://beanvalidation.org/1.0/spec/#validationapi-validatorapi-groups

As far as question is concerned:
If Hibernate Validator is a reference impl of the spec, are there other impl's of the spec?
There is also apache implementation of JSR-303 -> http://bval.apache.org/.
Unfortunately the latest release version Apache BVal (0.5) doesn't support Bean Validation 1.1. It should be introduced in version: Apache BVal (1.1.0). Right now there is an alpa-snapshot release:
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>1.1.0-alpha-SNAPSHOT</version>
</dependency>
More information on: http://cxf.apache.org/docs/validationfeature.html

Related

Getting a java bean property value by annotation

How do I get the returned value from a java bean property by annotation?
For example, trying to get the returned value of the property id from a Hibernate entity using its annotation (#Id).
Thanks.
Edit:
I've eliminated the requirement of using javassist for this question.
I don't know much details about javassit internal except that hibernate uses it internally, but surely can tell you that spring reflection util have a powerful support for handling things like processing all the classes which have an annotation on properties[e.g.] [user defined or not].In case you don't find success with javassist, give a try to spring reflection api.

JPA validation: String in column should be accepted by java.net.URI constructor

I'm using JPA to create a structure in a database. My task is to define a column with following properties:
is accepted by java.net.URI Constructor
ends with '/' (slash)
Does anyone have an idea how to do this?
Regards,
Patrick
Use JSR 303 (Bean validation). Use the #Pattern annotation on the field/getter and specify your pattern. http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html
What is Bean Validation?
Bean Validation (JSR 303) is a Java EE specification which:
provides a unified way of declaring and defining constraints on an object model.
defines a runtime engine to validate objects
Bean Validation includes integration with other Java EE specifications, such as JPA. Bean Validation constraints are automatically applied before data is persisted to the database, as a last line of defence against bad data.
http://www.jboss.org/ticket-monster/DataPersistence/

Hot to write a custom validator with apache bval

I am using bean-validation with apache bval as its implementation. (I do not want to use hibernate-validation or oval, because they have too much dependencies.)
First question: Is bval still maintained or is it orphaned?
Second question: Is it possible to implement custom validators using bval? E.g. a need a validator to File field that validates, that the file exists, isreadable and a file.
Apache BVal is afaik compliant with Bean Validation 1.0 which means should be able to write portable custom constraints. However, BVal is not yet Bean Validation 1.1 compatible, meaning you won't have executable constraints.
I don't know how active development is atm. Last release was in September 2012 which is quite a while back.
What is your concern with the Hibernate Validator or OVal dependencies?
Somebody did a performance comparison. However I am not sure how objective this comparison is: http://soularis999.blogspot.com/2011/07/bean-validation-performance-evaluation.html
Theres a how to now on baeldung.com: https://www.baeldung.com/apache-bval, it looks pretty standard
define an new annotation describing your constraint
define an constraint validator which implements ConstraintValidator<CONSTRAINT, TARGET>
annotatate your annotation with #Constraint(validatedBy={Validator.class})

Creating entities rules

I'd like to know the answer to this simple question.
When I create an entity object and I want to restrict a setting of an attribute (for example I don't want to allow anyone to set an integer value less then 1 to an attribute), should I implement it in the setter of this attribute or should I check this restriction latter in a class that handles these objects ? Generally, can I implement getters and setters however I want as long as my getters return and setters set attributes ?
I know there are some rules (code conventions) in java, so I don't want to break any of them.
Thanks in advance, hope that my question is clear enough and sorry for any grammar mistakes I might have made :/ .
Yes getters/setters are useful for that.
for example:
public void setAge(int age){
if(age < 0){
throw new IllegalArgumentException("Invalid age : " + age);
//or if you don't want to throw an exception you can handle it otherways too
}
}
You can also use Java-EE's Bean Validators for this
public class Person{
#Min(value = 0)
#Max(value = 99)
private Integer age;
//some other code
}
My preferred approach is to use JSR 303 (Bean Validation API) to ensure that the properties of the class are valid.
It is quite alright to perform validation in setters, but this is not always a desirable approach. There is the potential of mixing the needs of several contexts that are not related to each other. For example, some of your properties must never be set from the user-interface, and would instead be computed by a service, before being persisted. In such an event, it is not desirable to have this logic inside a setter, for you would need to know the context in which the setter is being invoked; you'll need to apply different rules in your UI layer and in your persistence layer. JSR 303 allows you to separate these concerns using validation groups, so that your UI validation group is different from your persistence validation group.
In JPA 2.0, when you annotate your class using constraints that are evaluated by a JSR 303 validator, your persistence provider can automatically evaluate these constraints on the PrePersist, PreUpdate and PreRemove (typically not done; see below) lifecycle events of entities. To perform validation of entities in your JPA provider, you must specify either the validation-mode element or the javax.persistence.validation.mode property in your persistence.xml file; the values must be either AUTO (the default) or CALLBACK (and not NONE).
The presence of a Bean Validation provider is sufficient to ensure that validation occurs on JPA entity lifecycle events, as the default value is AUTO. You get this by default, in a Java EE 6 application server; Glassfish uses the RI implementation of JSR 303 which is Hibernate Validator, and it works quite well with EclipseLink as well.
The CALLBACK mode will allow you to override the validation groups that are to be applied when the lifecycle events are triggered. By default, the default Bean validation group (Default) will be validated for update and persist events; the remove event does not involve any validation. The CALLBACK mode allows you to specify a different validation group for these events, using the properties javax.persistence.validation.group.pre-persist, javax.persistence.validation.group.pre-update and javax.persistence.validation.group.pre-remove.
Do keep in mind that JSR 303 validation can be used outside a Java EE container, although the Bean Validation API documentation link that I've posted above is from the Java EE 6 API documentation.
This is the goal of getters and setters.
If we cannot add some behavior in these methods, well... why don't we use public attributes ?
From my understanding of your question, it pretty much related to encapsulation OO principle.
You can have a look at this article: http://www.tutorialspoint.com/java/java_encapsulation.htm
Getters and setters are great for adding the restrictions, just like Jigar Joshi has in his answer. That way you get feedback immediately and can handle the problem when it is introduced.
Another solution would be to use object validation (something like a JSR-303 implementation) which would allow you to annotate the field with a min and max values. Something like
#Min(value=1)
private int myvalue;
Then you can validate the entire object in one go and get all messages if you have other constrained fields. This is obviously not useful everywhere, but if it fits your need it is an option.
Finally, when you say "entity" I think of something stored in a database or related to ORM tools. If that is the case, you will want to be careful with what you do in your getter. For instance, if you do lazy initialization in the getter some ORM suppliers will mark the entity as dirty and attempt to flush it to the database possibly causing an unintended write.

Commonly reusable annotations or commons annotations?

Are there any commonly usable annotations available? Similar to commons-lang?
If not, have you seen any effective use of annontations (not built-in annotations) as part of any open source application development.
I remember Mifos was using it for Transaction.
Mohan
i think Hibernate Validator has really good and reusable annotations for any kind of validation. it is based on a the reference implementation for JSR 303: Bean Validation.
Only non-standard annotations I've used more than once outside my testing project have been WicketStuff Annotations which are very useful in their own context.
Another interesting annotation set which is also the basis for JSR-305 is FindBugs' annotations which also may prove useful in the future - we'll see how that goes.
Check out my Bean annotations
http://code.google.com/p/javadude/wiki/Annotations
Things like
#Bean(
cloneable=true,
defineSimpleEqualsAndHashCode=true,
properties={
#Property(name="name", bound=true),
#Property(name="age", type=int.class, bound=true),
#Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
},
observers={
#Observer(type=FeverListener.class)
}
)
public class Person extends PersonGen { }
The annotation processor generates the PersonGen superclass.
Note that I'm currently working on a major change to them and the API is changing (I'll still leave the current version available, but the 3.x.x version stream will be breaking)
I'm trying to get the new version done in the next couple of weeks.
JAXB defines annotations (javax.xml.bind.annotation) that are reused to some degree -- although they are named to indicate they only related to XML serialization, most of metadata has to do with annotating properties to serialize, so they can be used for serializing to other data formats (such as JSON) too. Jackson JSON processor supports them, along its own 'native' annotations, since there are no really standardizes non-data-format specific annotations (AFAIK).
I like and Oval http://oval.sourceforge.net/ and JAXB
there really needs to be a set of common annotationsin the core jre which are used in similar ways in multiple frameworks.
for example #Transactional #Nullable

Categories