17.12.2009
Metadatenbasierte Validierung

             JSR 303 and more...




17.12.2009
DI (FH) Gerhard.Petracek @irian.at
• JCP-Member
  (Bean Validation Expert Group)
• Apache MyFaces
     • Committer
     • PMC Member
     • Project Lead (ExtVal)
• Schulungen zu JEE (v.a. JSF)
• Autor verschiedener Fachartikel
• Vorträge (Software und Web-Engineering)
17.12.2009
Bean-Validation Ökosystem - 1
• Spec.-Lead: Emmanuel Bernard
• EG-Members
      • Internationale Firmen wie
             •   Sun
             •   Oracle
             •   Google
             •   uvm.
      • Einige Project Leads erfolgreicher
        Validierungsframeworks
             • Von Irian Solutions: Gerhard Petracek

17.12.2009
Bean-Validation Ökosystem - 2
• Implementierungen
      • Hibernate-Validator v4+ (RI)
      • Agimatec-validation (bald bei Apache SF)
      • OVal
• JSF Support lt. Spec. für JSF 2+
• Adapter für JSF
      • MyFaces ExtVal BV-Integration-Module
        (für JSF 1.x und JSF 2+)



17.12.2009
Hello Bean-Validation
• Beispiel
     public class Customer {
        @NotNull
        private String firstName;

             public String getFirstName() {
                return firstName;
             }

             public void setFirstName(
               String firstName) {
                  this.firstName = firstName;
             }
     }
17.12.2009
Standard Constraints - Übersicht
•    @AssertFalse / @AssertTrue
•    @DecimalMax / @DecimalMin
•    @Digits
•    @Future / @Past
•    @Max / @Min
•    @NotNull / @Null
•    @Pattern
•    @Size




17.12.2009
Feature Tour




17.12.2009
Eigene Constraints Definieren
• Erforderliche Bestandteile:
      • @Constraint (1-n Constraint-Validator(en))
      • Target
             •   FIELD
             •   METHOD
             •   TYPE
             •   ANNOTATION_TYPE (für Constraint composition)
  • Und natürlich: Retention RUNTIME
• Verpflichtende Attribute
  • message
  • groups
  • payload
17.12.2009
Constraint-Validatoren
• Implementierung von
     javax.validation.ConstraintValidator
     • initialize
     • isValid
• Ist auf ein Constraint und einen
  Ziel-Typ beschränkt (via Generics)
• Ein Constraint kann für mehrere
  Ziel-Typen verwendet werden
      • Bsp.: @Size für String, Array, Map, …


17.12.2009
Error Messages
• Message-Interpolator transformiert
  Nachrichten automatisch
      • Keys
      • Hardcoded
• Beispiel:
     @Size(min = 1, max = 10,
       message = "{firstName.lengthMessage}")

     Resource-Bundle:
     firstName.lengthMessage =
         Name must be between {min} and {max}
17.12.2009
Group-Validation / Partial-Validation
• Default:
  Constraint ist der Default-Gruppe zugeordnet
  (javax.validation.groups.Default)
• Gruppen sind Interfaces und somit typesafe
• Ermöglicht Validierung impliziter Gruppen
• Beispiel:
  @NotNull
  entspricht
  @NotNull(groups = Default.class)




17.12.2009
Reihenfolge bei der Validierung
• Default: keine Reihenfolge
• @GroupSequence ermöglicht die Angabe
  der Reihenfolge
• Rechenintensive Gruppen sollen am Ende
  validiert werden
• Validierung einer Gruppe findet statt, wenn
  die vorherige Gruppe fehlerfrei validiert
  wurde



17.12.2009
Multiple-Constraints
• Via Annotation-Element
  (Array vom Constraint-Typ)
• Beispiel:
  Zuordnung von Constraints zu Rollen
  (via Group-Validation)
     @Size.List({
        @Size(groups = Default.class
           min = 10, max = 20),
        @Size(groups = AdminGroup.class
           min = 1, max = 30)
     })

17.12.2009
Validation-Payload
• Subset von Validation-Parameter
  (siehe MyFaces ExtVal >= 3. Release)
• javax.validation.Payload
• Für Validation-Clients wie MyFaces ExtVal
  nutzbar – bspw.: Severity.Warn.class
• Beispiel:
     public class Severity {
       public static class Warn
         implements Payload {}

             public static interface Error
               extends Payload {}
     }
17.12.2009
Graph-Validation
• Wird ein Objekt validiert, dann werden
  referenzierte Objekte mit-validiert, wenn
  @Valid verwendet wird
• Auch Inhalte von Collections und Arrays
• Keine Validierung erfolgt, wenn Lazy-
  Properties noch nicht geladen wurden




17.12.2009
Class-Level Validation
• Constraint für e. Klasse/Interface
• Wird vererbt aber nicht überschrieben
• Bei der Validierung liegt das aktuelle
  Objekt im gesamten vor
• In JSF nur mit MyFaces ExtVal




17.12.2009
Constraint-Composition
• Mit Constraints annotierte Constraints
• Wiederverwendung von Constraints
• Violation-Message(s)
      • Default: Messages der einzelnen Constraints
      • Mit @ReportAsSingleViolation wird die
        Error-Message des Haupt-Constraints
        angezeigt




17.12.2009
[DEMO] JSR 303 in Action




17.12.2009
JSR 303 in Web-Applikationen




17.12.2009
Bean-Validation und JSF
• Änderungen in JSF 2.0 für JSR 303
      •      Default Validator
      •      Geändertes Verhalten v. required-Attribut
      •      ValidatorException mit mehreren Messages
      •      Verschiedene Konfigurationsparameter
• Spezieller Tag (validiert Default-Gruppe):
     <f:validateBean/>
• Beispiele:
      • Validierung der Default Group
      • Group-Validation
             <f:validateBean validationGroups =
               "at.irian.demo.validation.groups.Order"/>
17.12.2009
MyFaces Extensions Validator
    Ermöglicht die einfache Umsetzung von
    fortschrittlichen Validierungskonzepten für
    JSF-Applikationen auf Basis von
                              dynamischen
                              Metadaten.




17.12.2009
[DEMO] JSR 303 and JSF




17.12.2009
Bean-Validation & MyFaces ExtVal - 1
• MyFaces ExtVal bietet JSR 303
  Integration für alle JSF Versionen
• Integration als unabhängiges
  Validation-Module
• Group-Validation erfolgt via Annotation
      • Definition (norm.) auf Page-Bean-Level
      • Compile-time check + IDE Support
• Support für Model-Validation
• Sorted violation messages
• DI Support für Constraint-Validatoren
17.12.2009
Bean-Validation & MyFaces ExtVal - 2
• Severity Aware Validation
• Client-side validation in Kombination mit
  MyFaces Trinidad
• Group Storage
     (ermöglicht die Speicherung von Validation-
     Groups in unterschiedlichen Quellen)
• Validation Interception
• Validation Exception Intercepetion
• Einige Add-ons


17.12.2009
Weitere Details




17.12.2009
JSF-Request-Lifecycle - Validierung

            Faces-                   Apply                    Conversion
                          Restore                   Process
            request                   Request                      and
                          View                      Events
                                     Values                    Validation




                                                                                Process
                                                                                 events
   CLIENT




                                                                                Update
                                                                                Model
            Faces-
            response    Render      Process       Invoke      Process
                       Response      Events     Application   Events

                                                                  Validation / Conversion Errors
                                                                  Render Response




17.12.2009
Exkurs: ExtVal im JSF-Lifecycle

                     Apply       Conversion
      Restore                                  Update      Invoke       Render
                      Request         and
                                                         Application
      View                                     Model                   Response
                     Values       Validation




                                                 ExtVal
              ExtVal            Std. JSF
                                                 Cross-
             Validation         Validation
                                                Validation




17.12.2009
ExtVal-BV-Integration im JSF-Lifecycle

                Apply        Conversion
      Restore                              Update     Invoke       Render
                 Request          and
                                                    Application
      View                                 Model                  Response
                Values        Validation




                                                         ExtVal-BV
                ExtVal-BV          Std. JSF
                                                          Model
                Validation         Validation
                                                         Validation




