1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.frontend.xeditor.tracker;
20
21 import java.util.Iterator;
22
23 import org.jdom2.Document;
24 import org.jdom2.Element;
25 import org.jdom2.ProcessingInstruction;
26 import org.jdom2.filter.Filters;
27 import org.mycore.common.MCRException;
28 import org.mycore.common.config.MCRConfiguration2;
29
30 public class MCRChangeTracker implements Cloneable {
31
32 private static final String CONFIG_PREFIX = "MCR.XEditor.ChangeTracker.";
33
34 public static final String PREFIX = "xed-tracker-";
35
36 private int counter = 0;
37
38 public void track(MCRChangeData data) {
39 ProcessingInstruction pi = data.getProcessingInstruction();
40 pi.setTarget(PREFIX + (++counter) + "-" + pi.getTarget());
41 data.getContext().addContent(data.getPosition(), pi);
42 }
43
44 public int getChangeCounter() {
45 return counter;
46 }
47
48 public void undoChanges(Document doc) {
49 undoChanges(doc, 0);
50 }
51
52 public void undoChanges(Document doc, int stepNumber) {
53 while (counter > stepNumber) {
54 undoLastChange(doc);
55 }
56 }
57
58 public String undoLastBreakpoint(Document doc) {
59 while (counter > 0) {
60 MCRChangeData change = undoLastChange(doc);
61 if ("breakpoint".equals(change.getType())) {
62 return change.getText();
63 }
64 }
65 return null;
66 }
67
68 public MCRChangeData undoLastChange(Document doc) {
69 MCRChangeData data = findLastChange(doc);
70 data.getProcessingInstruction().detach();
71 counter--;
72
73 String property = CONFIG_PREFIX + data.getType() + ".Class";
74 MCRChange change = MCRConfiguration2.<MCRChange>getSingleInstanceOf(property)
75 .orElseThrow(() -> MCRConfiguration2.createConfigurationException(property));
76 change.undo(data);
77 return data;
78 }
79
80 public MCRChangeData findLastChange(Document doc) {
81 String typePrefix = PREFIX + counter + "-";
82 for (ProcessingInstruction instruction : doc.getDescendants(Filters.processinginstruction())) {
83 String target = instruction.getTarget();
84
85 if (target.startsWith(typePrefix)) {
86 return new MCRChangeData(instruction, typePrefix);
87 }
88 }
89 throw new MCRException("Lost processing instruction for undo, not found: " + typePrefix);
90 }
91
92 public static Document removeChangeTracking(Document doc) {
93 Document clone = doc.clone();
94 removeChangeTracking(clone.getRootElement());
95 return clone;
96 }
97
98 public static void removeChangeTracking(Element element) {
99 for (Iterator<ProcessingInstruction> iter = element.getDescendants(Filters.processinginstruction())
100 .iterator(); iter.hasNext();) {
101 if (iter.next().getTarget().startsWith(PREFIX)) {
102 iter.remove();
103 }
104 }
105 }
106
107 @Override
108 public MCRChangeTracker clone() {
109 MCRChangeTracker tracker = new MCRChangeTracker();
110 tracker.counter = this.counter;
111 return tracker;
112 }
113 }