1 16 17 package org.springframework.beans.factory.xml; 18 19 import javax.xml.parsers.DocumentBuilder ; 20 import javax.xml.parsers.DocumentBuilderFactory ; 21 import javax.xml.parsers.ParserConfigurationException ; 22 23 import org.apache.commons.logging.Log; 24 import org.apache.commons.logging.LogFactory; 25 import org.w3c.dom.Document ; 26 import org.xml.sax.EntityResolver ; 27 import org.xml.sax.ErrorHandler ; 28 import org.xml.sax.InputSource ; 29 30 45 public class DefaultDocumentLoader implements DocumentLoader { 46 47 50 private static final String SCHEMA_LANGUAGE_ATTRIBUTE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; 51 52 55 private static final String XSD_SCHEMA_LANGUAGE = "http://www.w3.org/2001/XMLSchema"; 56 57 58 private static final Log logger = LogFactory.getLog(DefaultDocumentLoader.class); 59 60 61 65 public Document loadDocument( 66 InputSource inputSource, EntityResolver entityResolver, 67 ErrorHandler errorHandler, int validationMode, boolean namespaceAware) 68 throws Exception { 69 70 DocumentBuilderFactory factory = 71 createDocumentBuilderFactory(validationMode, namespaceAware); 72 if (logger.isDebugEnabled()) { 73 logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]"); 74 } 75 DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); 76 return builder.parse(inputSource); 77 } 78 79 85 protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware) 86 throws ParserConfigurationException { 87 88 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 89 factory.setNamespaceAware(namespaceAware); 90 91 if (validationMode != XmlBeanDefinitionReader.VALIDATION_NONE) { 92 factory.setValidating(true); 93 94 if (validationMode == XmlBeanDefinitionReader.VALIDATION_XSD) { 95 factory.setNamespaceAware(true); 97 try { 98 factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); 99 } 100 catch (IllegalArgumentException ex) { 101 throw new ParserConfigurationException ( 102 "Unable to validate using XSD: Your JAXP provider [" + factory + 103 "] does not support XML Schema. Are you running on Java 1.4 or below with " + 104 "Apache Crimson? Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); 105 } 106 } 107 } 108 109 return factory; 110 } 111 112 121 protected DocumentBuilder createDocumentBuilder( 122 DocumentBuilderFactory factory, EntityResolver entityResolver, ErrorHandler errorHandler) 123 throws ParserConfigurationException { 124 125 DocumentBuilder docBuilder = factory.newDocumentBuilder(); 126 if (entityResolver != null) { 127 docBuilder.setEntityResolver(entityResolver); 128 } 129 if (errorHandler != null) { 130 docBuilder.setErrorHandler(errorHandler); 131 } 132 return docBuilder; 133 } 134 135 } 136 | Popular Tags |