JSR-303 Bean Validation Emmanuel Bernard JBoss, by Red Hat http://in.relation.to/Bloggers/Emmanuel

Copyright 2007-2010 Emmanuel Bernard and Red Hat Inc. mardi 6 avril 2010

• •

Enable declarative validation in your applications Constrain Once,Validate Anywhere

mardi 6 avril 2010

Emmanuel Bernard • Hibernate Search in Action • blog.emmanuelbernard.com • twitter.com/emmanuelbernard • http://lescastcodeurs.com

mardi 6 avril 2010

Constraints • Constraint • restriction on a bean, field or property • not null, between 10 and 45, valid email... • How is that useful • give feedback to the user • ensure that a service will behave correctly • define service range of usability • avoid adding crap to the database • unless you like fixing the data manually mardi 6 avril 2010

Constraints in Java Ecosystems • Where should they be applied?

mardi 6 avril 2010

Constraints in the Java Ecosystem Java Client Side

Presentation Layer

Business Layer

Data Access Layer

• How many models do you have? • ONE mardi 6 avril 2010

Database

What is the solution? • Uniform way to express a constraint • everybody speaks the same language • based on the domain model (JavaBeans™) • Standard way to validate constraints • one runtime engine • same validation implementations shared • Bridge for constraints out of Java™ land • API to access the constraint repository mardi 6 avril 2010

Declare a constraint public class Address { @NotNull @Size(max=30, message="longer than {max} characters") private String street1; ... @NotNull @Valid private Country country; } public class Country { @NotNull @Size(max=30) private String name; ... }

mardi 6 avril 2010

Groups • Subset of constraints • Partial validation • screen of a wizard UI • Constraints applied in a given use case • Order constraint validations • which depends on other validations • when a constraint is resource/time intensive mardi 6 avril 2010

interface Billable {} interface BuyInOneClick extends Billable, Default {} class User { @NotNull(groups=BuyInOneClick.class) PaymentMethod getDefaultCreditCard() {...}

}

@NotNull //Default group String getUserName() {...}

@GroupSequence(sequence={Default.class, Heavy.class}) interface Complete {}

mardi 6 avril 2010

Create your own constraint • Annotations with expressive names • List of ConstraintValidators • Constraint composition

mardi 6 avril 2010

@Constraint(validatedBy={ SizeValidatorForCollections.class), SizeValidatorForString.class } ) public @interface Size { String message() default "{constraint.size}"; Class[] groups() default {}; Class payload() default {};

}

mardi 6 avril 2010

//custom attributes int min() default 0; int max() default Integer.MAX_VALUE;

public class SizeValidatorForString implements ConstraintValidator { public void initialize(Size annotation) {}

}

mardi 6 avril 2010

public boolean isValid(String value, ConstraintValidatorContext context) {}

Composition • Reuse constraints • Expose meta-informations @NotNull @Size(min=5, max=5) @Constraint(validatedBy=FrenchZipCodeValidator.class) public @interface FrenchZipCode { String message() default "{constraint.frenchzipcode}"; Class[] groups() default {}; Class[] payload() default {}; }

mardi 6 avril 2010

Message • Can be externalized • Internationalization • Interpolate constraint parameters • must be shorter than {min} • Custom MessageInterpolator strategy • Useful for application frameworks • Contextual data • Locale mardi 6 avril 2010

How to use Bean Validation • Standalone • JPA 2.0 • JSF 2.0 • EE 6

mardi 6 avril 2010

Bootstrap API • extensible • support multiple implementations • type-safe • can override some attributes contextually • XML configuration optional • META-INF/validation.xml mardi 6 avril 2010

ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); ValidatorFactory vf = Validation.byDefaultProvider() .configure() .messageInterpolator( containerMI ) .traversableResolver( jpaTR ) .constraintValidatorFactory( webBeansDI ) .buildValidatorFactory(); ValidatorFactory vf = Validation .byProvider(HibernateValidationProvider.class) .configure() .messageInterpolator( containerMI ) .failFast() .enableLegacyConstraints() .buildValidatorFactory();

mardi 6 avril 2010

Manual validation • Get a Validator from a ValidatorFactory Set> errors = validator.validate(user); Set> errors = validator.validate(user, BuyInOneClick.class);

• ConstraintViolation • error message / message template • invalid value • context mardi 6 avril 2010

Accessing the metadata • DDL generation, tools, JavaScript generators • Metadata API BeanDescriptor - validator.getConstraintsForClass(User.class) PropertyDescriptor - beanDescr.getConstrainedProperties() ConstraintDescriptor - descr.getConstraintDescriptors() - constrDescr.getComposingConstraints()

• Shines with: • composition • built-in annotations mardi 6 avril 2010

JSF 2 integration • Zero conf • Validate input components • find property via Expression Language • call Bean Validation on input value • return localized error messages • use JSF user Locale • custom MessageInterpolator mardi 6 avril 2010

Java Persistence 2 • On entity change • validation • can select the groups validated • Make use of a custom TraversableResolver • do not traverse associations mardi 6 avril 2010

Java EE 6 • Validator as an injectable resource @Resource Validator validator; //or @Resource ValidatorFactory vf;

