01: /*
02: * $Id: Dispatcher.java 752 2006-11-10 21:16:47Z hengels $
03: * (c) Copyright 2004 con:cern development team.
04: *
05: * This file is part of con:cern (http://concern.sf.net).
06: *
07: * con:cern is free software; you can redistribute it and/or modify
08: * it under the terms of the GNU Lesser General Public License
09: * as published by the Free Software Foundation; either version 2.1
10: * of the License, or (at your option) any later version.
11: *
12: * Please see COPYING for the complete licence.
13: */
14: package org.concern.model.cpd;
15:
16: import org.xml.sax.Attributes;
17: import org.xml.sax.SAXException;
18: import org.xml.sax.helpers.DefaultHandler;
19:
20: import javax.xml.parsers.SAXParser;
21: import javax.xml.parsers.SAXParserFactory;
22: import java.net.URL;
23: import java.util.*;
24:
25: /**
26: * @author hengels[at]mercatis[dot]de
27: * @version $Revision: 752 $
28: */
29: public class Dispatcher extends DefaultHandler {
30: ScopeHandler rootHandler;
31: Stack stack = new Stack();
32:
33: public Dispatcher(ScopeHandler rootHandler) {
34: this .rootHandler = rootHandler;
35: }
36:
37: public void push(ScopeHandler handler) {
38: stack.push(handler);
39: }
40:
41: public ScopeHandler pop() {
42: return (ScopeHandler) stack.pop();
43: }
44:
45: public void startElement(String uri, String localName,
46: String qName, Attributes attributes) throws SAXException {
47: ScopeHandler handler;
48: if (stack.size() > 0) {
49: handler = (ScopeHandler) stack.peek();
50: handler = handler.getHandler(localName, qName);
51: } else
52: handler = rootHandler;
53: handler.startElement(uri, localName, qName, attributes);
54: push(handler);
55: }
56:
57: public void characters(char ch[], int start, int length)
58: throws SAXException {
59: ScopeHandler handler = (ScopeHandler) stack.peek();
60: handler.characters(ch, start, length);
61: }
62:
63: public void endElement(String uri, String localName, String qName)
64: throws SAXException {
65: ScopeHandler handler = (ScopeHandler) stack.pop();
66: handler.endElement(uri, localName, qName);
67: ScopeHandler parent;
68: if (stack.size() > 0) {
69: parent = (ScopeHandler) stack.peek();
70: } else
71: parent = rootHandler;
72: parent.fetchChild(handler);
73: }
74:
75: public static void main(String[] args) {
76: SAXParserFactory factory = SAXParserFactory.newInstance();
77: try {
78: SAXParser saxParser = factory.newSAXParser();
79: Dispatcher dispatcher = new Dispatcher(new ProcessHandler());
80: saxParser.parse(new URL(args[0]).openStream(), dispatcher);
81: } catch (Exception e) {
82: System.err.println(e.getMessage());
83: e.printStackTrace();
84: }
85: }
86: }
|