1 22 23 package org.xquark.util; 24 25 import java.io.IOException ; 26 import java.io.InputStream ; 27 import java.io.Reader ; 28 import java.util.Stack ; 29 30 import javax.xml.parsers.SAXParserFactory ; 31 32 import org.xml.sax.*; 33 import org.xml.sax.helpers.DefaultHandler ; 34 import org.xquark.schema.validation.SchemaValidationContext; 35 import org.xquark.schema.validation.ValidatingSchemaFilter; 36 37 43 public abstract class SaxMapper extends DefaultHandler 44 { 45 private static final String RCSRevision = "$Revision: 1.1 $"; 46 private static final String RCSName = "$Name: $"; 47 48 public abstract Object getMappedObject(); 49 public abstract TagTracker createTagTrackerNetwork(); 50 51 private Stack tagStack = new Stack (); 55 56 private XMLReader xr; 58 59 private SchemaValidationContext context; 60 61 public SaxMapper() 62 { 63 64 try 65 { 66 SAXParserFactory factory = SAXParserFactory.newInstance(); 67 factory.setNamespaceAware(true); 68 xr = factory.newSAXParser().getXMLReader(); 69 } 70 catch (Exception e) 71 { 72 throw new RuntimeException ( 73 "JAXP exception while intantiating a SAX parser for internal use (" 74 + e.getMessage() 75 + ")."); 76 } 77 78 context = new SchemaValidationContext(); 79 xr = new ValidatingSchemaFilter(xr, context); 80 81 tagStack.push(createTagTrackerNetwork()); 103 104 } 105 106 public Object fromXML(String url) 107 { 108 109 try 110 { 111 return fromXML(new InputSource(url)); 112 113 } 114 catch (Exception e) 115 { 116 e.printStackTrace(); 117 return null; 118 } 119 } 120 121 public Object fromXML(InputStream in) 122 { 123 try 124 { 125 return fromXML(new InputSource(in)); 126 127 } 128 catch (Exception e) 129 { 130 e.printStackTrace(); 131 return null; 132 } 133 } 134 135 public Object fromXML(Reader in) 136 { 137 try 138 { 139 return fromXML(new InputSource(in)); 140 141 } 142 catch (Exception e) 143 { 144 e.printStackTrace(); 145 return null; 146 } 147 } 148 149 private synchronized Object fromXML(InputSource in) 150 throws SAXException, IOException 151 { 152 153 160 xr.setContentHandler(this); 162 163 xr.parse(in); 165 166 return getMappedObject(); 167 } 168 169 172 public void startElement( 173 String namespaceURI, 174 String localName, 175 String qName, 176 Attributes attr) 177 throws SAXException 178 { 179 180 TagTracker activeTracker = (TagTracker) tagStack.peek(); 183 activeTracker.startElement(context.getCurrentInfoset(), tagStack); 184 185 } 186 187 public void endElement(String namespaceURI, String localName, String qName) 188 throws SAXException 189 { 190 191 TagTracker activeTracker = (TagTracker) tagStack.peek(); 194 activeTracker.endElement(context.getCurrentInfoset(), tagStack); 195 196 } 197 } 198 | Popular Tags |