in CDI (Java Context and Dependency • Or Injection) @Inject Validator validator; //or @Inject ValidatorFactory vf;

mardi 6 avril 2010

Bean Validation • Status. It’s done.

mardi 6 avril 2010

Hibernate Validator 4 • Released too. 4.0.2 • What are you waiting for? • Road Map compatible with legacy Hibernate • backward Validator usage • some cool ideas out of the spec scope • License • ASL 2.0 mardi 6 avril 2010

Questions? Or not? • JCP.org • search “303” • http://in.relation.to • “bean validation” tag • Hibernate Validator • http://validator.hibernate.org • http://forum.hibernate.org/viewforum.php?f=26 mardi 6 avril 2010

errors = validator.validate(user)

based on the domain model (JavaBeans™). • Standard way to validate constraints. • one runtime engine. • same validation implementations shared. • Bridge for ...

332KB Sizes 1 Downloads 193 Views

Recommend Documents

server errors - Sascha Fahl
Certificate error reports may contain private information. For ex- ample, a certificate from an intranet might ... example, if the user's local system clock is set incorrectly, it may prevent a report about the condition from ...... droid, accounting

server errors - Sascha Fahl
HTTPS connection and replaces the certificate chain with one that the client cannot validate. Our pipeline classifies the following types of network errors: 4.3.1 Captive portal errors. Airport, hotel, and enterprise net- works often block access to

Grammatical Errors
http://grammarist.com/articles/grammarly-review/. British​ ​English​ ​vs.​ ​American​ ​English​ ​Test. For this test, we'll create a series of sentences that contain distinctly British spelling and. grammatical structures. § The

Cohesive Devices- Errors - UsingEnglish.com
Because the indigenous people have never really gained equal rights. 4. There are many reasons why the number of temporary positions is increasing. For ex-.

IELTS Listening- Typical Errors - UsingEnglish.com
12 Batchelor of Science. 13 bristol ... 101 powerfull computer programs .... short e (leisure activities, boats/ pleasure craft), ch (Bachelor of Science, matching.

english Spotting errors 13.03.2015.pdf
Diamond is (1) / not found (2) / everywhere. (3) / since it is a rare ... candidates to have clarity on the same. .... Displaying english Spotting errors 13.03.2015.pdf.

RAIM with Non-Gaussian Errors
conducted under a space-‐based augmentation system. (SBAS) or ground-‐based .... Accounting for biases and unequal variances in the distribution of ε .... P , we conclude that VPL ≤ VAL and the precision approach may be executed. Implementatio

Learning representations by back-propagating errors
or output come to represent important features of the task domain, and the regularities in the task are captured by the interactions of these units The ability to ...

Unconscious errors enhance prefrontal-occipital ... - Semantic Scholar
Nov 24, 2009 - synchrony was taken from three temporal windows (first averaging from 2–12 Hz): −1200 to −300 ms ... the analyses using different time windows did not appreciably alter the results. Averaged data were entered .... unconscious err

Business English Presentations- Correct the Errors - UsingEnglish.com
Correct your own errors in your homework or things you said in the last class that your ... There is a list of original sources in the last page of the handout.

Importance of Maintaining Continuous Errors and Omissions ...
Importance of Maintaining Continuous Errors and Omissions Coverage Bulletin.pdf. Importance of Maintaining Continuous Errors and Omissions Coverage ...

Mind your corpus: systematic errors in authorship ...
can be extracted from a population that seems to contain nothing but noise. However, it does not mean that one can overcome the impact of randomness: noise ...

man-4\errors-in-galvanic-cell-labs.pdf
man-4\errors-in-galvanic-cell-labs.pdf. man-4\errors-in-galvanic-cell-labs.pdf. Open. Extract. Open with. Sign In. Main menu.

Programmers' Build Errors: A Case Study - Research at Google
of reuse, developers use a cloud-based build system. ... Google's cloud-based build process utilizes a proprietary ..... accessing a protected or private member.

The Influence of Training Errors, Context and Number ...
Apr 21, 2009 - (i, j), 0 ≤ i ≤ M − 1,0 ≤ j ≤ N − 1, will be denoted by S, the support of the image. ... deserved a great deal of attention in the computer vision literature since they were ..... International Journal of Remote Sensing 13:

Can input explain children's me-for-I errors?
children make pronoun case errors producing utterances such as me do it,. her going,him ...... Note: See our website (http://www.acqdiv.uzh.ch) for more details.

Standard operating procedure for rectifying errors in PDCO opinions ...
SOP/EMA/0101. Standard operating procedure for conducting checks for conflicts of interest when ... Managing Meeting Documents system. Paed Asst ... Establish timelines. Inform PDCO sec. and applicant. 4. Schedule adoption of Revision by. PDCO plenar

Advanced Methods for Algorithmic Corrections of Errors ...
Some measuring systems have been designed in order to estimate performance of novel approaches, such as a structural method of error correction and iterating correction method of errors in immitance measurement. The expressions of functional conversi

Errors in Project Approval and Mandatory Review
We compare two processes for society to review projects: one that is entirely based .... savings. 2The court ruled that if one technology user successfully challenges the validity .... preclude the evaluator from taking their information into account