* @return an application object.
*/
public static Document getDocument(final URL url, final boolean isValidating, final EntityResolver entityResolver)
throws DocumentParserException {
// build factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// XML files use schemas.
factory.setNamespaceAware(true);
factory.setValidating(isValidating);
// ignore white space can only be set if parser is validating
if (isValidating) {
factory.setIgnoringElementContentWhitespace(true);
factory.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.valueOf(isValidating));
factory.setAttribute("http://apache.org/xml/features/validation/schema-full-checking", Boolean.valueOf(true));
}
// Add schema location
if (isValidating) {
// Needs to get the version attribute and then set the schema
// location. For this, get the version by parsing the document
// without validation
Document detectDocument = getDocument(url, false, entityResolver);
// Root element = <persistence>
Element persistenceRootElement = detectDocument.getDocumentElement();
String version = XMLUtils.getAttributeValue(persistenceRootElement, "version");
if ("1.0".equals(version)) {
factory.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation",
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
} else if ("2.0".equals(version)) {
factory.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation",
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
} else {
// This is a required attribute, needs to be set by the user !
throw new DocumentParserException("Cannot detect the version of the Persistence schema from the URL '" + url
+ "'");
}
}
// Build a document builder
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new DocumentParserException("Cannot build a document builder", e);
}
// Error handler (throwing exceptions)