CarbonRider - Articles

Apache CXF – Code First – Schema validation demystified

Posted by Carbon Rider on Sunday, March 21st, 2010

In my previous article, I talked about how you can use schemaLocation property to override default CXF behaviour for Code First approach. But the approach had one major problem – Defining entire schema structure in one XSD file.

After spending few hours finding an option to get rid of this problem, I could finally found one tweak. The tweak is all about configuration and having an appropriate directory structure so that CXF can make use of already defined XSD structure to validate SOAP requests. Just follow next few steps, we will be evaluating it by considering one sample example.

1. Define XSD with required structure and include/import the XSDs you want to define as common structures. In my case here is the XSD structure.
XSD Structure

2. The starting point for above structure is valueobjects.xsd and it includes one more XSD. (common/commontypes.xsd). The type of firstName element is referenced from commontypes.xsd.

valueobjects.xsd



	
		
			
			
			
			
		
	



CommonTypes.xsd


	
		
	


3. Define separate XSD to declare types for request & response. In this example, the structure is defined in RequestResponse.xsd




	
		
	


	
		
	

4. Configure schemaLocation for webservice and enable schema validation.


	
		ws-schema/RequestResponse.xsd
	
	
		
	

5. In given XSD, following validation is defined
- Maximum characters allowed for First Name are 5.

If you will send SOAP request with data not satisfying above validation, you will get schema validation error, similar to following

The tweak works because the root path for CXF services is configured as “/service/*” and the XSD defining types are stored in “schema” folder.


	CXFServlet
	/service/*

Here is a sample SOAP request to my webservice and it gives following error.


   
   
      
         
         
            Yogesh
            Jadhav
            10
            A09PP
         
      
   

SOAP Response


   
      
         soap:Client
         Unmarshalling Error: cvc-maxLength-valid: Value 'Yogesh' with length = '6' is not facet-valid with respect to maxLength '5' for type 'firstNameType'.
      
   

Posted in: Articles.

Leave a Reply

*