1
2
3
4
5
6
7
8
9
10
11
12 package sk.uniba.euromath.editor.wizards.document;
13 import java.util.Collections;
14 import java.util.List;
15 import org.w3c.dom.Element;
16 import sk.baka.ikslibs.ids.FailEnum;
17 import sk.baka.ikslibs.modify.DOMMutils;
18 import sk.baka.ikslibs.ptr.DOMPoint;
19 import sk.baka.ikslibs.ptr.DomPointer;
20 import sk.baka.ikslibs.ptr.DomPointerFactory;
21 import sk.baka.xml.gene.ExportException;
22 import sk.uniba.euromath.document.XMLAccess;
23 /***
24 * Represents an instance of element and an insertpoint, where the element
25 * should be inserted.
26 * @author Martin Vysny
27 */
28 public final class ElementLoc {
29 /***
30 * Constructor.
31 * @param xmlAccess the document instance.
32 * @param parent the parent element where given elements shall be inserted.
33 * @param elements the list of elements
34 * @param ip the list of insertpoints
35 */
36 public ElementLoc(XMLAccess xmlAccess, Element parent,
37 List<Element> elements, List<DOMPoint> ip) {
38 super();
39 if ((elements.size() != ip.size()) || (elements.size() == 0))
40 throw new IllegalArgumentException(
41 "Both lists must have same non-zero length");
42 this.xmlAccess = xmlAccess;
43 this.parent = parent;
44 this.elements = elements;
45 this.ip = ip;
46 }
47 /***
48 * List of elements.
49 */
50 private final List<Element> elements;
51 /***
52 * List of insertpoints where the elements shall be inserted.
53 */
54 private final List<DOMPoint> ip;
55 /***
56 * The parent element.
57 */
58 public final Element parent;
59 /***
60 * Modify this document.
61 */
62 private final XMLAccess xmlAccess;
63 /***
64 * Returns list of elements.
65 * @return list of elements, never <code>null</code>.
66 */
67 public List<Element> getElements() {
68 return Collections.unmodifiableList(elements);
69 }
70 /***
71 * Returns list of insertpoints.
72 * @return list of insertpoints, never <code>null</code>.
73 */
74 public List<DOMPoint> getLocations() {
75 return Collections.unmodifiableList(ip);
76 }
77 /***
78 * Inserts the elements into their locations.
79 * @throws ExportException if error occurs during document modification.
80 */
81 public void insert() throws ExportException {
82
83
84
85 DomPointer[] insertPtr = new DomPointer[ip.size()];
86 for (int i = 0; i < ip.size(); i++) {
87 DOMPoint ip = this.ip.get(i);
88 if (!ip.isValid(parent.getChildNodes(), false, false))
89 throw new IllegalStateException("Invalid insertpoint: " + ip);
90 insertPtr[i] = DomPointerFactory.create(parent, ip);
91 }
92
93 xmlAccess.getModifier().startModify();
94
95 int i = 0;
96 for (Element root : elements) {
97 if (root.getParentNode() != null)
98 throw new IllegalStateException(
99 "Elements are already inserted in their locations");
100
101 xmlAccess.getIdManager().addTree(root, FailEnum.FailWhenIdExists);
102
103 DOMMutils.insertNode(root, insertPtr[i], false);
104 i++;
105 }
106 xmlAccess.getModifier().endModify();
107 }
108 }