summaryrefslogtreecommitdiff
path: root/xmerge/source/xmerge/java/org/openoffice/xmerge/merger/diff/NodeIterator.java
blob: 6a37680657229ae5d682ad377773743db3b9b4c7 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

package org.openoffice.xmerge.merger.diff;

import java.util.ArrayList;
import java.util.List;

import org.openoffice.xmerge.ConverterCapabilities;
import org.openoffice.xmerge.merger.Iterator;
import org.openoffice.xmerge.util.Debug;
import org.openoffice.xmerge.util.Resources;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * This is an implementation of the {@code Iterator} interface.
 *
 * <p>It will traverse the tree and find {@code Node} sequences.</p>
 *
 * <p>Note: Once the XML Tree is parsed, then the {@code Iterator} will be a
 * snap shot of that tree. That means even the tree is modified later, than the
 * cached paragraph {@code Node} list will not be updated accordingly.  For this
 * reason and for performance reasons this {@code Iterator} does not support any
 * operation methods such as insert, remove or replace. The main purpose of this
 * {@code Iterator} is to be used with difference, not with merge.</p>
 */
public abstract class NodeIterator implements Iterator {

    private List<Node> nodeList = null;
    private int currentPosition = 0;
    private final Node root;
    private final ConverterCapabilities cc_;

    /**
     * Standard constructor.
     *
     * @param  cc    The {@code ConverterCapabilities}.
     * @param  node  The initial root {@code Node}.
     */
    public NodeIterator(ConverterCapabilities cc, Node node) {
        cc_ = cc;
        nodeList = new ArrayList<Node>();
        root = node;
        markTree(node);
    }

    public Object next() {
        if (currentPosition < nodeList.size() - 1) {
            currentPosition++;
            return currentElement();
        } else {
            return null;
        }
    }

    public Object previous() {
        if (currentPosition > 0) {
            currentPosition--;
            return currentElement();
        } else {
            return null;
        }
    }

    public Object start() {
        currentPosition = 0;
        return currentElement();
    }

    public Object end() {
        int size = nodeList.size();

        if (size > 0) {
            currentPosition = size - 1;
            return currentElement();
        } else  {
            return null;
        }
    }

    public Object currentElement() {
        if (currentPosition < 0 || currentPosition >= nodeList.size()) {
            return null;
        }
        return nodeList.get(currentPosition);
    }

    public int elementCount() {
        return nodeList.size();
    }

    public boolean equivalent(Object obj1, Object obj2) {
        boolean equal = false;
        if (!(obj1 instanceof Node && obj2 instanceof Node)) {
            String errMsg = Resources.getInstance().getString("NOT_NODE_ERROR");
            Debug.log(Debug.ERROR, errMsg);
        } else {
            Node node1 = (Node)obj1;
            Node node2 = (Node)obj2;

            equal = compareNode(node1, node2);
        }
        return equal;
    }

    public void refresh() {
        nodeList = new ArrayList<Node>();
        markTree(root);
        currentPosition = 0;
    }

    /**
     * Used to compare two {@code Node} objects (type/name/value) and all their
     * children {@code Node} objects.
     *
     * @param   node1  The first {@code Node} to compare.
     * @param   node2  The second {@code Node} to compare.
     *
     * @return  {@code true} if {@code Node} is equal, {@code false} otherwise.
     */
    protected boolean compareNode(Node node1, Node node2) {
        boolean equal = false;

        nodeCheck: {

            if (node1 == null || node2 == null) {
                break nodeCheck;
            }

            // nodevalue is short
            if (node1.getNodeType() != node2.getNodeType()) {
                break nodeCheck;
            }

            // nodeName will not be null
            if (!node1.getNodeName().equals(node2.getNodeName())) {
                break nodeCheck;
            }

            // nodeValue can be null for a lot of type of cells
            if (node1.getNodeValue() == null && node2.getNodeValue() == null) {
                // empty
            } else if (node1.getNodeValue() == null ||
                       node2.getNodeValue() == null) {
                break nodeCheck;
            } else if (!node1.getNodeValue().equals(node2.getNodeValue())) {
                break nodeCheck;
            }

            // try to compare attributes
            if (!attributesEqual(node1, node2)) {
                break nodeCheck;
            }

            // don't need to compare if both node do not have children
            if (!node1.hasChildNodes() && !node2.hasChildNodes()) {
                equal = true;
                break nodeCheck;
            // don't need to compare if one node has children but not the other
            } else if (!node1.hasChildNodes() || !node2.hasChildNodes()) {
                equal = false;
                break nodeCheck;
            // need to compare if both node has children
            } else if (!childrenEqual(node1, node2)) {
                break nodeCheck;
            }

            equal = true;
        }

        return equal;
    }

