SlideShare a Scribd company logo
REQUEST
VALIDATION:SPRING
REST-PART 2
Presented By Sabir Khan
Background
 Please refer my earlier presentation to get basics,
https://www.slideshare.net/MohammadSabirKhan/spring-rest-request-validation
 Part -1 presentation highlights use of @Valid annotation
 With @Valid annotation, you can validate Java POJOs i.e. specific to Spring REST, it
would be @RequestBody
 If you simply place @Valid & @NotEmpty to a GET request @RequestParam or
@PathVariable, it wouldn’t work i.e. it will have no effect – validator wouldn’t be
invoked
 Directly placing JSR annotations for method parameters was not supported in bean
validation 1.0 ( JSR – 303 ) and support started from bean validation 1.1 ( JSR –
349)
 So you have to make sure that you are using JSR – 349 implementation before using
this feature
Why we need it?
 For a REST End Point – Its not guaranteed that client will always send a well formed
request
 REST Entry Point need not to proceed if request is invalid and data sent is improper
 If request is invalid, REST Entry Point need to return an error response automatically and
service developers need not be tweaking service logic for data invalidity
 Validation needs to be segregated system component for maintainable flow and
readable code
 As described in previous slide, you will have to convert method parameters into a POJO
to validate with @Valid, we are trying to avoid it and directly process validation
annotations placed on method signatures for simple arguments like String etc.
 Lots of confusion is out there on Internet because of change of bean validation
standards, types of validations supported and various techniques to invoke validator
Getting Started : Coding…Dependency
 First you need to include validation API standard and implementations in your REST application
that supports JSR – 349.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
Getting Started : Coding…Dependency…Contd
 Out of those two dependencies, validation-api-1.1.0.Final.jar is a reference to JSR –
349 while hibernate-validator-5.3.4.Final.jar is a JSR-349 implementation
 Hibernate JAR has nothing to do with hibernate ORM implementation, its simply a
bean validation implementation and can be used in non – hibernate environments.
Here we are trying to use for Spring REST service.
 If you are using Spring Boot, these two dependencies will already be there as part of
below dependency and not required to include separately.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Coding…Enable Method Validation
 Processing validation annotations as part of method signatures are not
enabled by default.
 You need to tell Spring Framework to process @Email, @NotNull,
@NotEmpty annotations included in method signatures directly without
@Valid annotation
 This is achieved in two steps,
1. Place @Validated -
org.springframework.validation.annotation.Validated at your
controller class, like ,
@RestController
@RequestMapping("/…")
@Validated
Coding…Enable Method Validation…Contd
2. Place these two beans in your Spring Configuration i.e. in
@Configuration class available for application
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();
mvProcessor.setValidator(validator());
return mvProcessor;
}
@Bean
public LocalValidatorFactoryBean validator(){
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setProviderClass(HibernateValidator.class);
validator.afterPropertiesSet();
return validator;
}
Coding…Enable Method Validation…Contd
 You have to note that Spring has its own validators and we have to somehow tell
Spring that method level annotation processing is enabled and which validator
factory to use to process those validations ( Its Hibernate implementation in our
case )
 Hibernate validator documentation says that you can invoke their validator via some
AOP kind of mechanism and Spring provides that mechanism , refer JIRA -
https://jira.spring.io/browse/SPR-8199 to know a bit more
 In Absence of this in build mechanism, you will have to invoke validator on your own
as described in - https://github.com/gunnarmorling/methodvalidation-integration
 Anyway, now you are set to validate your @RequestParam & @PathVariable directly
in method signatures
Coding…Validate
 Now , you can do below
@RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes=MediaType.APPLICATION_JSON_VALUE, produces
=MediaType.APPLICATION_JSON_VALUE )
public ResponseBean<String> testValidated( @Email(message="email RequestParam is not a valid email address") @NotEmpty(message="email
RequestParam is empty") @RequestParam("email") String email ){
ResponseBean<String> response = new ResponseBean<>();
……
return response;
}
Above code tells that for @RequestParam(“email”) – validate if it’s a valid email address and if its not empty String
You can externalize message Strings
No need to place @Valid or @Validated in method signature
You can use other available annotations as per your need
Coding…Exception Handler
 In part – 1 of presentation, we saw that @Valid throws – MethodArgumentNotValidException but @Validated throws a different exception –
ConstraintViolationException so we will have to write a handler for this exception too.
@RestControllerAdvice(value=“*.controller") -> this is basically controller package location
public class ApplicationExceptionHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(ConstraintViolationException exception){
 StringBuilder messages = new StringBuilder();
 ResponseBean response = new ResponseBean();
 int count = 1;
 for(ConstraintViolation<?> violation:exception.getConstraintViolations()){
 messages.append(" "+count+"."+violation.getMessage());
 ++count;
 }
 response.setResponse(Constants.FAILURE);
 response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);
 response.setMessage(messages.toString());
 return response;
}
}
ResponseBean is my application specific class that I wrote my own , you can have your own.
This handler will automatically be called if validation fails and response returned to your client.
References
1. https://github.com/gunnarmorling/methodvalidation-integration
2. http://apprize.info/javascript/wrox/16.html
3. https://jira.spring.io/browse/SPR-8199
4. https://dzone.com/articles/method-validation-spring-31
5. http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-method-constraints
Thank You !!
Thank You !!

More Related Content

What's hot

Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
Raffaele Chiocca
 
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debuggingATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
Agile Testing Alliance
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
girichinna27
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
Juan Antonio
 
Hybrid framework
Hybrid frameworkHybrid framework
Hybrid frameworkSudhakar Mangi
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
SOAT
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand
SOAT
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
Abhijeet Vaikar
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API Project
Pantheon
 
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
SOAT
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automationsrivinayak
 
Mock Server Using WireMock
Mock Server Using WireMockMock Server Using WireMock
Mock Server Using WireMock
Globant
 
Jsf
JsfJsf
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIs
Jason Weden
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
Yuriy Bezgachnyuk
 

What's hot (19)

Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Selenium Handbook
Selenium HandbookSelenium Handbook
Selenium Handbook
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
 
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debuggingATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
 
Hybrid framework
Hybrid frameworkHybrid framework
Hybrid framework
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API Project
 
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automation
 
Mock Server Using WireMock
Mock Server Using WireMockMock Server Using WireMock
Mock Server Using WireMock
 
Jsf
JsfJsf
Jsf
 
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIs
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 

Similar to Request Validation In Spring Rest-Part2

Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
Abhishek Saxena
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST url
Xebia IT Architects
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
jbsysatm
 
OAuth Authorization flows in salesforce
OAuth Authorization flows in salesforceOAuth Authorization flows in salesforce
OAuth Authorization flows in salesforce
Kishore B T
 
Hackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platformHackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platform
Ihor Uzhvenko
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
Mek Srunyu Stittri
 
A Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingA Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API Testing
pCloudy
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor Monitoring
Anthony Ferrari
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-exam
dmz networks
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
Saurabh Dixit
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale
 
AAD B2C custom policies
AAD B2C custom policiesAAD B2C custom policies
AAD B2C custom policies
Rory Braybrook
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhAnirudh Bhatnagar
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
saqibsarwar
 
Open sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercisesOpen sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercises
vikram sukumar
 
Api testing
Api testingApi testing
Api testing
Keshav Kashyap
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaydeep Kale
 

Similar to Request Validation In Spring Rest-Part2 (20)

Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST url
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
 
OAuth Authorization flows in salesforce
OAuth Authorization flows in salesforceOAuth Authorization flows in salesforce
OAuth Authorization flows in salesforce
 
Hackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platformHackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platform
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
 
A Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingA Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API Testing
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor Monitoring
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-exam
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
 
AAD B2C custom policies
AAD B2C custom policiesAAD B2C custom policies
AAD B2C custom policies
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudh
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
 
Open sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercisesOpen sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercises
 
Api testing
Api testingApi testing
Api testing
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

