1 16 17 package org.springframework.beans.factory.xml; 18 19 import java.io.File ; 20 import java.io.IOException ; 21 import java.net.URL ; 22 import java.net.URLDecoder ; 23 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 import org.xml.sax.InputSource ; 27 import org.xml.sax.SAXException ; 28 29 import org.springframework.core.io.Resource; 30 import org.springframework.core.io.ResourceLoader; 31 32 53 public class ResourceEntityResolver extends DelegatingEntityResolver { 54 55 private static final Log logger = LogFactory.getLog(ResourceEntityResolver.class); 56 57 private final ResourceLoader resourceLoader; 58 59 60 66 public ResourceEntityResolver(ResourceLoader resourceLoader) { 67 super(resourceLoader.getClassLoader()); 68 this.resourceLoader = resourceLoader; 69 } 70 71 72 public InputSource resolveEntity(String publicId, String systemId) throws SAXException , IOException { 73 InputSource source = super.resolveEntity(publicId, systemId); 74 if (source == null && systemId != null) { 75 String resourcePath = null; 76 try { 77 String decodedSystemId = URLDecoder.decode(systemId); 78 String givenUrl = new URL (decodedSystemId).toString(); 79 String systemRootUrl = new File ("").toURL().toString(); 80 if (givenUrl.startsWith(systemRootUrl)) { 82 resourcePath = givenUrl.substring(systemRootUrl.length()); 83 } 84 } 85 catch (Exception ex) { 86 if (logger.isDebugEnabled()) { 88 logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex); 89 } 90 resourcePath = systemId; 92 } 93 if (resourcePath != null) { 94 if (logger.isTraceEnabled()) { 95 logger.trace("Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]"); 96 } 97 Resource resource = this.resourceLoader.getResource(resourcePath); 98 source = new InputSource (resource.getInputStream()); 99 source.setPublicId(publicId); 100 source.setSystemId(systemId); 101 if (logger.isDebugEnabled()) { 102 logger.debug("Found XML entity [" + systemId + "]: " + resource); 103 } 104 } 105 } 106 return source; 107 } 108 109 } 110 | Popular Tags |