DomChangeLogger.java 2.07 KB
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;

import java.util.HashSet;
import java.util.Set;

public class DomChangeLogger implements DomChangeListener {

    private static final Log LOG = LogFactory.getLog(DomChangeLogger.class);
    private Set<String> detailIds = new HashSet<String>();

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

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

    public void showDetails(String id) {
        detailIds.add(id);
    }

    public void hideDetails(String id) {
        detailIds.remove(id);
    }

    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 && detailIds.contains(id.getTextContent())) {
            LOG.info(event.getChangedNode().asXml());
        }
    }
}