17.12.2009
Group-Validation mit MyFaces ExtVal
• Via @BeanValidation
  (= typsichere Alternative zu f:validateBean)
• Nur bei Group-Validation (und Model Validation)
• Möglichkeiten
      •      Simple Angabe von Gruppen
      •      Einschränkung auf View-IDs
      •      Bedingungen via EL-Expression definieren
      •      Gruppen herausfiltern




17.12.2009
@BeanValidation Beispiele
• Group-Validation für alle Seiten, die dieses
  Page-Bean verwenden
     public class HelloWorldController {
        @BeanValidation(useGroups = User.class)
        private Person person = new Person();
        …
     }
• Group-Validation nach Seiten unterscheiden
     @BeanValidation.List({
        @BeanValidation(viewIds = "/page1.xhtml",
           useGroups = User.class),
        @BeanValidation(viewIds = "/page2.xhtml",
           useGroups = Admin.class)
     })
     public class HelloWorldController {
        private Person person = new Person();
        …
     }
17.12.2009
@ModelValidation
• Diese Validierung erfolgt nach der Phase
  „Update Model Values“
• Validiert wird
      • Base-Objekt der Property (Default)
      • Andere Objekte (via EL-Expression)
• Rollback via Add-on möglich
• Beispiel:
     @BeanValidation(modelValidation =
        @ModelValidation(isActive = true))




17.12.2009
@ModelValidation – Fehlermeldungen
• Fehler-Meldungen werden global angezeigt
  (inline ist optional möglich)
• Fehlermeldungen können bei Bedarf
  überschrieben werden




17.12.2009
ExtVal-Add-ons für JSR 303 Validation
•    Group-Validation via action-Methoden
•    Transactional model validation
•    Continue with warnings
•    Bypass BV
•    Tag als Alternative zu @BeanValidation
•    ...




17.12.2009
Q & A?




17.12.2009
Links
• JSR 303
       – Bean-Validation Specification
         http://jcp.org/en/jsr/detail?id=303
       – MyFaces ExtVal (BV-Integration)
         http://myfaces.apache.org/
         http://wiki.apache.org/myfaces/Extensions/Validator/

• Specification implementations
       – http://www.hibernate.org/412.html
       – http://oval.sourceforge.net
       – http://code.google.com/p/agimatec-validation/


• Trainings & Support (ExtVal und/oder BV)
       – http://www.irian.at/extval/

17.12.2009

