Thursday, April 19, 2012

How to validate an XML against XSD schema

I found this to be useful to share with you all. Because XML validation against a defined schema is very essential.

I will be mainly using Apache Xerces library to implement this functionality.

You will need these to be as imports to the following code block.
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
This will be the code block.
  SAXParser parser = new SAXParser();
                
  parser.setFeature("http://xml.org/sax/features/validation", true);
  parser.setFeature("http://apache.org/xml/features/validation/schema",true);

  //Set the validation/schema feature to true to report validation errors against a schema.
  parser.setFeature("http://apache.org/xml/features/validation/schema-full-  checking", true);

  parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "FileURLToTheSchema");

  Validator handler = new Validator();
  parser.setErrorHandler(handler);

  parser.parse(URLToTheXMLFile);

  FileURLToTheSchema,URLToTheXMLFile are URLs given as i.e file:///home/etc/.. 

You can use your own schema and a sample corresponding XML file and test this. This will throw meaningful Exceptions when parsing fails.

So following will be the Validator class which is mentioned above. This will allows us to register it as an ErrorHandler with the parser.

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class Validator extends DefaultHandler {

    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    public void error(SAXParseException exception)
            throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void fatalError(SAXParseException exception)
            throws SAXException {
        validationError = true;
        saxParseException = exception;
    }

    public void warning(SAXParseException exception)
            throws SAXException {
    }
}
References : http://onjava.com/onjava/2004/09/15/schema-validation.html

Thursday, March 1, 2012

Maven Axis2 aar plugin:Ignore maven class path dependencies

In a web service implementation class, you might want to exclude some dependencies get packaged inside service/lib, but still use those dependencies at compile time in the service class. Because maven axis2 aar plugin adds all the dependent jars in maven classpath in to the service/lib dir.

What you can do is to add a scope inside the dependencies. This will then exclude that particular dependency from being packaged inside lib(Remember: this will exclude all its related child dependencies also).


org.apache.axis2.wso2
axis2
provided