SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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)
 

Kürzlich hochgeladen

Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 

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

Hinweis der Redaktion

  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