Debian Codegraph @

src/dr/xml/XMLParser.java

raw symbols SCIP
1 /*
2 * XMLParser.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.xml;
27
28 import dr.inference.model.Likelihood;
29 import dr.inference.model.Model;
30 import dr.inference.model.Parameter;
31 import dr.inferencexml.loggers.LoggerParser;
32 import dr.util.*;
33 import org.w3c.dom.*;
34 import org.xml.sax.InputSource;
35 import org.xml.sax.SAXException;
36 import org.xml.sax.SAXParseException;
37 import org.xml.sax.helpers.DefaultHandler;
38
39 import java.io.*;
40 import java.util.*;
41
42 public class XMLParser {
43
44 public static final String ID = XMLObject.ID;
45 public static final String IDREF = "idref";
46 public static final String CONCURRENT = "concurrent";
47 public static final String VERSION = "version";
48
49 private Vector<Thread> threads = new Vector<Thread>();
50 protected boolean strictXML;
51 protected boolean parserWarnings;
52
53 // The software version
54 private final Version version;
55
56 public XMLParser(boolean verbose, boolean parserWarnings, boolean strictXML, Version version) {
57 this.verbose = verbose;
58 this.parserWarnings = parserWarnings;
59 this.strictXML = strictXML;
60 addXMLObjectParser(new ArrayParser(), false);
61 addXMLObjectParser(Report.PARSER, false);
62
63 this.version = version;
64 }
65
66 public void addXMLObjectParser(XMLObjectParser parser) {
67 addXMLObjectParser(parser, false);
68 }
69
70 public boolean addXMLObjectParser(XMLObjectParser parser, boolean canReplace) {
71
72 boolean replaced = false;
73 String[] parserNames = parser.getParserNames();
74
75 for (String parserName : parserNames) {
76 XMLObjectParser oldParser = parserStore.get(parserName);
77 if (oldParser != null) {
78 if (!canReplace) {
79 throw new IllegalArgumentException("New parser (" + parser.getParserName()
80 + ") in {" + parser.getReturnType() + "} cannot replace existing parser ("
81 + oldParser.getParserName() + ") in {" + oldParser.getReturnType() + "}");
82 } else {
83 replaced = true;
84 }
85 }
86 parserStore.put(parserName, parser);
87 }
88
89 return replaced;
90 }
91
92 public Iterator getParserNames() {
93 return parserStore.keySet().iterator();
94 }
95
96 public XMLObjectParser getParser(String name) {
97 return parserStore.get(name);
98 }
99
100 public Iterator getParsers() {
101 return parserStore.values().iterator();
102 }
103
104 public Iterator getThreads() {
105 return threads.iterator();
106 }
107
108 public void storeObject(String name, Object object) {
109
110 XMLObject xo = new XMLObject(null, null /*, objectStore*/);
111 xo.setNativeObject(object);
112 objectStore.put(name, xo);
113 }
114
115 /**
116 * An alternative parser that parses until it finds an object of the given
117 * class and then returns it.
118 *
119 * @param reader the reader
120 * @param target the target class
121 * @return
122 * @throws java.io.IOException
123 * @throws org.xml.sax.SAXException
124 * @throws dr.xml.XMLParseException
125 * @throws javax.xml.parsers.ParserConfigurationException
126 *
127 */
128 public Object parse(Reader reader, Class target)
129 throws java.io.IOException,
130 org.xml.sax.SAXException,
131 dr.xml.XMLParseException,
132 javax.xml.parsers.ParserConfigurationException {
133
134 InputSource in = new InputSource(reader);
135 javax.xml.parsers.DocumentBuilderFactory documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
136
137 javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
138 Document document = documentBuilder.parse(in);
139
140 Element e = document.getDocumentElement();
141 if (e.getTagName().equals("beast")) {
142
143 concurrent = false;
144 return convert(e, target, null, false, true);
145
146 } else {
147 throw new dr.xml.XMLParseException("Unknown root document element, " + e.getTagName());
148 }
149 }
150
151 public Map<String, XMLObject> parse(Reader reader, boolean run)
152 throws java.io.IOException,
153 org.xml.sax.SAXException,
154 dr.xml.XMLParseException,
155 javax.xml.parsers.ParserConfigurationException {
156
157 InputSource in = new InputSource(reader);
158 javax.xml.parsers.DocumentBuilderFactory documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
159
160 javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
161 documentBuilder.setErrorHandler(new MyErrorHandler());
162 Document document = documentBuilder.parse(in);
163
164 Element e = document.getDocumentElement();
165 if (e.getTagName().equals("beast")) {
166 // If the 'version' is attribute is present then check it is not an more recent version...
167 if (e.hasAttribute(VERSION)) {
168 String xmlVersion = e.getAttribute(VERSION);
169 if (version != null && Version.Utils.isMoreRecent(xmlVersion, version.getVersion())) {
170 throw new XMLParseException("The version of BEAUti that generated this XML (" + xmlVersion + ") is more recent than the version of BEAST running it (" + version.getVersion() + "). This may be incompatible and cause unpredictable errors.");
171 }
172 }
173
174 concurrent = false;
175 root = (XMLObject) convert(e, null, null, run, true);
176
177 } else {
178 throw new dr.xml.XMLParseException("Unknown root document element, " + e.getTagName());
179 }
180
181 return objectStore;
182 }
183
184 private class MyErrorHandler extends DefaultHandler {
185 public void warning(SAXParseException e) throws SAXException {
186 System.out.println("Warning: ");
187 printInfo(e);
188 }
189
190 public void error(SAXParseException e) throws SAXException {
191 System.out.println("Error: ");
192 printInfo(e);
193 }
194
195 public void fatalError(SAXParseException e) throws SAXException {
196 System.out.println("Fatal error: ");
197 printInfo(e);
198 }
199
200 private void printInfo(SAXParseException e) {
201 // System.out.println("\tPublic ID: " + e.getPublicId());
202 // System.out.println("\tSystem ID: " + e.getSystemId());
203 System.out.println("\tLine number: " + e.getLineNumber());
204 System.out.println("\tColumn number: " + e.getColumnNumber());
205 System.out.println("\tError message: " + e.getMessage());
206 }
207 }
208
209 public XMLObject getRoot() {
210 return root;
211 }
212
213 private Object convert(Element e, Class target, XMLObject parent, boolean run, boolean doParse) throws XMLParseException {
214
215 int index = -1;
216
217 if (e.hasAttribute(IDREF)) {
218
219 String idref = e.getAttribute(IDREF);
220
221 if (e.hasAttribute("index")) {
222 index = Integer.parseInt(e.getAttribute("index"));
223 }
224 if ((e.getAttributes().getLength() > 1 || e.getChildNodes().getLength() > 1) && index == -1) {
225 throw new XMLParseException("Object with idref=" + idref + " must not have other content or attributes (or perhaps it was not intended to be a reference?).");
226 }
227
228
229 XMLObject restoredXMLObject = objectStore.get(idref);
230 if (index != -1) {
231
232 if (restoredXMLObject.getNativeObject() instanceof List) {
233
234 restoredXMLObject = new XMLObject(restoredXMLObject, index);
235 } else {
236 throw new XMLParseException("Trying to get indexed object from non-list");
237 }
238 }
239
240 if (restoredXMLObject == null) {
241 throw new XMLParseException("Object with idref=" + idref + " has not been previously declared.");
242 }
243
244 if (restoredXMLObject.getNativeObject() == null) {
245 throw new XMLParseException("Object with idref=" + idref + " has not been parsed.");
246 }
247
248 XMLObjectParser parser = parserStore.get(e.getTagName());
249 boolean classMatch = parser != null && parser.getReturnType().isAssignableFrom(restoredXMLObject.getNativeObject().getClass());
250
251 if (!e.getTagName().equals(restoredXMLObject.getName()) && !classMatch) {
252 String msg = "Element named " + e.getTagName() + " with idref=" + idref +
253 " does not match stored object with same id and tag name " + restoredXMLObject.getName();
254 if (strictXML) {
255 throw new XMLParseException(msg);
256 } else if (parserWarnings) {
257 // System.err.println("WARNING: " + msg);
258 java.util.logging.Logger.getLogger("dr.xml").warning(msg);
259 }
260 }
261
262 if (verbose) System.out.println(" Restoring idref=" + idref);
263
264
265 return new Reference(restoredXMLObject);
266
267 } else {
268 int repeats = 1;
269 if (e.getTagName().equals(CONCURRENT)) {
270 if (concurrent) throw new XMLParseException("Nested concurrent elements not allowed.");
271 concurrent = true;
272
273 threads = new Vector<Thread>();
274 } else if (e.getTagName().equals("repeat")) {
275 repeats = Integer.parseInt(e.getAttribute("count"));
276 }
277
278 XMLObject xo = new XMLObject(e, parent);
279
280 final XMLObjectParser parser = doParse ? parserStore.get(xo.getName()) : null;
281
282 String id = null;
283 NodeList nodes = e.getChildNodes();
284 for (int k = 0; k < repeats; k++) {
285 for (int i = 0; i < nodes.getLength(); i++) {
286
287 Node child = nodes.item(i);
288 if (child instanceof Element) {
289
290 final Element element = (Element) child;
291 final String tag = element.getTagName();
292 if (verbose) System.out.println("Parsing " + tag);
293
294 // don't parse elements that may be legal here with global parsers
295 final boolean parseIt = parser == null || !parser.isAllowed(tag);
296 Object xoc = convert(element, target, xo, run, parseIt);
297 xo.addChild(xoc);
298
299 if (target != null && xoc instanceof XMLObject) {
300 Object obj = ((XMLObject) xoc).getNativeObject();
301 if (obj != null && target.isInstance(obj)) {
302 return obj;
303 }
304 }
305
306 } else if (child instanceof Text) {
307 // just add text as a child of type String object
308 String text = ((Text) child).getData().trim();
309 if (text.length() > 0) {
310 xo.addChild(text);
311 }
312 }
313 }
314 }
315 if (e.hasAttribute(ID)) {
316 id = e.getAttribute(ID);
317 }
318
319 if ((id != null) && objectStore.get(id) != null) {
320 throw new XMLParseException("Object with Id=" + id + " already exists");
321 }
322
323 Object obj = null;
324 if (parser != null) {
325 obj = parser.parseXMLObject(xo, id, objectStore, strictXML);
326
327 if (obj instanceof Identifiable) {
328 ((Identifiable) obj).setId(id);
329 }
330
331 if (obj instanceof Citable) {
332 addCitable((Citable)obj);
333 }
334
335 if (obj instanceof Likelihood) {
336 Likelihood.FULL_LIKELIHOOD_SET.add((Likelihood) obj);
337 } else if (obj instanceof Model) {
338 Model.FULL_MODEL_SET.add((Model) obj);
339 } else if (obj instanceof Parameter) {
340 Parameter.FULL_PARAMETER_SET.add((Parameter) obj);
341 }
342
343 xo.setNativeObject(obj);
344 }
345
346 if (id != null) {
347 if (verbose) System.out.println(" Storing " + xo.getName() + " with id=" + id);
348
349 objectStore.put(id, xo);
350 }
351
352 if (run) {
353 if (e.getTagName().equals(CONCURRENT)) {
354 for (int i = 0; i < xo.getChildCount(); i++) {
355 Object child = xo.getChild(i);
356 if (child instanceof Runnable) {
357 Thread thread = new Thread((Runnable) child);
358 thread.start();
359 threads.add(thread);
360 } else throw new XMLParseException("Concurrent element children must be runnable!");
361 }
362 concurrent = false;
363 // wait for all threads collected to die
364 for (Object thread1 : threads) {
365 waitForThread((Thread) thread1);
366 }
367 } else if (obj instanceof Runnable && !concurrent) {
368
369 executingRunnable();
370
371 if (obj instanceof Spawnable && !((Spawnable) obj).getSpawnable()) {
372 ((Spawnable) obj).run();
373 } else {
374 Thread thread = new Thread((Runnable) obj);
375 thread.start();
376 threads.add(thread);
377 waitForThread(thread);
378 }
379 }
380 threads.removeAllElements();
381 }
382
383 return xo;
384 }
385 }
386
387 protected void executingRunnable() {
388 // do nothing - for overriding by subclasses
389 }
390
391 public Map<Pair<String, String>, List<Citation>> getCitationStore() {
392 return citationStore;
393 }
394
395 public static FileReader getFileReader(XMLObject xo, String attributeName) throws XMLParseException {
396 if (xo.hasAttribute(attributeName)) {
397 final File inFile = getFileHandle(xo, attributeName);
398 try {
399 return new FileReader(inFile);
400 } catch (FileNotFoundException e) {
401 throw new XMLParseException("Input file " + inFile.getName()
402 + " was not found in the working directory");
403 }
404 }
405 throw new XMLParseException("Error reading input file in " + xo.getId());
406 }
407
408
409 /**
410 * Get filename and path from BEAST XML object
411 *
412 * @param xo
413 * @return
414 */
415 private static File getFileHandle(XMLObject xo, String attributeName) throws XMLParseException {
416 String fileName = xo.getStringAttribute(attributeName);
417
418 // Check to see if a filename prefix has been specified, check it doesn't contain directory
419 // separator characters and then prefix it.
420 final String fileNamePrefix = System.getProperty("file.name.prefix");
421 final String fileSeparator = System.getProperty("file.separator");
422 if (fileNamePrefix != null) {
423 if (fileNamePrefix.trim().length() == 0 || fileNamePrefix.contains(fileSeparator)) {
424 throw new XMLParseException("The specified file name prefix is illegal.");
425 }
426 }
427
428 final String fileRankPostfix = System.getProperty("mpi.rank.postfix");
429 if (fileRankPostfix != null) {
430 if (fileName.endsWith(".log")) {
431 fileName = fileName.substring(0, fileName.length() - 4) + fileRankPostfix + ".log";
432 }
433 if (fileName.endsWith(".trees")) {
434 fileName = fileName.substring(0, fileName.length() - 6) + fileRankPostfix + ".trees";
435 }
436 }
437
438 return FileHelpers.getFile(fileName, fileNamePrefix);
439 }
440
441 /**
442 * Allow a file relative to beast xml file with a prefix of ./
443 *
444 * @param xo element
445 * @param parserName for error messages
446 * @return Print writer from fileName attribute in the given XMLObject
447 * @throws XMLParseException if file can't be created for some reason
448 */
449
450 public static PrintWriter getFilePrintWriter(XMLObject xo, String parserName) throws XMLParseException {
451 return getFilePrintWriter(xo, parserName, FileHelpers.FILE_NAME);
452 }
453
454 public static PrintWriter getFilePrintWriter(XMLObject xo, String parserName, String attributeName) throws XMLParseException {
455
456 if (xo.hasAttribute(attributeName)) {
457 File logFile = getLogFile(xo, attributeName);
458
459 try {
460 return new PrintWriter(new FileOutputStream(logFile));
461 } catch (FileNotFoundException fnfe) {
462 throw new XMLParseException("File '" + logFile.getAbsolutePath() +
463 "' can not be opened for " + parserName + " element.");
464 }
465
466 }
467 return new PrintWriter(System.out);
468 }
469
470 public static File getLogFile(XMLObject xo, String attributeName) throws XMLParseException {
471 final File logFile = getFileHandle(xo, attributeName);
472 boolean allowOverwrite = false;
473
474 if (xo.hasAttribute(LoggerParser.ALLOW_OVERWRITE_LOG)) {
475 allowOverwrite = xo.getBooleanAttribute(LoggerParser.ALLOW_OVERWRITE_LOG);
476 }
477
478 // override with a runtime set System Property
479 if (System.getProperty("log.allow.overwrite") != null) {
480 allowOverwrite = Boolean.parseBoolean(System.getProperty("log.allow.overwrite", "false"));
481 }
482
483 if (logFile.exists() && !allowOverwrite) {
484 throw new XMLParseException("\nThe log file " + logFile.getName() + " already exists in the working directory." +
485 "\nTo allow it to be overwritten, use the '-overwrite' command line option when running" +
486 "\nBEAST or select the option in the Run Options dialog box as appropriate.");
487 }
488
489
490 return logFile;
491 }
492
493 public Map<String, XMLObject> getObjectStore() {
494 return objectStore;
495 }
496
497 public class ArrayParser extends AbstractXMLObjectParser {
498
499 public String getParserName() {
500 return "array";
501 }
502
503 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
504
505 List<Object> list = new ArrayList<Object>();
506
507 for (int i = 0; i < xo.getChildCount(); i++) {
508 list.add(xo.getChild(i));
509 }
510 return list;
511 }
512
513 //************************************************************************
514 // AbstractXMLObjectParser implementation
515 //************************************************************************
516
517 public String getParserDescription() {
518 return "This element returns an array of the objects it contains.";
519 }
520
521 public Class getReturnType() {
522 return Object[].class;
523 }
524
525 public XMLSyntaxRule[] getSyntaxRules() {
526
527 return new XMLSyntaxRule[]{new ElementRule(Object.class, "Objects to be put in an array", 1, Integer.MAX_VALUE)};
528 }
529
530 }
531
532 private void waitForThread(Thread thread) {
533 // wait doggedly for thread to die
534 while (thread.isAlive()) {
535 try {
536 thread.join();
537 } catch (InterruptedException ie) {
538 // DO NOTHING
539 }
540 }
541 }
542
543 // //anonymous object store class
544 // private final ObjectStore objectStore = new ObjectStore() {
545 // public Object getObjectById(Object uid) throws ObjectNotFoundException {
546 // XMLObject obj = (XMLObject) store.get(uid);
547 // if (obj == null) throw new ObjectNotFoundException("Object with uid=" + uid + " not found in ObjectStore");
548 // if (obj.hasNativeObject()) return obj.getNativeObject();
549 // return obj;
550 // }
551 //
552 // public boolean hasObjectId(Object uid) {
553 // Object obj = store.get(uid);
554 // return (obj != null);
555 // }
556 //
557 // public Set getIdSet() {
558 // return store.keySet();
559 // }
560 //
561 // public Collection getObjects() {
562 // return store.values();
563 // }
564 //
565 //// public void addIdentifiableObject(Identifiable obj, boolean force) {
566 ////
567 //// String id = obj.getId();
568 //// if (id == null) throw new IllegalArgumentException("Object must have a non-null identifier.");
569 ////
570 //// if (force) {
571 //// store.put(id, obj);
572 //// } else {
573 //// if (store.get(id) == null) {
574 //// store.put(id, obj);
575 //// }
576 //// }
577 //// }
578 // };
579
580 public void addCitable(Citable citable) {
581 // remove 'In prep' citations
582 List<Citation> citationList = new LinkedList<Citation>();
583 for (Citation citation : citable.getCitations()) {
584 if (citation.getStatus() != Citation.Status.IN_PREPARATION) {
585 citationList.add(citation);
586 }
587 }
588 if (citationList.size() > 0) {
589 Pair<String, String> pair = new Pair<String, String>(citable.getCategory().toString(),
590 citable.getDescription());
591 citationStore.put(pair, citationList);
592 }
593 }
594
595 // private final Hashtable<String, XMLObject> store = new Hashtable<String, XMLObject>();
596 private final Map<String, XMLObjectParser> parserStore = new TreeMap<String, XMLObjectParser>(new ParserComparator());
597 private final Map<String, XMLObject> objectStore = new LinkedHashMap<String, XMLObject>();
598 private final Map<Pair<String, String>, List<Citation>> citationStore = new LinkedHashMap<Pair<String, String>, List<Citation>>();
599 private boolean concurrent = false;
600 private XMLObject root = null;
601
602 private boolean verbose = false;
603
604 public static class Utils {
605
606 /**
607 * Throws a runtime exception if the element does not have
608 * the given name.
609 */
610 public static void validateTagName(Element e, String name) throws XMLParseException {
611 if (!e.getTagName().equals(name)) {
612 throw new XMLParseException("Wrong tag name! Expected " + name + ", found " + e.getTagName() + ".");
613 }
614 }
615
616 public static boolean hasAttribute(Element e, String name) {
617 String attr = e.getAttribute(name);
618 return ((attr != null) && !attr.equals(""));
619 }
620
621 /**
622 * @return the first child element of the given name.
623 */
624 public static Element getFirstByName(Element parent, String name) {
625 NodeList nodes = parent.getElementsByTagName(name);
626 if (nodes.getLength() > 0) {
627 return (Element) nodes.item(0);
628 } else return null;
629 }
630
631 }
632
633 class ParserComparator implements Comparator<String> {
634 public int compare(String o1, String o2) {
635 String name1 = o1.toUpperCase();
636 String name2 = o2.toUpperCase();
637
638 return name1.compareTo(name2);
639 }
640 }
641
642 }
643
644