SlideShare une entreprise Scribd logo
1  sur  20
JSR-303 Bean Validation API


                 •
                     Overview
                 •
                     Concept
                 •
                     Defining Constraints
                 •
                     Validate Constraints
                 •
                     Bootstrapping
                 •
                     Integration JEE/JSF


Heiko Scherrer
Preface JSR-303



  •
      Specifies common validation concept for
      JavaBeans™
  •
      For JavaEE & SE, extension of the
      JavaBeans object model
  •
      JSR-303 addresses validation in all
      layers of the application



Heiko Scherrer
Before JSR-303

                                                                          DDL: CHECK(length(email)==8)
   Script:if (email.length == 8) {...}




                                         if (email.length() == 8) {...}
                                                                          Person {
 <f:validateLength minimum="8" />                                         …
                                                                            @Column(length=8)
                                                                            String email;
                                                                          …
                                                                          }




Heiko Scherrer
Without Specification

  •
      Several validation frameworks exist:
       ●
           Apache Common-Validator
       ●
           Hibernate Validator
       ●
           JSF Validators
       ●
           ...
  •
      Not all frameworks for all layers
      =>Duplicated error-prone code
      =>Similar to JPA: A standard is needed!

Heiko Scherrer
With JSR-303




                                   Constraint is
                                   validated in
                                    all layers!

                 Person {
                 …
                   @Min(8)
                   String email;
                 …
                 }




Heiko Scherrer
JSR-303 - Concept



  •
      The JSR-303 API guarantees a stable,
      independent and extensible way to
      define constraints in domain objects and
      validate them
  •
      At least two implementations (SPI) are
      currently available: Hibernate, Spring3



Heiko Scherrer
JSR-303 - Concept
                             Specifies responsibilities
                             of the implementation: Validation.buildDefaultValidatorFactory()
                             Exceptions, Factories...




                                       Interesting parts
                                                           Validator definition:
                 Standard constraint                        Specifies how to
                     Definitions:                              validate data
                 @NotNull, @Min ...
                                                       validator.validate(myClass)




Heiko Scherrer
JSR-303 – Standard Constraints

Name             Description
@NotNull         must not be NULL
@AssertTrue      must not be true. NULL means valid
@AssertFalse     must not be false. NULL means valid
@Min             must be a number whose value must be higher or equal
@Max             must be a number whose value must be lower or equal
@DecimalMin      same as @Min
@DecimalMax      same as @Max
@Size            must been between the specified boundaries (included)
@Digits          must be a number within accepted range (included)
@Past            must be a date in the past
@Future          must be a date in the future
@Pattern         must match the defined regular expression




Heiko Scherrer
JSR-303 – Constraints

  •
      Constraints can be defined on methods, fields,
      annotations (constructors and parameters)
  •
      Custom constraints: @Constraint (see
      sourcecode example)
  •
      Constraints have properties: message,
      payload, groups
  •
      Annotated methods must follow the
      JavaBeans™ specification



Heiko Scherrer
JSR-303 – Constraints II


   •
       Validation of two separate properties is done
       within a validation method
   •
       A validation method is annotated with a
       Constraint and must follow JavaBeans Spec.

       @AssertTrue
       public boolean isValid() {
         …
         return qty1 > qty2;
       }


Heiko Scherrer
JSR-303 – Constraint example

    •
        Custom constraints can validate multiple fields
    •
        Some constraints apply to the database schema
    •
        Constraints can be grouped together using the groups
        property
    •
        The message text is interpolated ({…}) and
        internationalized
     Custom
    constraint


     Grouped
     together

     Simple
  constraint in
  default group

    Added a
  message text



