1 package net.sf.openrocket.file.simplesax;
3 import java.util.HashMap;
4 import java.util.Stack;
6 import net.sf.openrocket.aerodynamics.Warning;
7 import net.sf.openrocket.aerodynamics.WarningSet;
9 import org.xml.sax.Attributes;
10 import org.xml.sax.SAXException;
11 import org.xml.sax.helpers.DefaultHandler;
14 * The actual SAX handler class. Contains the necessary methods for parsing the SAX source.
15 * Delegates the actual content parsing to {@link ElementHandler} objects.
17 class DelegatorHandler extends DefaultHandler {
18 private final WarningSet warnings;
20 private final Stack<ElementHandler> handlerStack = new Stack<ElementHandler>();
21 private final Stack<StringBuilder> elementData = new Stack<StringBuilder>();
22 private final Stack<HashMap<String, String>> elementAttributes =
23 new Stack<HashMap<String, String>>();
26 // Ignore all elements as long as ignore > 0
27 private int ignore = 0;
30 public DelegatorHandler(ElementHandler initialHandler, WarningSet warnings) {
31 this.warnings = warnings;
32 handlerStack.add(initialHandler);
33 elementData.add(new StringBuilder()); // Just in case
37 ///////// SAX handlers
40 public void startElement(String uri, String localName, String name,
41 Attributes attributes) throws SAXException {
49 // Check for unknown namespace
50 if (!uri.equals("")) {
51 warnings.add(Warning.fromString("Unknown namespace element '" + uri
52 + "' encountered, ignoring."));
57 // Add layer to data stacks
58 elementData.push(new StringBuilder());
59 elementAttributes.push(copyAttributes(attributes));
62 ElementHandler h = handlerStack.peek();
63 h = h.openElement(localName, elementAttributes.peek(), warnings);
67 // Start ignoring elements
74 * Stores encountered characters in the elementData stack.
77 public void characters(char[] chars, int start, int length) throws SAXException {
82 StringBuilder sb = elementData.peek();
83 sb.append(chars, start, length);
88 * Removes the last layer from the stack.
91 public void endElement(String uri, String localName, String name) throws SAXException {
99 // Remove data from stack
100 String data = elementData.pop().toString(); // throws on error
101 HashMap<String, String> attr = elementAttributes.pop();
103 // Remove last handler and call the next one
106 h = handlerStack.pop();
107 h.endHandler(localName, attr, data, warnings);
109 h = handlerStack.peek();
110 h.closeElement(localName, attr, data, warnings);
114 private static HashMap<String, String> copyAttributes(Attributes atts) {
115 HashMap<String, String> ret = new HashMap<String, String>();
116 for (int i = 0; i < atts.getLength(); i++) {
117 ret.put(atts.getLocalName(i), atts.getValue(i));