use of javax.xml.validation.SchemaFactory in project jqa-core-framework by buschmais.
the class XmlHelper method getSchema.
/**
* Return a {@link Schema} instance for the given resource.
*
* @param resource
* The resource.
* @return The {@link Schema} instance.
*/
public static Schema getSchema(String resource) {
Schema schema;
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(XmlHelper.class.getResource(resource));
} catch (SAXException e) {
throw new IllegalStateException("Cannot read rules schema.", e);
}
return schema;
}
use of javax.xml.validation.SchemaFactory in project simba-os by cegeka.
the class Utils method validateXML.
/**
* This function attempts to validate an XML string against the specified
* schema. It will parse the string into a DOM document and validate this
* document against the schema.
*
* @param xmlString The XML document which should be validated
* @param schemaName The schema filename which should be used
* @throws Exception
*/
public static Document validateXML(String xmlString, String schemaName, Boolean... debugMode) throws Exception {
try {
String schemaFullPath = "schemas/" + schemaName;
log.debug("schemaFullPath: " + schemaFullPath);
ClassLoader classLoader = Utils.class.getClassLoader();
URL schemaFile = classLoader.getResource(schemaFullPath);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
XMLErrorHandler errorHandler = new XMLErrorHandler();
validator.setErrorHandler(errorHandler);
validator.validate(new StreamSource(new StringReader(xmlString)));
if (errorHandler.getErrorXML().size() > 0) {
throw new Error("Invalid XML. See the log");
}
} catch (Exception ex) {
log.error("Error executing validateXML: " + ex.getMessage(), ex);
throw ex;
}
return convertStringToDocument(xmlString);
}
Aggregations