Heiko Scherrer
JSR-303 – Grouping constraints

 •
      Not all declared constraints     Define a group:
                                       /**
      shall be validated each time      * A PersistenceGroup
                                        * validation group. This group
 •
      Different layers use perhaps a    * is validated in the integration layer.
                                        */
      different sequence of            public interface PersistenceGroup { }
      validation
 •
      Simple Java marker interfaces    In your domain class:
      (also classes) are used for      @NotNull(groups = PersistenceGroup.class)
                                       private String businessKey;
      grouping
 •
      Group inheritance with class     Validate the group:
      inheritance                      validator.validate(obj, PersistenceGroup.class);

 •
      Constraints on @Constraints      Bring all groups in a defined order:
      allows composing them            @GroupSequence(
                                       {Default.class, WMChecks.class,
                                                              PersistenceGroup.class})
 •
      Sequencing is done with          public interface SequencedChecks {
      @GroupSequence                   }




Heiko Scherrer
JSR-303 - Validation


 •
      Similar to JPA the Bean Validation API defines
      a factory to create a Validator
 •
      Validation is done with a Validator instance
 •
      Three methods at all:
      ●   validate(T object, Class<?>... groups)
      ●   validateProperty(T object,String pName, Class<?>... groups)
      ●   validateValue(Class<T> clazz, String pName, Object val, Class<?>... groups)

 •
      The return value is an empty Set in case the
      validation succeeds


