DomChangeLogger.java
2.07 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
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());
}
}
}