source: annotrans/trunk/src/main/java/nl/mpi/annot/translate/XMLparser.java @ 6979

Last change on this file since 6979 was 6979, checked in by peter.beinema@mpi.nl, 8 years ago

first upload

File size: 21.5 KB
Line 
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package nl.mpi.annot.translate;
7
8import javax.xml.parsers.*;
9import org.xml.sax.*;
10import org.xml.sax.helpers.*;
11
12import java.util.*;
13import java.io.*;
14
15/**
16 *
17 * @author petbei
18 */
19public class XMLparser extends DefaultHandler {
20    boolean inElement = false;
21    int indentation = 0;
22
23    private static class MyErrorHandler implements ErrorHandler {
24        private PrintStream out;
25
26        MyErrorHandler(PrintStream out) {
27            this.out = out;
28        }
29
30        private String getParseExceptionInfo(SAXParseException spe) {
31            String systemId = spe.getSystemId();
32            if (systemId == null) {
33                systemId = "null";
34            }
35
36            String info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage();
37            return info;
38        }
39
40        public void warning(SAXParseException spe) throws SAXException {
41            out.println("Warning: " + getParseExceptionInfo(spe));
42        }
43       
44        public void error(SAXParseException spe) throws SAXException {
45            String message = "Error: " + getParseExceptionInfo(spe);
46            throw new SAXException(message);
47        }
48
49        public void fatalError(SAXParseException spe) throws SAXException {
50            String message = "Fatal Error: " + getParseExceptionInfo(spe);
51            throw new SAXException(message);
52        }
53    }
54
55    private SymbolTable       resources;
56    private SymbolTable       layers;
57    private ResourceLayers    resourcesLayers;
58    private SymbolTable       formalisms;
59    private TranslationTypes  translationTypes;
60    private TranslationTables translationTables;
61   
62    XMLparser(String fileName, SymbolTable atrs, SymbolTable atls, SymbolTable atfs, TranslationTypes tts, ResourceLayers atRLs, TranslationTables atTTs) {
63        resources = atrs;
64        layers = atls;
65        resourcesLayers = atRLs;
66        formalisms = atfs;
67        translationTypes = tts;
68        translationTables = atTTs;
69       
70        System.out.println("XMLparser input file name: " + fileName);
71        if (fileName == null) {
72            usage();
73        } 
74        else {
75            try {
76                SAXParserFactory spf = SAXParserFactory.newInstance();
77                spf.setNamespaceAware(true);
78                SAXParser saxParser = spf.newSAXParser();
79                XMLReader xmlReader = saxParser.getXMLReader();
80                //--- xmlReader.setContentHandler(new SAXLocalNameCount());
81                xmlReader.setContentHandler(this);
82                xmlReader.setErrorHandler(new MyErrorHandler(System.err));
83                xmlReader.parse(convertToFileURL(fileName));
84            }
85            catch (Exception e) {
86                System.err.println("*** ERROR *** exception in AnnotationTranslator SAX parser: " + e.getMessage());
87            }
88        }
89        //resources.display();
90        //layers.display();
91        //resourcesLayers.display();
92        //formalisms.display();
93        //translationTypes.display();
94        //translationTables.display();
95    }
96
97    private Hashtable<String,Integer> tags;
98
99    private static void usage() {
100        System.err.println("Usage: SAXLocalNameCount <file.xml>");
101        System.err.println("       -usage or -help = this message");
102        System.exit(1);
103    }
104
105    public void startDocument() throws SAXException {
106        tags = new Hashtable<String,Integer>();
107    }
108
109    private boolean amInAnnotationTranslation = false;  //--- part of state machine that is used in parsing the XML file
110    private boolean amInResources = false;              //--- part of state machine that is used in parsing the XML file
111    private boolean amInTranslations = false;           //--- part of state machine that is used in parsing the XML file
112    private boolean amInTranslationTable = false;       //--- part of state machine that is used in parsing the XML file
113
114    //--- keep track of current TranslationTable, so that we know what to add translation pairs to
115    private TranslationTable  curTable = null;
116   
117    //--- code to track file name / pare line / parse position (for error messages)
118    private Locator locator;
119   
120    public void setDocumentLocator(Locator locator) {
121        this.locator = locator;
122    }
123   
124    String getLocator() {
125        return ("[" + locator.getSystemId() + " " + locator.getLineNumber() + ":" + locator.getColumnNumber() + "]");
126    }
127   
128    //--- code to create a unique ResourceLayer object; Resource + Layer define Formalism
129    void tryAddResourceLayer(Attributes atts) {
130        //--- get parameters
131        if (atts.getLength() == 3) {
132            String resourceValue = null;
133            String layerValue = null;
134            String formalismValue = null;
135            for (int ix = 0; ix < atts.getLength(); ix++) {
136                if (atts.getLocalName(ix).equals("resource")) {
137                    resourceValue = atts.getValue(ix);
138                }
139                else if (atts.getLocalName(ix).equals("layer")) {
140                    layerValue = atts.getValue(ix);
141                }
142                else if (atts.getLocalName(ix).equals("formalism")) {
143                    formalismValue = atts.getValue(ix);
144                }
145                else {
146                    System.err.println("*** ERROR *** " + getLocator() + " unexpected attribute in \"ResourceLayer\": " + atts.getLocalName(ix) + " - ResourceLayer ignored");
147                    return;
148                }
149            }
150            if (resourceValue == null) {
151                System.err.println("*** ERROR *** " + getLocator() + " missing \"resource\" attribute in \"ResourceLayer\": ");
152                return;
153            }
154            if (layerValue == null) {
155                System.err.println("*** ERROR *** " + getLocator() + " missing \"layer\" attribute in \"ResourceLayer\": ");
156                return;
157            }
158            if (formalismValue == null) {
159                System.err.println("*** ERROR *** " + getLocator() + " missing \"formalism\" attribute in \"ResourceLayer\": ");
160                return;
161            }
162            resources.add(resourceValue);
163            layers.add(layerValue);
164            formalisms.add(formalismValue);
165            try {
166                resourcesLayers.addResourceLayer(resourceValue, layerValue, formalismValue);
167                // System.err.println("INFO " + getLocator() + " added unique ResourceLayer (" + resourceValue + ", " + layerValue + ", " + formalismValue + ")");
168            }
169            catch (Exception e) {
170                System.err.println("*** ERROR *** " + getLocator() + " failed to add unique ResourceLayer (" + resourceValue + ", " + layerValue + ", " + formalismValue + "): " + e.getMessage());
171            }
172        }
173        else {
174            System.err.println("*** ERROR *** " + getLocator() + " \"ResourceLayer\" has wrong number of attributes: 3 expected, " + atts.getLength() + " found - ResourceLayer ignored");
175        }
176    }
177
178    //--- code to create a unique TranslationTable object (from/to ResourceLayer object, translation type object
179    void tryAddTranslationTable(Attributes atts) {
180        //--- get parameters
181        if (atts.getLength() == 3) {
182            String fromRLValue = null;
183            String toRLValue = null;
184            String translationTypeValue = null;
185            for (int ix = 0; ix < atts.getLength(); ix++) {
186                if (atts.getLocalName(ix).equals("fromResourceLayer")) {
187                    fromRLValue = atts.getValue(ix);
188                }
189                else if (atts.getLocalName(ix).equals("toResourceLayer")) {
190                    toRLValue = atts.getValue(ix);
191                }
192                else if (atts.getLocalName(ix).equals("translationType")) {
193                    translationTypeValue = atts.getValue(ix);
194                }
195                else {
196                    System.err.println("*** ERROR *** " + getLocator() + " unexpected attribute in \"TranslationTable\": " + atts.getLocalName(ix) + " - TranslationTable ignored");
197                    return;
198                }
199            }
200            if (fromRLValue == null) {
201                System.err.println("*** ERROR *** " + getLocator() + " missing \"fromResourceLayer\" attribute in \"TranslationTable\": ");
202                return;
203            }
204            if (toRLValue == null) {
205                System.err.println("*** ERROR *** " + getLocator() + " missing \"toResourceLayer\" attribute in \"TranslationTable\": ");
206                return;
207            }
208            if (translationTypeValue == null) {
209                System.err.println("*** ERROR *** " + getLocator() + " missing \"translationType\" attribute in \"TranslationTable\": ");
210                return;
211            }
212            try {
213                ResourceLayer fromRL = resourcesLayers.getResourceLayer(fromRLValue);
214                ResourceLayer toRL = resourcesLayers.getResourceLayer(toRLValue);
215                TranslationType tt = translationTypes.addTranslationType(translationTypeValue);
216                curTable = translationTables.addTranslationTable(fromRL, toRL, tt);
217                //System.err.println("INFO " + getLocator() + " added TranslationTable (" + fromRLValue + ", " + toRLValue + ", " + translationTypeValue);
218            }
219            catch (Exception e) {
220                System.err.println("*** ERROR *** " + getLocator() + " failed to add TranslationTable (" + fromRLValue + ", " + toRLValue + ", " + translationTypeValue + "): " + e.getMessage());
221            }
222        }
223        else {
224            System.err.println("*** ERROR *** " + getLocator() + " \"ResourceLayer\" has wrong number of attributes: 3 expected, " + atts.getLength() + " found - ResourceLayer ignored");
225        }
226    }
227
228    //--- code to add a from / to translation pair to a TranslationTable
229    void tryAddTranslation(Attributes atts) {
230        //--- get parameters
231        if (curTable == null) {
232            System.err.println("*** ERROR *** " + getLocator() + " while processing \"Pair\": no valid TranslationTable available, Pair ignored");
233            return;
234        }
235        if (atts.getLength() != 2) {
236            System.err.println("*** ERROR *** " + getLocator() + " \"Pair\" has wrong number of attributes: 2 expected, " + atts.getLength() + " found - Pair ignored");
237        }
238        String fromValue = null;
239        String toValue = null;
240        for (int ix = 0; ix < atts.getLength(); ix++) {
241            if (atts.getLocalName(ix).equals("from")) {
242                fromValue = atts.getValue(ix);
243            }
244            else if (atts.getLocalName(ix).equals("to")) {
245                toValue = atts.getValue(ix);
246            }
247            else {
248                System.err.println("*** ERROR *** " + getLocator() + " unexpected attribute in \"Pair\": " + atts.getLocalName(ix) + " - Pair ignored");
249                return;
250            }
251        }
252        if (fromValue == null) {
253            System.err.println("*** ERROR *** " + getLocator() + " missing \"from\" attribute in \"Pair\": ");
254            return;
255        }
256        if (toValue == null) {
257            System.err.println("*** ERROR *** " + getLocator() + " missing \"to\" attribute in \"Pair\": ");
258            return;
259        }
260        try {
261            curTable.addTranslation(fromValue, toValue);
262            // System.out.println("INFO " + getLocator() + " added Translation Pair (" + fromValue + ", " + toValue + ")");
263        }
264        catch (Exception e) {
265            System.err.println("*** ERROR *** " + getLocator() + " failed to add Pair (" + fromValue + ", " + toValue + "): " + e.getMessage());
266        }
267    }
268
269    public void startElement(String namespaceURI,
270                             String localName,
271                             String qName, 
272                             Attributes atts) throws SAXException {
273        inElement = true;
274        String key = localName;
275        Integer value = tags.get(key);
276        // System.err.println("==> XML parse tag \"" + localName + "\"");
277        if (localName.equals("AnnotationTranslation")) {
278            if (amInAnnotationTranslation){
279                System.err.println("*** WARNING *** " + getLocator() + " entered \"AnnotationTranslation\" TWICE, ignored");
280            }
281            else {
282                amInAnnotationTranslation = true;
283            }
284        }
285        else if (localName.equals("Resources")) {
286            if (!amInAnnotationTranslation){
287                System.err.println("*** WARNING *** " + getLocator() + " \"Resources\" tag encountered while not in \"AnnotationTranslation\"");
288                amInAnnotationTranslation = true;
289            }
290            if (amInResources){
291                System.err.println("*** WARNING *** " + getLocator() + " entered \"resources\" TWICE, ignored");
292            }
293            else {
294                amInResources = true;
295            }
296        }
297        else if (localName.equals("ResourceLayer")) {
298            if (!amInAnnotationTranslation){
299                System.err.println("*** WARNING *** " + getLocator() + " \"ResourceLayer\" tag encountered while not in \"AnnotationTranslation\"");
300                amInAnnotationTranslation = true;
301            }
302            if (!amInResources){
303                System.err.println("*** WARNING *** " + getLocator() + " \"ResourceLayer\" tag encountered while not in \"Resources\"");
304                amInResources = true;
305            }
306            tryAddResourceLayer(atts);
307        }
308        else if (localName.equals("Translations")) {
309            if (!amInAnnotationTranslation){
310                System.err.println("*** WARNING *** " + getLocator() + " \"Translations\" tag encountered while not in \"AnnotationTranslation\"");
311                amInAnnotationTranslation = true;
312            }
313            if (amInTranslations){
314                System.err.println("*** WARNING *** " + getLocator() + " entered \"Translations\" TWICE, ignored");
315            }
316            else {
317                amInTranslations = true;
318            }
319        }
320        else if (localName.equals("TranslationTable")) {
321            if (!amInAnnotationTranslation){
322                System.err.println("*** WARNING *** " + getLocator() + " \"TranslationTable\" tag encountered while not in \"AnnotationTranslation\"");
323                amInAnnotationTranslation = true;
324            }
325            if (!amInTranslations){
326                System.err.println("*** WARNING *** " + getLocator() + " \"TranslationTable\" tag encountered while not in \"Translations\"");
327                amInTranslations = true;
328            }
329            if (amInTranslationTable){
330                System.err.println("*** WARNING *** " + getLocator() + " entered \"TranslationTable\" TWICE, ignored");
331            }
332            else {
333                amInTranslationTable = true;
334            }
335            tryAddTranslationTable(atts);
336        }
337        else if (localName.equals("Pair")) {
338            if (!amInAnnotationTranslation){
339                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" tag encountered while not in \"AnnotationTranslation\"");
340                amInAnnotationTranslation = true;
341            }
342            if (!amInTranslations){
343                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" tag encountered while not in \"Translations\"");
344                amInTranslations = true;
345            }
346            if (!amInTranslationTable){
347                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" tag encountered while not in \"TranslationTable\"");
348                amInTranslationTable = true;
349            }
350            tryAddTranslation(atts);
351        }
352        else {
353            System.err.println("*** ERROR *** " + getLocator() + " unknown tag \"" + localName + "\", ignored");           
354        }
355        //--- commented out: code that displays detailed information on current tag attributes
356        //indent(indentation);
357        //System.out.print("" + namespaceURI + "\"" + localName + "\": " + atts.getLength() + " attributes");
358        //for (int i = 0; i < atts.getLength(); i++) {
359        //    String attsName = atts.getLocalName(i);
360        //    String attsValue = atts.getValue(i);
361        //    System.out.print("   [" + i + "] " + attsName + " = \"" + attsValue + "\"");
362        //}
363        //System.out.println("");
364    }
365
366    @Override
367    public void characters(char[] chars, int i, int i1) throws SAXException {
368        //if (inElement) {
369        //    System.out.println("characters: =>" + chars/*.toString()*/ + "<= " + i + "," + i1 + " ==>" + new String(chars, i, i1) + "<==");
370        //}
371        String data = new String(chars, i, i1);
372        // Whitespace makes up default StringTokenizer delimeters
373        StringTokenizer tok = new StringTokenizer(data);
374        if (tok.hasMoreTokens()) { 
375            indent(indentation);
376            System.out.print("==>" + tok.nextToken());
377            while (tok.hasMoreTokens()) {
378                System.out.print(" " + tok.nextToken());
379            }
380            System.out.println("<==");
381        }
382    }
383
384    @Override
385    public void endElement(String uri, String localName, String qName) throws SAXException {
386        if (localName.equals("AnnotationTranslation")) {
387            if (!amInAnnotationTranslation){
388                System.err.println("*** WARNING *** " + getLocator() + " end of \"AnnotationTranslation\" while not in it, ignored");
389            }
390            else {
391                amInAnnotationTranslation = false;
392            }
393        }
394        else if (localName.equals("Resources")) {
395            if (!amInAnnotationTranslation){
396                System.err.println("*** WARNING *** " + getLocator() + " \"Resources\" end tag encountered while not in \"AnnotationTranslation\"");
397                amInAnnotationTranslation = false;
398            }
399            if (!amInResources){
400                System.err.println("*** WARNING *** " + getLocator() + " end of \"resources\" while not in it, ignored");
401            }
402            else {
403                amInResources = false;
404            }
405        }
406        else if (localName.equals("ResourceLayer")) {
407            if (!amInAnnotationTranslation){
408                System.err.println("*** WARNING *** " + getLocator() + " \"ResourceLayer\" end tag encountered while not in \"AnnotationTranslation\"");
409            }
410            if (!amInResources){
411                System.err.println("*** WARNING *** " + getLocator() + " \"ResourceLayer\" end tag encountered while not in \"Resources\"");
412            }
413        }
414        else if (localName.equals("Translations")) {
415            if (!amInAnnotationTranslation){
416                System.err.println("*** WARNING *** " + getLocator() + " \"Translations\" end tag encountered while not in \"AnnotationTranslation\"");
417            }
418            if (!amInTranslations){
419                System.err.println("*** WARNING *** " + getLocator() + " leaving \"Translations\" while not in translations, ignored");
420            }
421            else {
422                amInTranslations = false;
423            }
424        }
425        else if (localName.equals("TranslationTable")) {
426            if (!amInAnnotationTranslation){
427                System.err.println("*** WARNING *** " + getLocator() + " \"TranslationTable\" end tag encountered while not in \"AnnotationTranslation\"");
428                amInAnnotationTranslation = true;
429            }
430            if (!amInTranslations){
431                System.err.println("*** WARNING *** " + getLocator() + " \"TranslationTable\" end tag encountered while not in \"Translations\"");
432                amInTranslations = true;
433            }
434            if (!amInTranslationTable){
435                System.err.println("*** WARNING *** " + getLocator() + " leaving \"TranslationTable\" TWICE, ignored");
436            }
437            else {
438                amInTranslationTable = false;
439                curTable.tryPopulateTrellis();
440                curTable = null;
441            }
442        }
443        else if (localName.equals("Pair")) {
444            if (!amInAnnotationTranslation){
445                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" end tag encountered while not in \"AnnotationTranslation\"");
446                amInAnnotationTranslation = true;
447            }
448            if (!amInTranslations){
449                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" end tag encountered while not in \"Translations\"");
450                amInTranslations = true;
451            }
452            if (!amInTranslationTable){
453                System.err.println("*** WARNING *** " + getLocator() + " \"Pair\" end tag encountered while not in \"TranslationTable\"");
454                amInTranslationTable = true;
455            }
456        }
457        else {
458            System.err.println("*** ERROR *** " + getLocator() + " unknown end tag \"" + localName + "\", ignored");           
459        }
460    }
461
462    private void indent(int indentation) {
463        for(int i=0; i<indentation; i++) {
464            System.out.print(" ");
465        }
466    }
467
468    public void endDocument() throws SAXException {
469        Enumeration e = tags.keys();
470        while (e.hasMoreElements()) {
471            String tag = (String)e.nextElement();
472            int count = ((Integer)tags.get(tag)).intValue();
473            System.out.println("Local Name \"" + tag + "\" occurs " + count + " times");
474        }   
475    }
476 
477    private static String convertToFileURL(String fileName) {
478        String path = new File(fileName).getAbsolutePath();
479        if (File.separatorChar != '/') {
480            path = path.replace(File.separatorChar, '/');
481        }
482
483        if (!path.startsWith("/")) {
484            path = "/" + path;
485        }
486        return "file:" + path;
487    }
488}
Note: See TracBrowser for help on using the repository browser.