Heiko Scherrer
JSR-303 – Validation (II)

           •
                 ConstraintViolation in case of failure
           •
                 to determine the reason why use methods like:
                 ●
                     String getMessage();
                 ●
                     Object getInvalidValue();
           •
                 ValidationMessages.properties file for custom messages
           •
                 @NotNull(message=”{org.openwms.resources.myText}”

Set<ConstraintViolation<MyClass>> c = validator.validate(obj);
assertEquals(1, c.size());


assertEquals("text defined with the constraint", c.iterator().next().getMessage());


assertEquals(2, validator.validate(obj, PersistenceGroup.class).size());


assertEquals(0, validator.validateProperty(obj, "qtyOnHand").size());


Heiko Scherrer
JSR-303 – Bootstrapping in J2SE

 •
     In a J2SE environment as well as JUnit test
     classes the factory/validator is instanciated:
       ●   ValidatorFactory f = Validation.buildDefaultValidatorFactory();
           Validator validator = factory.getValidator();

 •
     The ValidatorFactory is thread-safe,
     creation is an expensive operation
       ●
           This is done in a static method in the test super
           class
 •
     Creating the Validator is fast and can be
     done in each test execution method


Heiko Scherrer
JSR-303 – Bootstrapping in JEE6

  •
      In an EJB container it is not allowed to call the
      static build method
  •
      The factory and the validator are handled as
      Resources
  •
      In an EJB container use:
       ●   @Resource ValidatorFactory factory;
           @Resource Validator validator;

  •
      Or JNDI to lookup both:
       ●   initCtx.lookup("java:comp/ValidatorFactory");
           initCtx.lookup("java:comp/Validator");

  •
      JEE5 does not implement the Bean Val. SPI!

Heiko Scherrer
JSR-303 – Activation in JEE6/JPA

  •
      JPA2.0 comes along with built-in validation
      support with JSR-303
  •
      Persistence.xml defines a new element:
      <validation-mode>
        ●   AUTO:      Validation is done before create/update/delete
            if Validation provider is present
        ●   CALLBACK: An exception is raised when no Validator
            is present
        ●   NONE: Bean Validation is not used at all



Heiko Scherrer
JSR-303 – Usage in JSF2.0

 •
     Outside JEE6 use the servlet context param:
       ●   javax.faces.validator.beanValidator.ValidatorFactory
       ●
           Without this param the classpath is scanned
 •
     Within JEE6 use annotations or access the
     ServletContext. The container is responsible
     to make the factory available there
 •
     Validation can be done programatically or
     declarative
       ●
           <h:inputText value=”#{myBean.name}”>
               <f:validateBean />
           </h:inputText>



Heiko Scherrer
Recommended links




         •
             JSR-303 final specification
         •
             JSR-314 JSF2.0 final specification
         •
             JSR-316 JEE6 final specification
         •
             Hibernate Validator documentation




Heiko Scherrer
Q&A




Heiko Scherrer

Contenu connexe

Tendances

JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJohn Ferguson Smart Limited
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Javaguy_davis
 
How to Test Enterprise Java Applications
How to Test Enterprise Java ApplicationsHow to Test Enterprise Java Applications
How to Test Enterprise Java ApplicationsAlex Soto
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingOrtus Solutions, Corp
 
#codemotion2016: Everything you should know about testing to go with @pedro_g...
#codemotion2016: Everything you should know about testing to go with @pedro_g...#codemotion2016: Everything you should know about testing to go with @pedro_g...
#codemotion2016: Everything you should know about testing to go with @pedro_g...Sergio Arroyo
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Sergio Arroyo
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!rafaelliu
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testingPeter Edwards
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpdayStephan Hochdörfer
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontendHeiko Hardt
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USCreating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USAnnyce Davis
 

Tendances (20)

JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit Tests
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
How to Test Enterprise Java Applications
How to Test Enterprise Java ApplicationsHow to Test Enterprise Java Applications
How to Test Enterprise Java Applications
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
#codemotion2016: Everything you should know about testing to go with @pedro_g...
#codemotion2016: Everything you should know about testing to go with @pedro_g...#codemotion2016: Everything you should know about testing to go with @pedro_g...
#codemotion2016: Everything you should know about testing to go with @pedro_g...
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
3 j unit
3 j unit3 j unit
3 j unit
 
Creating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf USCreating Gradle Plugins - GR8Conf US
Creating Gradle Plugins - GR8Conf US
 

Similaire à JSR-303 Bean Validation API

How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?Dmitry Buzdin
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.IT Weekend
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyClare Macrae
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applicationssilviad74
 
New Security Features in Apache HBase 0.98: An Operator's Guide
New Security Features in Apache HBase 0.98: An Operator's GuideNew Security Features in Apache HBase 0.98: An Operator's Guide
New Security Features in Apache HBase 0.98: An Operator's GuideHBaseCon
 
Continuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma ScanContinuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma ScanPuma Security, LLC
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Migration strategies 4
Migration strategies 4Migration strategies 4
Migration strategies 4Wenhua Wang
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIAashish Jain
 
Java EE Security API - JSR375: Getting Started
Java EE Security API - JSR375: Getting Started Java EE Security API - JSR375: Getting Started
Java EE Security API - JSR375: Getting Started Rudy De Busscher
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateLB Denker
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Kirk Bushell
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 Newsos890
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cppClare Macrae
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Ryan Cuprak
 

Similaire à JSR-303 Bean Validation API (20)

How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
 
Fluent validation
Fluent validationFluent validation
Fluent validation
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ Effectively
 
cbvalidation
cbvalidationcbvalidation
cbvalidation
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applications
 
New Security Features in Apache HBase 0.98: An Operator's Guide
New Security Features in Apache HBase 0.98: An Operator's GuideNew Security Features in Apache HBase 0.98: An Operator's Guide
New Security Features in Apache HBase 0.98: An Operator's Guide
 
Sva.pdf
Sva.pdfSva.pdf
Sva.pdf
 
Continuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma ScanContinuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma Scan
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Migration strategies 4
Migration strategies 4Migration strategies 4
Migration strategies 4
 
Spock
SpockSpock
Spock
 
Document db
Document dbDocument db
Document db
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
 
Java EE Security API - JSR375: Getting Started
Java EE Security API - JSR375: Getting Started Java EE Security API - JSR375: Getting Started
Java EE Security API - JSR375: Getting Started
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 News
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

JSR-303 Bean Validation API

  • 1. JSR-303 Bean Validation API • Overview • Concept • Defining Constraints • Validate Constraints • Bootstrapping • Integration JEE/JSF Heiko Scherrer
  • 2. Preface JSR-303 • Specifies common validation concept for JavaBeans™ • For JavaEE & SE, extension of the JavaBeans object model • JSR-303 addresses validation in all layers of the application Heiko Scherrer
  • 3. Before JSR-303 DDL: CHECK(length(email)==8) Script:if (email.length == 8) {...} if (email.length() == 8) {...} Person { <f:validateLength minimum="8" /> … @Column(length=8) String email; … } Heiko Scherrer
  • 4. Without Specification • Several validation frameworks exist: ● Apache Common-Validator ● Hibernate Validator ● JSF Validators ● ... • Not all frameworks for all layers =>Duplicated error-prone code =>Similar to JPA: A standard is needed! Heiko Scherrer
  • 5. With JSR-303 Constraint is validated in all layers! Person { … @Min(8) String email; … } Heiko Scherrer
  • 6. JSR-303 - Concept • The JSR-303 API guarantees a stable, independent and extensible way to define constraints in domain objects and validate them • At least two implementations (SPI) are currently available: Hibernate, Spring3 Heiko Scherrer
  • 7. JSR-303 - Concept Specifies responsibilities of the implementation: Validation.buildDefaultValidatorFactory() Exceptions, Factories... Interesting parts Validator definition: Standard constraint Specifies how to Definitions: validate data @NotNull, @Min ... validator.validate(myClass) Heiko Scherrer
  • 8. JSR-303 – Standard Constraints Name Description @NotNull must not be NULL @AssertTrue must not be true. NULL means valid @AssertFalse must not be false. NULL means valid @Min must be a number whose value must be higher or equal @Max must be a number whose value must be lower or equal @DecimalMin same as @Min @DecimalMax same as @Max @Size must been between the specified boundaries (included) @Digits must be a number within accepted range (included) @Past must be a date in the past @Future must be a date in the future @Pattern must match the defined regular expression Heiko Scherrer
  • 9. JSR-303 – Constraints • Constraints can be defined on methods, fields, annotations (constructors and parameters) • Custom constraints: @Constraint (see sourcecode example) • Constraints have properties: message, payload, groups • Annotated methods must follow the JavaBeans™ specification Heiko Scherrer
  • 10. JSR-303 – Constraints II • Validation of two separate properties is done within a validation method • A validation method is annotated with a Constraint and must follow JavaBeans Spec. @AssertTrue public boolean isValid() { … return qty1 > qty2; } Heiko Scherrer
  • 11. JSR-303 – Constraint example • Custom constraints can validate multiple fields • Some constraints apply to the database schema • Constraints can be grouped together using the groups property • The message text is interpolated ({…}) and internationalized Custom constraint Grouped together Simple constraint in default group Added a message text Heiko Scherrer
  • 12. JSR-303 – Grouping constraints • Not all declared constraints Define a group: /** shall be validated each time * A PersistenceGroup * validation group. This group • Different layers use perhaps a * is validated in the integration layer. */ different sequence of public interface PersistenceGroup { } validation • Simple Java marker interfaces In your domain class: (also classes) are used for @NotNull(groups = PersistenceGroup.class) private String businessKey; grouping • Group inheritance with class Validate the group: inheritance validator.validate(obj, PersistenceGroup.class); • Constraints on @Constraints Bring all groups in a defined order: allows composing them @GroupSequence( {Default.class, WMChecks.class, PersistenceGroup.class}) • Sequencing is done with public interface SequencedChecks { @GroupSequence } Heiko Scherrer
  • 13. JSR-303 - Validation • Similar to JPA the Bean Validation API defines a factory to create a Validator • Validation is done with a Validator instance • Three methods at all: ● validate(T object, Class<?>... groups) ● validateProperty(T object,String pName, Class<?>... groups) ● validateValue(Class<T> clazz, String pName, Object val, Class<?>... groups) • The return value is an empty Set in case the validation succeeds Heiko Scherrer
  • 14. JSR-303 – Validation (II) • ConstraintViolation in case of failure • to determine the reason why use methods like: ● String getMessage(); ● Object getInvalidValue(); • ValidationMessages.properties file for custom messages • @NotNull(message=”{org.openwms.resources.myText}” Set<ConstraintViolation<MyClass>> c = validator.validate(obj); assertEquals(1, c.size()); assertEquals("text defined with the constraint", c.iterator().next().getMessage()); assertEquals(2, validator.validate(obj, PersistenceGroup.class).size()); assertEquals(0, validator.validateProperty(obj, "qtyOnHand").size()); Heiko Scherrer
  • 15. JSR-303 – Bootstrapping in J2SE • In a J2SE environment as well as JUnit test classes the factory/validator is instanciated: ● ValidatorFactory f = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); • The ValidatorFactory is thread-safe, creation is an expensive operation ● This is done in a static method in the test super class • Creating the Validator is fast and can be done in each test execution method Heiko Scherrer
  • 16. JSR-303 – Bootstrapping in JEE6 • In an EJB container it is not allowed to call the static build method • The factory and the validator are handled as Resources • In an EJB container use: ● @Resource ValidatorFactory factory; @Resource Validator validator; • Or JNDI to lookup both: ● initCtx.lookup("java:comp/ValidatorFactory"); initCtx.lookup("java:comp/Validator"); • JEE5 does not implement the Bean Val. SPI! Heiko Scherrer
  • 17. JSR-303 – Activation in JEE6/JPA • JPA2.0 comes along with built-in validation support with JSR-303 • Persistence.xml defines a new element: <validation-mode> ● AUTO: Validation is done before create/update/delete if Validation provider is present ● CALLBACK: An exception is raised when no Validator is present ● NONE: Bean Validation is not used at all Heiko Scherrer
  • 18. JSR-303 – Usage in JSF2.0 • Outside JEE6 use the servlet context param: ● javax.faces.validator.beanValidator.ValidatorFactory ● Without this param the classpath is scanned • Within JEE6 use annotations or access the ServletContext. The container is responsible to make the factory available there • Validation can be done programatically or declarative ● <h:inputText value=”#{myBean.name}”> <f:validateBean /> </h:inputText> Heiko Scherrer
  • 19. Recommended links • JSR-303 final specification • JSR-314 JSF2.0 final specification • JSR-316 JEE6 final specification • Hibernate Validator documentation Heiko Scherrer

Notes de l'éditeur

  1. JSTL (JSP Standard Tag Library): extends JSP about useful tags JAX-RPC (Java API for XML Based RPC): CS communication with XML SAAJ (SOAP with Attachments API): Comparable with JMS, SOAP as transport protocol STAX (Streaming API for XML): Simplifies XML handling and eliminates SAX and DOM JSR-250 (Common annotations for the Java Platform): Aggregation of all Java EE and Java SE annotations JAF (JavaBeans Activation Framework): Typing, instantiation and reflection of unknown objects
  2. Not permitted (..): An enterprise bean must not use read/write static fields. Using read-only static fields is allowed An enterprise bean must not use the AWT functionality The enterprise bean must not attempt to use the Reflection API
  3. Not permitted (..): An enterprise bean must not use read/write static fields. Using read-only static fields is allowed An enterprise bean must not use the AWT functionality The enterprise bean must not attempt to use the Reflection API
  4. Not permitted (..): An enterprise bean must not use read/write static fields. Using read-only static fields is allowed An enterprise bean must not use the AWT functionality The enterprise bean must not attempt to use the Reflection API
  5. No annotation means Local interface Multiple Interceptors can be defined for a bean, the order is specified in the Core/Requ. Spec. Interceptors are stateless, but with the InvocationContext object it is possible to store data across method invocations @PostConstruct , @PreDestroy methods signature: any name, return void, throws no checked exceptions
  6. No annotation means Local interface Multiple Interceptors can be defined for a bean, the order is specified in the Core/Requ. Spec. Interceptors are stateless, but with the InvocationContext object it is possible to store data across method invocations @PostConstruct , @PreDestroy methods signature: any name, return void, throws no checked exceptions
  7. To redefine the Default group place @GroupSequence directly on the domain class
  8. The first method validates all constraints The second field validates a given field or property of an object The last one validates the property referenced by pName present on clazz or any of its superclasses, if the property value were val