Metadatenbasierte Validierung

  • 1.
  • 2.
    Metadatenbasierte Validierung JSR 303 and more... 17.12.2009
  • 3.
    DI (FH) Gerhard.Petracek@irian.at • JCP-Member (Bean Validation Expert Group) • Apache MyFaces • Committer • PMC Member • Project Lead (ExtVal) • Schulungen zu JEE (v.a. JSF) • Autor verschiedener Fachartikel • Vorträge (Software und Web-Engineering) 17.12.2009
  • 4.
    Bean-Validation Ökosystem -1 • Spec.-Lead: Emmanuel Bernard • EG-Members • Internationale Firmen wie • Sun • Oracle • Google • uvm. • Einige Project Leads erfolgreicher Validierungsframeworks • Von Irian Solutions: Gerhard Petracek 17.12.2009
  • 5.
    Bean-Validation Ökosystem -2 • Implementierungen • Hibernate-Validator v4+ (RI) • Agimatec-validation (bald bei Apache SF) • OVal • JSF Support lt. Spec. für JSF 2+ • Adapter für JSF • MyFaces ExtVal BV-Integration-Module (für JSF 1.x und JSF 2+) 17.12.2009
  • 6.
    Hello Bean-Validation • Beispiel public class Customer { @NotNull private String firstName; public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } } 17.12.2009
  • 7.
    Standard Constraints -Übersicht • @AssertFalse / @AssertTrue • @DecimalMax / @DecimalMin • @Digits • @Future / @Past • @Max / @Min • @NotNull / @Null • @Pattern • @Size 17.12.2009
  • 8.
  • 9.
    Eigene Constraints Definieren •Erforderliche Bestandteile: • @Constraint (1-n Constraint-Validator(en)) • Target • FIELD • METHOD • TYPE • ANNOTATION_TYPE (für Constraint composition) • Und natürlich: Retention RUNTIME • Verpflichtende Attribute • message • groups • payload 17.12.2009
  • 10.
    Constraint-Validatoren • Implementierung von javax.validation.ConstraintValidator • initialize • isValid • Ist auf ein Constraint und einen Ziel-Typ beschränkt (via Generics) • Ein Constraint kann für mehrere Ziel-Typen verwendet werden • Bsp.: @Size für String, Array, Map, … 17.12.2009
  • 11.
    Error Messages • Message-Interpolatortransformiert Nachrichten automatisch • Keys • Hardcoded • Beispiel: @Size(min = 1, max = 10, message = "{firstName.lengthMessage}") Resource-Bundle: firstName.lengthMessage = Name must be between {min} and {max} 17.12.2009
  • 12.
    Group-Validation / Partial-Validation •Default: Constraint ist der Default-Gruppe zugeordnet (javax.validation.groups.Default) • Gruppen sind Interfaces und somit typesafe • Ermöglicht Validierung impliziter Gruppen • Beispiel: @NotNull entspricht @NotNull(groups = Default.class) 17.12.2009
  • 13.
    Reihenfolge bei derValidierung • Default: keine Reihenfolge • @GroupSequence ermöglicht die Angabe der Reihenfolge • Rechenintensive Gruppen sollen am Ende validiert werden • Validierung einer Gruppe findet statt, wenn die vorherige Gruppe fehlerfrei validiert wurde 17.12.2009
  • 14.
    Multiple-Constraints • Via Annotation-Element (Array vom Constraint-Typ) • Beispiel: Zuordnung von Constraints zu Rollen (via Group-Validation) @Size.List({ @Size(groups = Default.class min = 10, max = 20), @Size(groups = AdminGroup.class min = 1, max = 30) }) 17.12.2009
  • 15.
    Validation-Payload • Subset vonValidation-Parameter (siehe MyFaces ExtVal >= 3. Release) • javax.validation.Payload • Für Validation-Clients wie MyFaces ExtVal nutzbar – bspw.: Severity.Warn.class • Beispiel: public class Severity { public static class Warn implements Payload {} public static interface Error extends Payload {} } 17.12.2009
  • 16.
    Graph-Validation • Wird einObjekt validiert, dann werden referenzierte Objekte mit-validiert, wenn @Valid verwendet wird • Auch Inhalte von Collections und Arrays • Keine Validierung erfolgt, wenn Lazy- Properties noch nicht geladen wurden 17.12.2009
  • 17.
    Class-Level Validation • Constraintfür e. Klasse/Interface • Wird vererbt aber nicht überschrieben • Bei der Validierung liegt das aktuelle Objekt im gesamten vor • In JSF nur mit MyFaces ExtVal 17.12.2009
  • 18.
    Constraint-Composition • Mit Constraintsannotierte Constraints • Wiederverwendung von Constraints • Violation-Message(s) • Default: Messages der einzelnen Constraints • Mit @ReportAsSingleViolation wird die Error-Message des Haupt-Constraints angezeigt 17.12.2009
  • 19.
    [DEMO] JSR 303in Action 17.12.2009
  • 20.
    JSR 303 inWeb-Applikationen 17.12.2009
  • 21.
    Bean-Validation und JSF •Änderungen in JSF 2.0 für JSR 303 • Default Validator • Geändertes Verhalten v. required-Attribut • ValidatorException mit mehreren Messages • Verschiedene Konfigurationsparameter • Spezieller Tag (validiert Default-Gruppe): <f:validateBean/> • Beispiele: • Validierung der Default Group • Group-Validation <f:validateBean validationGroups = "at.irian.demo.validation.groups.Order"/> 17.12.2009
  • 22.
    MyFaces Extensions Validator Ermöglicht die einfache Umsetzung von fortschrittlichen Validierungskonzepten für JSF-Applikationen auf Basis von dynamischen Metadaten. 17.12.2009
  • 23.
    [DEMO] JSR 303and JSF 17.12.2009
  • 24.
    Bean-Validation & MyFacesExtVal - 1 • MyFaces ExtVal bietet JSR 303 Integration für alle JSF Versionen • Integration als unabhängiges Validation-Module • Group-Validation erfolgt via Annotation • Definition (norm.) auf Page-Bean-Level • Compile-time check + IDE Support • Support für Model-Validation • Sorted violation messages • DI Support für Constraint-Validatoren 17.12.2009
  • 25.
    Bean-Validation & MyFacesExtVal - 2 • Severity Aware Validation • Client-side validation in Kombination mit MyFaces Trinidad • Group Storage (ermöglicht die Speicherung von Validation- Groups in unterschiedlichen Quellen) • Validation Interception • Validation Exception Intercepetion • Einige Add-ons 17.12.2009
  • 26.
  • 27.
    JSF-Request-Lifecycle - Validierung Faces- Apply Conversion Restore Process request Request and View Events Values Validation Process events CLIENT Update Model Faces- response Render Process Invoke Process Response Events Application Events Validation / Conversion Errors Render Response 17.12.2009
  • 28.
    Exkurs: ExtVal imJSF-Lifecycle Apply Conversion Restore Update Invoke Render Request and Application View Model Response Values Validation ExtVal ExtVal Std. JSF Cross- Validation Validation Validation 17.12.2009
  • 29.
    ExtVal-BV-Integration im JSF-Lifecycle Apply Conversion Restore Update Invoke Render Request and Application View Model Response Values Validation ExtVal-BV ExtVal-BV Std. JSF Model Validation Validation Validation 17.12.2009
  • 30.
    Group-Validation mit MyFacesExtVal • Via @BeanValidation (= typsichere Alternative zu f:validateBean) • Nur bei Group-Validation (und Model Validation) • Möglichkeiten • Simple Angabe von Gruppen • Einschränkung auf View-IDs • Bedingungen via EL-Expression definieren • Gruppen herausfiltern 17.12.2009
  • 31.
    @BeanValidation Beispiele • Group-Validationfür alle Seiten, die dieses Page-Bean verwenden public class HelloWorldController { @BeanValidation(useGroups = User.class) private Person person = new Person(); … } • Group-Validation nach Seiten unterscheiden @BeanValidation.List({ @BeanValidation(viewIds = "/page1.xhtml", useGroups = User.class), @BeanValidation(viewIds = "/page2.xhtml", useGroups = Admin.class) }) public class HelloWorldController { private Person person = new Person(); … } 17.12.2009
  • 32.
    @ModelValidation • Diese Validierungerfolgt nach der Phase „Update Model Values“ • Validiert wird • Base-Objekt der Property (Default) • Andere Objekte (via EL-Expression) • Rollback via Add-on möglich • Beispiel: @BeanValidation(modelValidation = @ModelValidation(isActive = true)) 17.12.2009
  • 33.
    @ModelValidation – Fehlermeldungen •Fehler-Meldungen werden global angezeigt (inline ist optional möglich) • Fehlermeldungen können bei Bedarf überschrieben werden 17.12.2009
  • 34.
    ExtVal-Add-ons für JSR303 Validation • Group-Validation via action-Methoden • Transactional model validation • Continue with warnings • Bypass BV • Tag als Alternative zu @BeanValidation • ... 17.12.2009
  • 35.
  • 36.
    Links • JSR 303 – Bean-Validation Specification http://jcp.org/en/jsr/detail?id=303 – MyFaces ExtVal (BV-Integration) http://myfaces.apache.org/ http://wiki.apache.org/myfaces/Extensions/Validator/ • Specification implementations – http://www.hibernate.org/412.html – http://oval.sourceforge.net – http://code.google.com/p/agimatec-validation/ • Trainings & Support (ExtVal und/oder BV) – http://www.irian.at/extval/ 17.12.2009