Monday, 11 February 2013

Validation Code to validate a xml and make it parse


package uk.co.igindex.regression.service.util;

import java.io.StringReader;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

/**
 *
 * @version 1.0
 * @author Jarvis Ragona
 */
public class SchemaValidatorImpl implements SchemaValidator {
private static final Logger LOG = Logger.getLogger(SchemaValidatorImpl.class);

/**
*
* @param document
* @return
*/
public void validateTestCaseDocument(Document document) throws SchemaValidationException {
try {
SchemaValidationErrorHandler errorHandler = getSchemaValidationErrorHandler();

SAXReader reader = new SAXReader();
reader.setValidation(true);
reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", getClass().getResourceAsStream("/schema/regression-test-case.xsd"));
reader.setErrorHandler(errorHandler);
reader.read(new StringReader(document.asXML()));

if(errorHandler.isValidationError()) {
String message = "XML Document has Error: " + errorHandler.isValidationError() + " " +errorHandler.getSaxParseException().getMessage();
LOG.error(message);
throw errorHandler.getSaxParseException();
}

LOG.debug("Test case XML document is valid");
} catch(Exception e) {
LOG.fatal(e.getMessage(), e);
throw new SchemaValidationException(e.getMessage(), e);
}
}

protected SchemaValidationErrorHandler getSchemaValidationErrorHandler() {
return (SchemaValidationErrorHandler)BeanFactory.getBean("schemaValidationErrorHandler");
}
}

No comments:

Post a Comment