001package org.hl7.fhir.r5.utils.formats;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034import java.util.Stack;
035
036import org.w3c.dom.Document;
037import org.w3c.dom.Element;
038import org.w3c.dom.Node;
039import org.w3c.dom.UserDataHandler;
040import org.w3c.dom.events.Event;
041import org.w3c.dom.events.EventListener;
042import org.w3c.dom.events.EventTarget;
043import org.w3c.dom.events.MutationEvent;
044import org.xml.sax.Attributes;
045import org.xml.sax.Locator;
046import org.xml.sax.SAXException;
047import org.xml.sax.SAXNotRecognizedException;
048import org.xml.sax.SAXNotSupportedException;
049import org.xml.sax.XMLReader;
050import org.xml.sax.helpers.LocatorImpl;
051import org.xml.sax.helpers.XMLFilterImpl;
052
053// http://javacoalface.blogspot.com.au/2011/04/line-and-column-numbers-in-xml-dom.html
054
055public class XmlLocationAnnotator extends XMLFilterImpl  {
056
057  private Locator locator;
058  private Stack<Locator> locatorStack = new Stack<Locator>();
059  private Stack<Element> elementStack = new Stack<Element>();
060  private UserDataHandler dataHandler = new LocationDataHandler();
061
062  public XmlLocationAnnotator(XMLReader xmlReader, Document dom) {
063      super(xmlReader);
064
065      // Add listener to DOM, so we know which node was added.
066      EventListener modListener = new EventListener() {
067          @Override
068          public void handleEvent(Event e) {
069              EventTarget target = ((MutationEvent) e).getTarget();
070              elementStack.push((Element) target);
071          }
072      };
073      ((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
074  }
075
076  @Override
077  public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
078    if (!name.equals("http://javax.xml.XMLConstants/property/accessExternalDTD")) {
079      super.setProperty(name, value);
080    }
081  }
082
083  @Override
084  public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
085    if (!name.equals("http://javax.xml.XMLConstants/property/accessExternalDTD")) {
086      return null;
087    } else {
088      return super.getProperty(name);
089    }
090  }
091
092  @Override
093  public void setDocumentLocator(Locator locator) {
094      super.setDocumentLocator(locator);
095      this.locator = locator;
096  }
097
098  @Override
099  public void startElement(String uri, String localName,
100          String qName, Attributes atts) throws SAXException {
101      super.startElement(uri, localName, qName, atts);
102
103      // Keep snapshot of start location,
104      // for later when end of element is found.
105      locatorStack.push(new LocatorImpl(locator));
106  }
107
108  @Override
109  public void endElement(String uri, String localName, String qName)
110          throws SAXException {
111
112      // Mutation event fired by the adding of element end,
113      // and so lastAddedElement will be set.
114      super.endElement(uri, localName, qName);
115     
116      if (locatorStack.size() > 0) {
117          Locator startLocator = locatorStack.pop();
118         
119          XmlLocationData location = new XmlLocationData(
120                  startLocator.getSystemId(),
121                  startLocator.getLineNumber(),
122                  startLocator.getColumnNumber(),
123                  locator.getLineNumber(),
124                  locator.getColumnNumber());
125         Element lastAddedElement = elementStack.pop();
126         
127          lastAddedElement.setUserData(
128                  XmlLocationData.LOCATION_DATA_KEY, location,
129                  dataHandler);
130      }
131  }
132
133  // Ensure location data copied to any new DOM node.
134  private class LocationDataHandler implements UserDataHandler {
135
136      @Override
137      public void handle(short operation, String key, Object data,
138              Node src, Node dst) {
139         
140          if (src != null && dst != null) {
141              XmlLocationData locatonData = (XmlLocationData)
142                      src.getUserData(XmlLocationData.LOCATION_DATA_KEY);
143             
144              if (locatonData != null) {
145                  dst.setUserData(XmlLocationData.LOCATION_DATA_KEY,
146                          locatonData, dataHandler);
147              }
148          }
149      }
150  }
151
152  
153  
154}