| 1 | |
package net.spy.digg.parsers; |
| 2 | |
|
| 3 | |
import java.io.IOException; |
| 4 | |
import java.io.InputStream; |
| 5 | |
|
| 6 | |
import javax.xml.parsers.DocumentBuilder; |
| 7 | |
import javax.xml.parsers.DocumentBuilderFactory; |
| 8 | |
import javax.xml.parsers.ParserConfigurationException; |
| 9 | |
|
| 10 | |
import org.w3c.dom.Document; |
| 11 | |
import org.w3c.dom.Node; |
| 12 | |
import org.xml.sax.SAXException; |
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | 42 | public abstract class BaseParser { |
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
protected Document getDocument(InputStream is, String rootEl) |
| 27 | |
throws SAXException, IOException { |
| 28 | |
try { |
| 29 | 39 | final DocumentBuilder docbuilder = |
| 30 | |
DocumentBuilderFactory.newInstance().newDocumentBuilder(); |
| 31 | 39 | final Document doc=docbuilder.parse(is); |
| 32 | |
|
| 33 | 39 | assert doc.getFirstChild().getNodeName().equals(rootEl); |
| 34 | |
|
| 35 | 39 | return doc; |
| 36 | 0 | } catch (final ParserConfigurationException e) { |
| 37 | 0 | throw new RuntimeException(e); |
| 38 | |
} |
| 39 | |
} |
| 40 | |
|
| 41 | |
|
| 42 | |
|
| 43 | |
|
| 44 | |
protected abstract String getRootElementName(); |
| 45 | |
|
| 46 | |
|
| 47 | |
|
| 48 | |
|
| 49 | |
public void parse(InputStream is) throws SAXException, IOException { |
| 50 | 39 | final Document doc=getDocument(is, getRootElementName()); |
| 51 | 39 | handleDocument(doc); |
| 52 | 39 | } |
| 53 | |
|
| 54 | |
|
| 55 | |
|
| 56 | |
|
| 57 | |
protected abstract void handleDocument(Document doc) |
| 58 | |
throws SAXException, IOException; |
| 59 | |
|
| 60 | |
|
| 61 | |
|
| 62 | |
|
| 63 | |
public static String getAttr(Node n, String s) { |
| 64 | 7647 | String rv=null; |
| 65 | 7647 | assert n != null : "Null node"; |
| 66 | 7647 | assert s != null : "Null attr name"; |
| 67 | 7647 | assert n.getAttributes() != null : "No attributes on " + n; |
| 68 | 7647 | if(n.getAttributes().getNamedItem(s) != null) { |
| 69 | 7167 | rv=n.getAttributes().getNamedItem(s).getNodeValue(); |
| 70 | |
} |
| 71 | 7647 | return rv; |
| 72 | |
} |
| 73 | |
|
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | |
public static String getAttr(Node n, String s, String def) { |
| 78 | 30 | String rv=getAttr(n, s); |
| 79 | 30 | return rv == null ? def : rv; |
| 80 | |
} |
| 81 | |
} |