Blame view

src/main/java/pl/labno/bernard/htmlunified/DomChangeLogger.java 1.83 KB
bernard authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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;

public class DomChangeLogger implements DomChangeListener {

    private static final Log LOG = LogFactory.getLog(DomChangeLogger.class);

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

    public void nodeDeleted(DomChangeEvent event) {
        logEvent(event, "removed");
    }

    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");
        if (id != null && "searchClass:searchStudent".equals(id.getTextContent())) {
            LOG.info(event.getChangedNode().asXml());
        }
    }
}