    /**
     * Compare the children of two {@code Node} objects.
     *
     * <p>This method can be intentionally overridden by any class that extend
     * from {@code NodeIterator} so that it can have its own children comparison
     * if necessary.</p>
     *
     * @param   node1  The first {@code Node} to compare.
     * @param   node2  The second {@code Node} to compare.
     *
     * @return  {@code true} if children are equal, {@code false} otherwise.
     */
    protected boolean childrenEqual(Node node1, Node node2) {

        boolean equal = false;

        childrenCheck: {
            NodeList node1Children = node1.getChildNodes();
            NodeList node2Children = node2.getChildNodes();

            if (node1Children == null || node2Children == null) {
                break childrenCheck;
            }

            if (node1Children.getLength() != node2Children.getLength())  {
                break childrenCheck;
            }

            // compare all the children
            equal = true;

            for (int i = 0; i < node1Children.getLength(); i++) {
                if (!compareNode(node1Children.item(i),
                                 node2Children.item(i))) {
                    equal = false;
                    break childrenCheck;
                }
            }
        }

        return equal;
    }

    /**
     * Compare attributes of two {@code Node} objects.
     *
     * <p>This method can be intentionally overridden by any class that extends
     * from {@code NodeIterator} so that it can have its own attribute comparison.
     * </p>
     *
     *  @param   node1  The first {@code Node} to compare.
     *  @param   node2  The second {@code Node} to compare.
     *
     *  @return  {@code true} if attributes are equal, {@code false} otherwise.
     */
    private boolean attributesEqual(Node node1, Node node2) {

        boolean equal = false;
        String nodeName = node1.getNodeName();
        NamedNodeMap attrNode[] = new NamedNodeMap[2];
        attrNode[0] = node1.getAttributes();
        attrNode[1] = node2.getAttributes();

        // Attribute node will be null if node is not an element node
        // and attribute nodes are equal if both are not element node
        if (attrNode[0] == null || attrNode[1] == null) {
            if (attrNode[0] == null && attrNode[1] == null) {
                equal = true;
            }
            return equal;
        }

        // Compare the attributes from node1 vs node2 and node2 vs node1
        // though it's a little inefficient for the duplication of comparison
        // as the number of attributes is not so many, it should not be
        // a big problem.
        int len [] = new int[2];
        int src, dst;

        attrCheck: {
            for (int i = 0; i < 2; i++) {

                if (i == 0) {
                    src = 0;
                    dst = 1;
                } else {
                    src = 1;
                    dst = 0;
                }

                len[src] = attrNode[src].getLength();

                for (int j = 0; j < len[src]; j++) {
                    Node srcAttr = attrNode[src].item(j);
                    String srcAttrName = srcAttr.getNodeName();

                    // copy the supported attrs
                    if (cc_ == null ||
                        cc_.canConvertAttribute(nodeName, srcAttrName)) {

                        // check whether the attribute exist in dst node
                        Node dstAttr = attrNode[dst].getNamedItem(srcAttrName);

                        if (dstAttr == null)  {
                            Debug.log(Debug.INFO,
                                      "[NodeIterator] Attr not exist in dst - "
                                      + srcAttrName);
                            break attrCheck;
                        }

                        // then compare the attribute values
                        if (!srcAttr.getNodeValue().equals(
                             dstAttr.getNodeValue())) {
                            Debug.log(Debug.INFO,
                                      "[NodeIterator] Attr diff src: " +
                                      srcAttr.getNodeValue() + " dst: "+
                                      dstAttr.getNodeValue());
                            break attrCheck;
                        }
                    } // end if cc_ loop
                } // end for j loop
            } // end for i loop

            // the whole checking is done smoothly and all attributes are equal
            equal = true;
        }

        return equal;
    }

    /**
     * Check whether a {@code Node} is supported.
     *
     * <p>This method can be intentionally overridden by any class that extends
     * from {@code NodeIterator} so that it can specify which {@code Node} to
     * support.</p>
     *
     * @param   node  {@code Node} to check.
     *
     * @return  {@code true} if <code>Node</code> is supported, {@code false}
     *          otherwise.
     */
    protected abstract boolean nodeSupported(Node node);

    // doing a depth first search for the tree and mark all supported nodes
    private void markTree(Node node) {

        // if this is a supported node, then we add it to our cache table
        if (nodeSupported(node)) {
            nodeList.add(node);
        } else {
        // or we go through all children nodes recursively
        // (can be optimized in future)
            String nodeName = node.getNodeName();
            if ( cc_ == null || cc_.canConvertTag(nodeName)) {
                NodeList auxNodeList = node.getChildNodes();
                int nodeListLength = auxNodeList.getLength();
                for (int i = 0; i < nodeListLength; i++) {
                    markTree(auxNodeList.item(i));
                }
            }
            else {
                Debug.log(Debug.INFO, " [NodeIterator::markTree] Skipping node "
                                      + nodeName);
            }
        }
    }
}