My journey to use a validation framework

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

1 comments

Comments 1 - 1 of 1 previous next Post a comment

  • + guest635fbb8 guest635fbb8 8 months ago
    Great presentation! I was looking for a validation framework that was both easy to use (no code bloat) and reusable in different layers of our application. Hibernate annotations seems to be the way to go indeed, even though we intend to use OpenJPA.

    (We chose OpenJPA for its better detachment support with fetchplans/fetch groups, which we think is almost a necessity if you have a remote rich client which will not use lazy loading for performance reasons and you don’t want to use unnecessary DTO’s).
Post a comment
Embed Video
Edit your comment Cancel

2 Favorites

My journey to use a validation framework - Presentation Transcript

  1. My Journey to Validate Muhammad Saqib Sarwar [email_address]
  2. 1.To share my experience(thought process) of choosing a Validator framework. 2.To deliver basic knowledge of my chosen tool. Basic Goals Muhammad Saqib Sarwar [email_address]
    • New Change Arrived in current project
      • DB Fields From 11 to 137
      • Account [54 Fields] Customer [74 Fields] Customer_account[9 Fields]
      • So Big Change on Message Validations
      • For: Create an Account Message
        • Total: 46 Fields
          • 14 Mandatory Fields
            • 13 have length checks
            • 5 have pattern checks
          • others if exist should be validated too ….
    How I felt the need ? Simply Means a huge collection of if-else statements Muhammad Saqib Sarwar [email_address]
    • 1 st I written required if-else statements.
    • BUT Soon
    • I Found
    • Myself
    • In huge
    • Mess .. 
    How I felt the need ? Muhammad Saqib Sarwar [email_address]
    • Asked the BOSS
    • Google “how to avoid too many if-else”
    • Placed Question on JavaRanch
    • Consulted with Colleagues
    • Surprised !
    • Business layer validation frameworks
    • exist in java world
    • I only know them as presentation
    • layer validator.
    What I did next … Muhammad Saqib Sarwar [email_address]
    • There are many available like
      • Spring’s own validation
      • Commons Validator
      • JaValid
      • Hibernate Validator (My Chosed One)
      • And many more …
    • Now the Question is
    • Which one to use ?
    • So I Sorted Few Priorities
      • It should Solves the problem
      • It should have Short learning curve
    Which one to use ..? Muhammad Saqib Sarwar [email_address]
    • First I looked at Validation in Spring 2.0.8 (as we already using it)
    • Two Parts in the Validation Package
      • Validator Interface Implementation
      • DataBinder
    • Primarily used in Spring-MVC framework
    • Have to implement complete validation logic in validate() method
    • Separate Validator for each entity
    • Not fallow any standard (like few emerging in the market)
    Validation in Spring 2.0.8 Muhammad Saqib Sarwar [email_address]
    • Validation of JavaBeans based on an xml file
    • Provides two distinct sets of functionality
      • A configurable (typically XML) validation engine
      • Reusable "primitive" validation methods
    • Steps
      • Create XML file
      • Instantiate Validator class (org.apache.commons.validator.Validator)
      • Add Resources (JavaBean,Locale)
      • Call Validator’s validate method
      • Evaluate Results
    Commons Validator Muhammad Saqib Sarwar [email_address]
    • Heavily depends on XML
    • Manual evaluation of errors [  ]
    • No default error messages
    • Lengthy validation code
    • Fallow No Standard
    Commons Validator Muhammad Saqib Sarwar [email_address]
    • I want something easier than XML so searched for Annotation based bean validation frameworks and found JaValid.org
    • It is an Annotations based bean validation framework
    • Could be used standalone
    • Provides full integration with Spring, JSF, Facelets and DB
    • Customizable and Extensible
    • Built in annotations for basic validations
    • Well elaborated documentation
    • Well documented source code
    Muhammad Saqib Sarwar [email_address]
    • Annotate Bean’s Properties/(getter Methods)
    • Instantiate Validator implementation
    • Pass bean instance to Validator
    • Validator returns List<ValidationMessage>
    Steps to use JaValid Muhammad Saqib Sarwar [email_address]
    • only few built in annotation constraints
    • building new constraints are little lengthier
    • use XML configuration file to know about annotation classes and their related validator classes.
    • error messages are hard coded
    • ValidationMessage object is not customizable
    • does not fallow any standard for validation
    Few disadvantages of JaValid ! Good Solution but not as simple and easy as hibernate validator Muhammad Saqib Sarwar [email_address]
    • Annotations based bean validation framework
    • Aims to provide implementation of the emerging standard (JSR - 303 Bean Validation)
    • Purely intended for multi-layered data validation
    • Constraints are expressed in a single place (model)
    • Not limited to use with hibernate
      • Can be used any where in application
      • Can be used with any java persistence provider
    Hibernate Validator Muhammad Saqib Sarwar [email_address]
    • Decent Collection of Built in Constraints
      • @Length (min=,max=)
      • @Max(value=)
      • @Min(value=)
      • @NotNull
      • @NotEmpty
      • @Past
      • @Future
      • @Size(min=, max=)
    Hibernate Validator
    • @Pattern(regex=&quot;regexp”, flag=)
    • @Range(min=, max=)
    • @AssertFalse
    • @AssertTrue
    • @Valid
    • @Email
    • @CreditCardNumber
    • @Digits
    • @EAN
    • Few more …
    Muhammad Saqib Sarwar [email_address]
    • Error Messages
      • Validator returns array of InvalidValue
      • InvalidValue contains constraint violation information (bean, name, path, value etc)
      • It also contains Error Description Message
      • we can override Error Messages
          • By Creating Own ValidatorMessages.properties
          • we can embed constraint parameters in messages
    Hibernate Validator Muhammad Saqib Sarwar [email_address]
  3. Sample Code [Annotated Account Bean] /*--------- Simple Bean ---------------*/ public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
  4. Validation Code: Account account = new Account(); account.setAccountTitle(&quot;Mobex Ltd&quot;); ClassValidator<Account> accountValidator = new ClassValidator<Account>(Account.class); InvalidValue[] validationMessages = accountValidator. getInvalidValues (account); for(InvalidValue msg:validationMessages) System.out.println(msg.getPropertyPath()+&quot;-&quot;+msg.getMessage()); OUTPUT accountTitle-length must be between 10 and 100 processingCode-may not be null or empty Hibernate Validator Muhammad Saqib Sarwar [email_address]
  5. public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
  6. public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty @ProcessingCode(code=IProcessingCode. CHECK_BALANCE) private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
    • Steps For Writing Our Own Constraints
      • Constraint Descriptor (annotation)
      • Constraint Validator (implementation class)
    Hibernate Validator Muhammad Saqib Sarwar [email_address]
      • Constraint Descriptor (annotation)
    • @Documented
    • @ValidatorClass(ProcessingCodeValidator. class)
    • @Target({METHOD, FIELD})
    • @Retention(RUNTIME)
    • public @interface ProcessingCode {
    • String code();
    • String message() default &quot;Invalid Processing Code&quot;;
    • }
    Hibernate Validator org.hibernate.validator.ValidatorClass Muhammad Saqib Sarwar [email_address]
  7. 2. Constraint Validator Implementation Class public class ProcessingCodeValidator implements Serializable, Validator<ProcessingCode> { private static final long serialVersionUID = 1146464976464879846L; private String code; public void initialize (ProcessingCode parameter) { code = parameter.code(); } public boolean isValid (Object value) { if ( value == null )return false; if (!( value instanceof String)) return false; String str = (String) value; if(str.equals(code)) return true; return false; } } Muhammad Saqib Sarwar [email_address]
  8. Account account = new Account(); account.setAccountTitle(&quot;Mobex Ltd&quot;); account.setProcessingCode(IProcessingCode. CREDIT_ACCOUNT); ClassValidator<Account> accountValidator = new ClassValidator<Account>(Account.class); InvalidValue[] validationMessages = accountValidator.getInvalidValues(account); for(InvalidValue msg:validationMessages) System. out.println(msg.getPropertyPath()+&quot;-&quot;+msg.getMessage()); OUTPUT accountTitle-length must be between 10 and 100 processingCode-Invalid Processing Code Hibernate Validator Muhammad Saqib Sarwar [email_address]
    • Using the Validator
      • Database Schema-Level Validation
      • ORM Integration
        • Hibernate event-based validation
          • PreInsertEvent
          • PreUpdateEvent
        • Java Persistence event-based validation
      • Application-level validation
      • Presentation layer validation
    Hibernate Validator Muhammad Saqib Sarwar [email_address]
    • Benifits
      • simplicity
        • Avoid XML based configuration
        • Could be learned in short time
        • Could be implemented in minutes
      • Constraints annotation could be applied to
        • Property
        • Getter method
        • Bean Class
      • Aims to Fallows a developing standard (JSR-303 Bean Validation)
      • Fallows DRY Principle [multi-layered validation]
      • etc [many more to explore]
    Muhammad Saqib Sarwar [email_address]
    • We Use Validation Framework
      • To avoid series of messy if-else statements
      • To Increase code readability
      • To make code easily maintainable
      • To avoid writing validation on multiple layers
      • To increase productivity
    Summary Muhammad Saqib Sarwar [email_address]
SlideShare Zeitgeist 2009

+ saqibsarwarsaqibsarwar Nominate

custom

1356 views, 2 favs, 1 embeds more stats

Presentation about how i evaluated different valida more

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 1356
    • 1348 on SlideShare
    • 8 from embeds
  • Comments 1
  • Favorites 2
  • Downloads 15
Most viewed embeds
  • 8 views on http://javaspell.blogspot.com

more

All embeds
  • 8 views on http://javaspell.blogspot.com

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories