How to Validate XML on Gradle build

code

 646 total views

In this blog, we will discuss why do we need to validate XML on Gradle build and how to do it.

Many of the enterprises are adopting Gradle to build their projects.

With its various components like task, plugin, etc Gradle is a strong tool to build your Java project.

Any typical java project not only contains JAVA files it might also contain other files, for example, JSON and XML files.

Purpose:

Ok so let’s discuss the “Why” part here, we always validate XML before parsing it but mostly at runtime.

There are various cases when we check-in the wrong XML into the repository and all developers take the latest revision of the XML now all developers have this faulty XML.

Now you can face many issues because of this faulty XML the two most common would be :

  • Failure on server startup if you are parsing the faulty XML.
  • Some of your features stop working that use this faulty XML.

So why not Validate all the XML related changes at the time of project build, which will definitely gonna save a lot of debugging effort for a silly mistake.

Solution:

So now you are aware of the problem related to using faulty XML lets talk about the “How” part now.

There are many ways to implement this solution, I am implementing it using a Gradle task created in a Gradle file.

Create ValidateXML.gradle file and add it root folder of your project.

  1. Add these lines of code in your validateXML.gradle
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

class XMLValidationTask extends DefaultTask
{
    @TaskAction
    def taskAction()
    {
       String rootDir = project.rootDir.toString();
       try {
       String xsdPath =rootDir+"/src/main/resource/xsd/testXSD.xsd";
       String xmlPath =rootDir+"/src/main/resource/xml/testXML.xml";
            SchemaFactory factory = 
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(xmlPath)));
        } catch (IOException | SAXException e) {
            //System.out.println("Exception: "+e.getMessage());
            println 'XML not valid ::: '+false
            throw new GradleException("Exception: "+e.getMessage());

            //return false;
        }
        println 'XML validated ::: '+true
        return true;
    }
}


task poc(type: XMLValidationTask){
    println('Inside poc task')
}

build.finalizedBy(poc)

2. Now call this validateXML.gradle from your projects build.gradle

apply from: 'validateXML.gradle'

So in above code, we are validating test testXML.xml against testXSD.xsd .

Once all the above configuration is done just build your Gradle project.

It will look some thing like below screenshot:

Lets also test a negative case, where I will modify an element in the XML and lets see what happens to the build.

I have modified one of the attribute id to name, and as my XSD does not allow this name attribute the build has failed.

In Conclusion, I would say its always better to adopt a fail-first technique which will save a lot of your and your team’s time.

Leave a Reply

Your email address will not be published. Required fields are marked *