final String xmlFileName = context.getConfigValue(Context.CONFIG_FILENAME);
final File xmlFile = new File(xmlFileName);
if (!xmlFile.exists() || !xmlFile.canRead()) {
throw new ConfigurationException("Error: Can not read configuration file: " + xmlFile.getAbsolutePath());
}
final boolean validate = Boolean.valueOf(context.getConfigValue(Context.CONFIG_VALIDATE));
// Read the XML document and validate
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setValidating(validate);
builderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
// Schema validation
if (validate) {
final URL schemaURL = ElementBuilder.class.getResource("/schema/jmxeval-" + context.getConfigValue(Context.CONFIG_SCHEMA) + ".xsd");
builderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaURL.toString());
}
try {
final DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
// set error handler to throw any exceptions out
documentBuilder.setErrorHandler(new ConfigurationErrorHandler());
final Document document = documentBuilder.parse(xmlFile);
// process the configuration
return build(document.getDocumentElement(), null);
} catch (ParserConfigurationException e) {
throw new ConfigurationException("XML Parser configuration error: " + e.getMessage(), e);
} catch (SAXException e) {
throw new ConfigurationException("Exception while parsing configuration file: " + e.getMessage(), e);
} catch (IOException e) {
throw new ConfigurationException("Error reading configuration file: " + e.getMessage(), e);
}
}