Skip to main content

Validating XML messages against more than one XSD with WSO2 ESB Validate mediator

Request validation is one of the important feature of any ESB. If you do not validate the request, it will go through your system and make unnecessary traffic on your resources. If you could validate the requests at the beginning of your message flow, that would help you to respond quickly and avoid resource utilization for wrong requests.

WSO2 ESB is the world's fastest one most comprehensive open source ESB available in the market. It is driven by the award winning WSO2 Carbon platform which you can use for any of your SOA implementations.

WSO2 ESB provides an OOTB (Out Of The Box) feature for request validation. This is called the Validate Mediator. This will provide you the capability to validate your request against any number of XSD schemas. If you are validating the request against a single XSD file, you can refer the below blog post written by Amani.

http://sparkletechthoughts.blogspot.com/2012/09/how-to-use-validate-mediator-to.html


In this blog post, I am going to discuss about a bit complex scenario where you have more than one XSD file to validate against. In this scenario, you have a XSD file A which has a reference to another XSD file B. In this kind of scenario, you need to take additional care when you implement your scenario.

1. Create your XSD file clear and make the references correct.

This is the main XSD(HelloSchema.xsd) file which we are validating the request against. This XSD has a reference to another XSD file(Hello.xsd)

HelloSchema.xsd
===============

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:q1="http://www.wso2.org/hello"
xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://www.wso2.org/types"
attributeFormDefault="qualified" elementFormDefault="qualified"
targetNamespace="http://www.wso2.org/types">
 <xs:import namespace="http://www.wso2.org/hello"
               schemaLocation="hello.xsd" />
<xs:element name="greet" type="q1:hello">
</xs:element>
</xs:schema>

In this schema definition, you can find there is a reference to the schema xmlns:q1="http://www.wso2.org/hello" which is defined in a secondary schema file. type "hello" is defined in the secondary schema given below.

Hello.xsd
==========

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://www.wso2.org/hello"
attributeFormDefault="qualified" elementFormDefault="qualified"
targetNamespace="http://www.wso2.org/hello">
<xs:element name="hello" type="ns:hello"></xs:element>
<xs:complexType name="hello">
<xs:sequence>
<xs:element minOccurs="1" name="name" >
 <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:minLength value="1" />
        </xs:restriction>
    </xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>

Now you are going to validate the request against the HelloSchema.xsd file which has a reference to Hello.xsd file.

2. Once you create your XSD files, upload them to WSO2 ESB registry under the path \_system\conf\. Now your XSD files should be in the below registry paths.

/_system/config/Hello.xsd
/_system/config/HelloSchema.xsd

3. Create the proxy service to validate the incoming request.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="MyValidateProxy"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <log level="full">
            <property name="Message" value="Inside Insequance"/>
         </log>
         <validate>
            <schema key="conf:/HelloSchema.xsd"/>
            <resource location="hello.xsd" key="conf:/Hello.xsd"/>
            <on-fail>
               <makefault version="soap11">
                  <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
                  <reason value="Invalid Request!!!"/>
                  <role/>
               </makefault>
               <log level="full"/>
               <property name="RESPONSE" value="true"/>
               <header name="To" action="remove"/>
               <send/>
               <drop/>
            </on-fail>
         </validate>
         <respond/>
      </inSequence>
      <outSequence>
         <send/>
      </outSequence>
   </target>
   <description/>
</proxy>
                               
In this proxy configuration, you can find the validate mediator configuration like below.

 <validate>
            <schema key="conf:/HelloSchema.xsd"/>
            <resource location="hello.xsd" key="conf:/Hello.xsd"/>
            <on-fail>
               <makefault version="soap11">
                  <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
                  <reason value="Invalid Request!!!"/>
                  <role/>
               </makefault>
               <log level="full"/>
               <property name="RESPONSE" value="true"/>
               <header name="To" action="remove"/>
               <send/>
               <drop/>
            </on-fail>
         </validate>

Here we are validating the request against the schema key conf:/HelloSchema.xsd it has a reference to another xsd which is stored with the location="hello.xsd". This value is the one we referenced inside the HelloSchema.xsd file like below.

 <xs:import namespace="http://www.wso2.org/hello"
               schemaLocation="hello.xsd" /> 

