1 15 package org.apache.hivemind.parse; 16 17 import java.io.IOException ; 18 import java.net.URL ; 19 20 import javax.xml.parsers.FactoryConfigurationError ; 21 import javax.xml.parsers.ParserConfigurationException ; 22 import javax.xml.parsers.SAXParser ; 23 import javax.xml.parsers.SAXParserFactory ; 24 25 import org.apache.commons.logging.Log; 26 import org.apache.commons.logging.LogFactory; 27 import org.apache.hivemind.ApplicationRuntimeException; 28 import org.apache.hivemind.ClassResolver; 29 import org.apache.hivemind.ErrorHandler; 30 import org.apache.hivemind.Resource; 31 import org.xml.sax.InputSource ; 32 import org.xml.sax.SAXException ; 33 34 43 public class XmlResourceProcessor 44 { 45 private static final Log LOG = LogFactory.getLog(XmlResourceProcessor.class); 46 47 protected ClassResolver _resolver; 48 49 protected ErrorHandler _errorHandler; 50 51 private DescriptorParser _contentHandler; 52 53 private SAXParser _saxParser; 54 55 public XmlResourceProcessor(ClassResolver resolver, ErrorHandler errorHandler) 56 { 57 _resolver = resolver; 58 _errorHandler = errorHandler; 59 } 60 61 69 public ModuleDescriptor processResource(Resource resource) 70 { 71 if (_contentHandler == null) 72 _contentHandler = new DescriptorParser(_errorHandler); 73 74 _contentHandler.initialize(resource, _resolver); 75 76 try 77 { 78 if (LOG.isDebugEnabled()) 79 LOG.debug("Parsing " + resource); 80 81 ModuleDescriptor descriptor = parseResource(resource, getSAXParser(), _contentHandler); 82 83 if (LOG.isDebugEnabled()) 84 LOG.debug("Result: " + descriptor); 85 86 return descriptor; 87 } 88 catch (ApplicationRuntimeException e) 89 { 90 throw e; 91 } 92 catch (Exception e) 93 { 94 _saxParser = null; 95 96 throw new ApplicationRuntimeException( 97 ParseMessages.errorReadingDescriptor(resource, e), resource, _contentHandler 98 .getLocation(), e); 99 } 100 finally 101 { 102 _contentHandler.resetParser(); 103 } 104 } 105 106 113 protected ModuleDescriptor parseResource(Resource resource, SAXParser parser, 114 DescriptorParser contentHandler) throws SAXException , IOException 115 { 116 InputSource source = getInputSource(resource); 117 118 parser.parse(source, contentHandler); 119 120 return contentHandler.getModuleDescriptor(); 121 } 122 123 private InputSource getInputSource(Resource resource) 124 { 125 try 126 { 127 URL url = resource.getResourceURL(); 128 129 return new InputSource (url.openStream()); 130 } 131 catch (Exception e) 132 { 133 throw new ApplicationRuntimeException(ParseMessages.missingResource(resource), 134 resource, null, e); 135 } 136 } 137 138 private SAXParser getSAXParser() throws ParserConfigurationException , SAXException , 139 FactoryConfigurationError 140 { 141 if (_saxParser == null) 142 _saxParser = SAXParserFactory.newInstance().newSAXParser(); 143 144 return _saxParser; 145 } 146 147 } | Popular Tags |