Blame view

src/main/java/pl/labno/bernard/htmlunified/DomChangeLogger.java 2.07 KB
bernard authored
1 2 3 4 5 6 7 8 9
package pl.labno.bernard.htmlunified;

import com.gargoylesoftware.htmlunit.html.DomChangeEvent;
import com.gargoylesoftware.htmlunit.html.DomChangeListener;
import com.gargoylesoftware.htmlunit.html.DomNode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Node;
bernard authored
10 11 12
import java.util.HashSet;
import java.util.Set;
bernard authored
13 14 15
public class DomChangeLogger implements DomChangeListener {

    private static final Log LOG = LogFactory.getLog(DomChangeLogger.class);
bernard authored
16
    private Set<String> detailIds = new HashSet<String>();
bernard authored
17 18 19 20 21 22 23 24 25

    public void nodeAdded(DomChangeEvent event) {
        logEvent(event, "added");
    }

    public void nodeDeleted(DomChangeEvent event) {
        logEvent(event, "removed");
    }
bernard authored
26 27 28 29 30 31 32 33
    public void showDetails(String id) {
        detailIds.add(id);
    }

    public void hideDetails(String id) {
        detailIds.remove(id);
    }
bernard authored
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    private void logEvent(DomChangeEvent event, String action) {
        String changed;
        final DomNode changedNode = event.getChangedNode();
        try {
            changed = changedNode.toString();
        } catch (Exception e) {
            changed = changedNode.getNodeName() + "[id=" + changedNode.getAttributes().getNamedItem("id") + ("#text".equals(changedNode.getNodeName()) ? ";value=" + changedNode.getTextContent() : "") + "]";
        }
        String parent;
        final DomNode parentNode = event.getParentNode();
        try {
            parent = parentNode.toString();
        } catch (Exception e) {
            parent = parentNode.getNodeName() + "[id=" + parentNode.getAttributes().getNamedItem("id") + ("#text".equals(parentNode.getNodeName()) ? ";value=" + parentNode.getTextContent() : "") + "]";
        }
        LOG.info("DomChangeEvent[action=" + action + ";changedElement=" + changed + ";source=" + event.getSource() + ";parent=" + parent + "]");
        final Node id = event.getChangedNode().getAttributes().getNamedItem("id");
bernard authored
51
        if (id != null && detailIds.contains(id.getTextContent())) {
bernard authored
52 53 54 55
            LOG.info(event.getChangedNode().asXml());
        }
    }
}