This is a very important reference and you should carefully understand this reference. This will make sure that the validate mediator can resolve the references correctly.

Now you have the proxy and the XSD files in place.

4. Send a request to the proxy service with the correct request like below.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <p:greet xmlns:p="http://www.wso2.org/types" xmlns:q="http://www.wso2.org/hello">
         <q:name>chanaka</q:name>
      </p:greet>
   </soapenv:Body>
</soapenv:Envelope>

Here you can see we are using two namespaces

xmlns:p="http://www.wso2.org/types" xmlns:q="http://www.wso2.org/hello"

which we have defined in two different xsd files. Once you send this request, it will respond with the same request since it validated the XSD correctly.

If you send a different request like below it will respond with a failure response.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <p:greet xmlns:p="http://www.wso2.org/types" xmlns:q="http://www.wso2.org/hello">
         <q:name></q:name>
      </p:greet>
   </soapenv:Body>
</soapenv:Envelope>

This will respond with the below response.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode xmlns:tns="http://www.w3.org/2003/05/soap-envelope">tns:Receiver</faultcode>
         <faultstring>Invalid Request!!!</faultstring>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

Here we go !!! The wrong request has been sent back with the fault message.

Comments

  1. I have tried above example and worked fine for me
    But I am trying to apply validation on dynamically created XML.
    But got some error.
    Please see below link

    http://stackoverflow.com/questions/25748669/wso2-esb-xsd-validation-on-xml/25749632#25749632

    Thanks for your help. :)

    ReplyDelete
  2. How to validate dynamically created xml file against xsd

    ReplyDelete
  3. Excellent article and this helps to enhance your knowledge regarding new things. Waiting for more updates.
    Angular CSS
    Angular Material

    ReplyDelete

  4. Awesome article! You are providing us very valid information. This is worth reading. Keep sharing more such articles.
    Data Science Course in Chennai
    Data Science Online Training
    Data Science Course in Coimbatore

    ReplyDelete

Post a Comment

Popular posts from this blog

How to protect your APIs with self contained access token (JWT) using WSO2 API Manager and WSO2 Identity Server

In a typical enterprise information system, there is a high chance that people will use different types of systems built by different vendors to implement certain types of functionalities. The APIs might be hosted in an API Manager developed by vendor A and the user management can be implemented using a different vendor (vendor B). In this type of a situation, one system will not be able to directly contact the other system but they want to use both systems in tandem. Self-contained access tokens are used in these types of situations where applications can get the token from one system and use that in another system to access protected resources. In this scenario, the second system does not need to make a contact to the first system over the network to validate the user information since the token is self-contained and it has relevant details about the user. This will improve the token processing time significantly since it completely removes the network interaction. The below fig...

WSO2 ESB creating a response for a "GET" request

When you are creating REST APIs with WSO2 ESB, you may need to send some response message back to the user when something goes wrong. In this kind of scenario, you can create a payload inside the ESB and send it back. For doing this, you can use the below configuration. <api xmlns=" http://ws.apache.org/ ns/synapse " name="LoopBackProxy" context="/loopback">    <resource methods="POST GET">       <inSequence>          <property name="NO_ENTITY_BODY" scope="axis2" action="remove"></property>          <log level="full"></log>          <payloadFactory media-type="xml">             <format>                <m:messageBeforeLoopBack xmlns:m=" http://services...

WSO2 ESB usage of get-property function

What are Properties? WSO2 has a huge set of mediators but property mediator is mostly used mediator for writing any proxy service or API. Property mediator is used to store any value or xml fragment temporarily during life cycle of a thread for any service or API. We can compare “Property” mediator with “Variable” in any other traditional programming languages (Like: C, C++, Java, .Net etc). There are few properties those are used/maintained by ESB itself and on the other hand few properties can be defined by users (programmers). In other words, we can say that properties can be define in below 2 categories: ESB Defined Properties User Defined Properties. These properties can be stored/defined in different scopes, like: Transport Synapse or Default Axis2 Registry System Operation Generally, these properties are read by get-properties() function. This function can be invoked with below 2 variations. get-property(String propertyName) get-property(String scop...