Request Validation In Spring Rest-Part2

  • 2. Background  Please refer my earlier presentation to get basics, https://www.slideshare.net/MohammadSabirKhan/spring-rest-request-validation  Part -1 presentation highlights use of @Valid annotation  With @Valid annotation, you can validate Java POJOs i.e. specific to Spring REST, it would be @RequestBody  If you simply place @Valid & @NotEmpty to a GET request @RequestParam or @PathVariable, it wouldn’t work i.e. it will have no effect – validator wouldn’t be invoked  Directly placing JSR annotations for method parameters was not supported in bean validation 1.0 ( JSR – 303 ) and support started from bean validation 1.1 ( JSR – 349)  So you have to make sure that you are using JSR – 349 implementation before using this feature
  • 3. Why we need it?  For a REST End Point – Its not guaranteed that client will always send a well formed request  REST Entry Point need not to proceed if request is invalid and data sent is improper  If request is invalid, REST Entry Point need to return an error response automatically and service developers need not be tweaking service logic for data invalidity  Validation needs to be segregated system component for maintainable flow and readable code  As described in previous slide, you will have to convert method parameters into a POJO to validate with @Valid, we are trying to avoid it and directly process validation annotations placed on method signatures for simple arguments like String etc.  Lots of confusion is out there on Internet because of change of bean validation standards, types of validations supported and various techniques to invoke validator
  • 4. Getting Started : Coding…Dependency  First you need to include validation API standard and implementations in your REST application that supports JSR – 349. <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.3.4.Final</version> </dependency>
  • 5. Getting Started : Coding…Dependency…Contd  Out of those two dependencies, validation-api-1.1.0.Final.jar is a reference to JSR – 349 while hibernate-validator-5.3.4.Final.jar is a JSR-349 implementation  Hibernate JAR has nothing to do with hibernate ORM implementation, its simply a bean validation implementation and can be used in non – hibernate environments. Here we are trying to use for Spring REST service.  If you are using Spring Boot, these two dependencies will already be there as part of below dependency and not required to include separately. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 6. Coding…Enable Method Validation  Processing validation annotations as part of method signatures are not enabled by default.  You need to tell Spring Framework to process @Email, @NotNull, @NotEmpty annotations included in method signatures directly without @Valid annotation  This is achieved in two steps, 1. Place @Validated - org.springframework.validation.annotation.Validated at your controller class, like , @RestController @RequestMapping("/…") @Validated
  • 7. Coding…Enable Method Validation…Contd 2. Place these two beans in your Spring Configuration i.e. in @Configuration class available for application @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor(); mvProcessor.setValidator(validator()); return mvProcessor; } @Bean public LocalValidatorFactoryBean validator(){ LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setProviderClass(HibernateValidator.class); validator.afterPropertiesSet(); return validator; }
  • 8. Coding…Enable Method Validation…Contd  You have to note that Spring has its own validators and we have to somehow tell Spring that method level annotation processing is enabled and which validator factory to use to process those validations ( Its Hibernate implementation in our case )  Hibernate validator documentation says that you can invoke their validator via some AOP kind of mechanism and Spring provides that mechanism , refer JIRA - https://jira.spring.io/browse/SPR-8199 to know a bit more  In Absence of this in build mechanism, you will have to invoke validator on your own as described in - https://github.com/gunnarmorling/methodvalidation-integration  Anyway, now you are set to validate your @RequestParam & @PathVariable directly in method signatures
  • 9. Coding…Validate  Now , you can do below @RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes=MediaType.APPLICATION_JSON_VALUE, produces =MediaType.APPLICATION_JSON_VALUE ) public ResponseBean<String> testValidated( @Email(message="email RequestParam is not a valid email address") @NotEmpty(message="email RequestParam is empty") @RequestParam("email") String email ){ ResponseBean<String> response = new ResponseBean<>(); …… return response; } Above code tells that for @RequestParam(“email”) – validate if it’s a valid email address and if its not empty String You can externalize message Strings No need to place @Valid or @Validated in method signature You can use other available annotations as per your need
  • 10. Coding…Exception Handler  In part – 1 of presentation, we saw that @Valid throws – MethodArgumentNotValidException but @Validated throws a different exception – ConstraintViolationException so we will have to write a handler for this exception too. @RestControllerAdvice(value=“*.controller") -> this is basically controller package location public class ApplicationExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseBean handle(ConstraintViolationException exception){  StringBuilder messages = new StringBuilder();  ResponseBean response = new ResponseBean();  int count = 1;  for(ConstraintViolation<?> violation:exception.getConstraintViolations()){  messages.append(" "+count+"."+violation.getMessage());  ++count;  }  response.setResponse(Constants.FAILURE);  response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);  response.setMessage(messages.toString());  return response; } } ResponseBean is my application specific class that I wrote my own , you can have your own. This handler will automatically be called if validation fails and response returned to your client.
  • 11. References 1. https://github.com/gunnarmorling/methodvalidation-integration 2. http://apprize.info/javascript/wrox/16.html 3. https://jira.spring.io/browse/SPR-8199 4. https://dzone.com/articles/method-validation-spring-31 5. http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-method-constraints

Editor's Notes

  1. NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.