-
Notifications
You must be signed in to change notification settings - Fork 107
/
TreeReference.java
714 lines (618 loc) · 23.6 KB
/
TreeReference.java
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/*
* Copyright (C) 2009 JavaRosa
*
* Licensed 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.javarosa.core.model.instance;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.javarosa.core.util.DataUtil;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.expr.XPathExpression;
public class TreeReference implements Externalizable, Serializable {
/**
* @deprecated replaced by {@link #DEFAULT_MULTIPLICITY}
*/
@Deprecated
public static final int DEFAULT_MUTLIPLICITY = 0;
/**
* Multiplicity demarcates the position of a given element with respect to other elements
* of the same name.
* <p>
* Since users usually want to select the first instance from the nodeset
* returned from a reference query, let the default multiplicity be selecting the first node.
*/
public static final int DEFAULT_MULTIPLICITY = 0;
/**
* Refers to all instances of an element, e.g. /data/b[-1] refers to b[0] and b[1]
*/
public static final int INDEX_UNBOUND = -1;
/**
* 'repeats' (sections of a form that can multiply themselves) are populated with a
* template that never exists in the form (IE: If you serialized the form to XML
* it wouldn't be there) but provides the xml structure that should be replicated
* when a 'repeat' is added
*/
public static final int INDEX_TEMPLATE = -2;
/**
* Multiplicity flag for an attribute
*/
public static final int INDEX_ATTRIBUTE = -4;//multiplicity flag for an attribute
public static final int INDEX_REPEAT_JUNCTURE = -10;
//TODO: Roll these into RefLevel? Or more likely, take absolute
//ref out of refLevel
public static final int CONTEXT_ABSOLUTE = 0;
public static final int CONTEXT_INHERITED = 1;
public static final int CONTEXT_ORIGINAL = 2;
public static final int CONTEXT_INSTANCE = 4;
public static final int REF_ABSOLUTE = -1;
public static final String NAME_WILDCARD = "*";
/**
* -1 = absolute, 0 = context node, 1 = parent, 2 = grandparent ...
*/
private int refLevel;
private int contextType;
private String instanceName = null;
private List<TreeReferenceLevel> data = null;
public static TreeReference rootRef() {
TreeReference root = new TreeReference();
root.refLevel = REF_ABSOLUTE;
root.contextType = CONTEXT_ABSOLUTE;
return root;
}
public static TreeReference selfRef() {
TreeReference self = new TreeReference();
self.refLevel = 0;
self.contextType = CONTEXT_INHERITED;
return self;
}
public TreeReference() {
instanceName = null; // null means the default instance
refLevel = 0;
contextType = CONTEXT_ABSOLUTE;
data = new ArrayList<TreeReferenceLevel>(0);
}
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
public int getMultiplicity(int index) {
return data.get(index).getMultiplicity();
}
public String getName(int index) {
return data.get(index).getName();
}
public int getMultLast() {
return data.get(data.size() - 1).getMultiplicity();
}
public String getNameLast() {
return data.get(data.size() - 1).getName();
}
public void setMultiplicity(int i, int mult) {
data.set(i, data.get(i).setMultiplicity(mult));
}
public int size() {
return data.size();
}
private void add(TreeReferenceLevel level) {
data.add(level);
}
public void add(String name, int mult) {
add(new TreeReferenceLevel(name, mult).intern());
}
public void addPredicate(int key, List<XPathExpression> xpe) {
data.set(key, data.get(key).setPredicates(xpe));
}
public List<XPathExpression> getPredicate(int key) {
return data.get(key).getPredicates();
}
public int getRefLevel() {
return refLevel;
}
public void setRefLevel(int refLevel) {
this.refLevel = refLevel;
}
public void incrementRefLevel() {
if (!isAbsolute()) {
refLevel++;
}
}
public boolean isAbsolute() {
return refLevel == REF_ABSOLUTE;
}
//return true if this ref contains any unbound multiplicities... ie, there is ANY chance this ref
//could ambiguously refer to more than one instance node.
public boolean isAmbiguous() {
//ignore level 0, as /data implies /data[0]
for (int i = 1; i < size(); i++) {
if (getMultiplicity(i) == INDEX_UNBOUND) {
return true;
}
}
return false;
}
//return a copy of the ref
@Override
public TreeReference clone() {
TreeReference newRef = new TreeReference();
newRef.setRefLevel(this.refLevel);
for (TreeReferenceLevel l : data) {
newRef.add(l.shallowCopy());
}
//copy instances
newRef.setInstanceName(instanceName);
newRef.setContextType(this.contextType);
return newRef;
}
/*
* chop the lowest level off the ref so that the ref now represents the parent of the original ref
* return true if we successfully got the parent, false if there were no higher levels
*/
public boolean removeLastLevel() {
int size = size();
if (size == 0) {
if (isAbsolute()) {
return false;
} else {
refLevel++;
return true;
}
} else {
data.remove(size - 1);
return true;
}
}
public TreeReference getParentRef() {
//TODO: level
TreeReference ref = this.clone();
if (ref.removeLastLevel()) {
return ref;
} else {
return null;
}
}
/**
* Builds and returns a new reference that is this reference anchored to a passed-in base reference.
* <p>
* Unlike in {@link #anchor(TreeReference)}, the base reference can be relative. This allows anchoring of nodes
* with inherited context such as in {@link org.javarosa.core.model.instance.TreeElement#BuildRef} which
* {@link #anchor(TreeReference) anchor} can't do. However, if this ref has 'parent' steps (..), it can only be
* anchored if the base ref is a relative ref consisting only of other 'parent' steps. For example,
* '../../a'.parent('..') is valid and yields '../../../a'.
*
* @return a new TreeReference that represents this reference anchored to the parent or null if this ref has parent
* steps and the parent ref is not a relative reference consisting only of other 'parent' steps.
**/
public TreeReference parent(TreeReference baseReference) {
if (isAbsolute()) {
return this.clone();
} else {
TreeReference newRef = baseReference.clone();
if (refLevel > 0) {
if (!baseReference.isAbsolute() && baseReference.size() == 0) {
newRef.refLevel += refLevel;
} else {
return null;
}
}
for (TreeReferenceLevel level : data) {
newRef.add(level.shallowCopy());
}
return newRef;
}
}
/**
* Builds and returns a new reference that is this reference anchored to a passed-in base reference.
* <p>
* Unlike in {@link #parent(TreeReference)}, the base reference must be absolute and refer to a singular, existing
* node in the model. For example, this allows '../../d/e/f'.anchor('/a/b/c') -> '/a/d/e/f' which can't be done by
* {@link #parent(TreeReference)}.
* <p>
* NOTE: this function still works even when baseReference contains INDEX_UNBOUND multiplicities. Conditions depend
* on this behavior, even though it's slightly icky.
* <p>
* TODO: Technically we should possibly be modifying context stuff here instead of in the xpath stuff
*
* @return a new TreeReference that represents this reference anchored to the context.
* @throws XPathException if the context reference is not absolute or if there is an attempt to parent past the
* root node (too many '../' levels).
*/
public TreeReference anchor(TreeReference baseReference) throws XPathException {
if (isAbsolute()) {
return this.clone();
} else if (!baseReference.isAbsolute()) {
throw new XPathException(baseReference.toString(true) + " is not an absolute reference");
} else if (refLevel > baseReference.size()) {
throw new XPathException("Attempt to parent past the root node " + this.toString(true));
}
TreeReference newRef = baseReference.clone();
for (int i = 0; i < refLevel; i++) {
newRef.removeLastLevel();
}
for (TreeReferenceLevel level : data) {
newRef.add(level.shallowCopy());
}
return newRef;
}
public TreeReference contextualize(TreeReference contextRef) {
if (!contextRef.isAbsolute()) {
return null;
}
TreeReference newRef = anchor(contextRef);
//apply multiplicities and fill in wildcards as necessary based on the context ref
for (int i = 0; i < contextRef.size() && i < newRef.size(); i++) {
//If the the contextRef can provide a definition for a wildcard (not currently supported by JR), do so
if (TreeReference.NAME_WILDCARD.equals(newRef.getName(i)) && !TreeReference.NAME_WILDCARD.equals(contextRef.getName(i))) {
newRef.data.set(i, newRef.data.get(i).setName(contextRef.getName(i)));
}
if (contextRef.getName(i).equals(newRef.getName(i))) {
if (newRef.getPredicate(i) == null) {
newRef.addPredicate(i, contextRef.getPredicate(i));
}
if (i + refLevel <= newRef.size()) {
newRef.setMultiplicity(i, contextRef.getMultiplicity(i));
}
} else {
break;
}
}
return newRef;
}
public TreeReference relativize(TreeReference parent) {
if (parent.isAncestorOf(this, false)) {
TreeReference relRef = selfRef();
for (int i = parent.size(); i < this.size(); i++) {
relRef.add(this.getName(i), INDEX_UNBOUND);
}
return relRef;
} else {
return null;
}
}
//turn unambiguous ref into a generic ref
public TreeReference genericize() {
TreeReference genericRef = clone();
for (int i = 0; i < genericRef.size(); i++) {
//TODO: It's not super clear whether template refs should get
//genericized or not
genericRef.setMultiplicity(i, INDEX_UNBOUND);
}
return genericRef;
}
/**
* @deprecated replaced by {@link #isAncestorOf(TreeReference, boolean)}
*/
@Deprecated
public boolean isParentOf(TreeReference child, boolean properParent) {
return isAncestorOf(child, properParent);
}
//returns true if 'this' is parent of 'child'
//return true if 'this' equals 'child' only if properParent is false
public boolean isAncestorOf(TreeReference child, boolean properParent) {
//Instances and context types;
if (refLevel != child.refLevel)
return false;
if (child.size() < size() + (properParent ? 1 : 0))
return false;
for (int i = 0; i < size(); i++) {
if (!this.getName(i).equals(child.getName(i))) {
return false;
}
int parMult = this.getMultiplicity(i);
int childMult = child.getMultiplicity(i);
if (parMult != INDEX_UNBOUND && parMult != childMult && !(i == 0 && parMult == 0 && childMult == INDEX_UNBOUND)) {
return false;
}
}
return true;
}
/**
* clone and extend a reference by one level
*/
public TreeReference extendRef(String name, int mult) {
//TODO: Shouldn't work for this if this is an attribute ref;
TreeReference childRef = this.clone();
childRef.add(name, mult);
return childRef;
}
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof TreeReference) {
TreeReference ref = (TreeReference) o;
if (this.refLevel == ref.refLevel && this.size() == ref.size()) {
for (int i = 0; i < this.size(); i++) {
String nameA = this.getName(i);
String nameB = ref.getName(i);
int multA = this.getMultiplicity(i);
int multB = ref.getMultiplicity(i);
List<XPathExpression> predA = this.getPredicate(i);
List<XPathExpression> predB = ref.getPredicate(i);
if (!nameA.equals(nameB)) {
return false;
} else if (multA != multB) {
if (i == 0 && (multA == 0 || multA == INDEX_UNBOUND) && (multB == 0 || multB == INDEX_UNBOUND)) {
// /data and /data[0] are functionally the same
} else {
return false;
}
} else if (predA != null && predB != null) {
if (predA.size() != predB.size()) {
return false;
}
for (int j = 0; j < predA.size(); ++j) {
if (!predA.get(j).equals(predB.get(j))) {
return false;
}
}
} else if ((predA == null && predB != null) || (predA != null && predB == null)) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
}
public int hashCode() {
int hash = (Integer.valueOf(refLevel)).hashCode();
for (int i = 0; i < size(); i++) {
//NOTE(ctsims): It looks like this is only using Integer to
//get the hashcode method, but that method
//is just returning the int value, I think, so
//this should potentially just be replaced by
//an int.
Integer mult = DataUtil.integer(getMultiplicity(i));
if (i == 0 && mult.intValue() == INDEX_UNBOUND)
mult = DataUtil.integer(0);
hash ^= getName(i).hashCode();
hash ^= mult.hashCode();
List<XPathExpression> predicates = this.getPredicate(i);
if (predicates == null) {
continue;
}
int val = 0;
for (XPathExpression xpe : predicates) {
hash ^= val;
hash ^= xpe.hashCode();
++val;
}
}
return hash;
}
public String toString() {
return toString(true);
}
public String toString(boolean includePredicates) {
return toString(includePredicates, false);
}
public String toString(boolean includePredicates, boolean zeroIndexMult) {
StringBuilder sb = new StringBuilder();
if (instanceName != null) {
sb.append("instance(" + instanceName + ")");
} else if (contextType == CONTEXT_ORIGINAL) {
sb.append("current()");
} else if (contextType == CONTEXT_INHERITED) {
sb.append("inherited()");
}
if (isAbsolute()) {
sb.append("/");
} else {
for (int i = 0; i < refLevel; i++)
sb.append("../");
}
for (int i = 0; i < size(); i++) {
String name = getName(i);
int mult = getMultiplicity(i);
if (mult == INDEX_ATTRIBUTE) {
sb.append("@");
}
sb.append(name);
if (includePredicates) {
switch (mult) {
case INDEX_UNBOUND:
break;
case INDEX_TEMPLATE:
sb.append("[@template]");
break;
case INDEX_REPEAT_JUNCTURE:
sb.append("[@juncture]");
break;
default:
if ((i > 0 || mult != 0) && mult != -4) {
sb.append("[").append(mult + (zeroIndexMult ? 0 : 1)).append("]");
}
break;
}
}
if (i < size() - 1)
sb.append("/");
}
return sb.toString();
}
//For debugging purposes only.
public String toShortString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
int mult = getMultiplicity(i);
switch (mult) {
case INDEX_UNBOUND:
break;
case INDEX_TEMPLATE:
sb.append("[@template]");
break;
case INDEX_REPEAT_JUNCTURE:
sb.append("[@juncture]");
break;
default:
if ((i > 0 || mult != 0) && mult != -4) {
if (sb.length() > 0) {
sb.append("_");
}
sb.append(mult + 1);
}
break;
}
}
return getNameLast() + " [" + sb.toString() + "]";
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf)
throws IOException, DeserializationException {
refLevel = ExtUtil.readInt(in);
instanceName = (String) ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
contextType = ExtUtil.readInt(in);
int size = ExtUtil.readInt(in);
for (int i = 0; i < size; ++i) {
TreeReferenceLevel level = (TreeReferenceLevel) ExtUtil.read(in, TreeReferenceLevel.class);
this.add(level.intern());
}
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeNumeric(out, refLevel);
ExtUtil.write(out, new ExtWrapNullable(instanceName));
ExtUtil.writeNumeric(out, contextType);
ExtUtil.writeNumeric(out, size());
for (TreeReferenceLevel l : data) {
ExtUtil.write(out, l);
}
}
/**
* Intersect this tree reference with another, returning a new tree reference
* which contains all of the common elements, starting with the root element.
* <p>
* Note that relative references by their nature can't share steps, so intersecting
* any (or by any) relative ref will result in the root ref. Additionally, if the
* two references don't share any steps, the intersection will consist of the root
* reference.
*
* @param b The tree reference to intersect
* @return The tree reference containing the common basis of this ref and b
*/
public TreeReference intersect(TreeReference b) {
if (!this.isAbsolute() || !b.isAbsolute()) {
return TreeReference.rootRef();
}
if (this.equals(b)) {
return this;
}
TreeReference a;
//A should always be bigger if one ref is larger than the other
if (this.size() < b.size()) {
a = b.clone();
b = this.clone();
} else {
a = this.clone();
b = b.clone();
}
//Now, trim the refs to the same length.
int diff = a.size() - b.size();
for (int i = 0; i < diff; ++i) {
a.removeLastLevel();
}
int aSize = a.size();
//easy, but requires a lot of re-evaluation.
for (int i = 0; i <= aSize; ++i) {
if (a.equals(b)) {
return a;
} else if (a.size() == 0) {
return TreeReference.rootRef();
} else {
if (!a.removeLastLevel() || !b.removeLastLevel()) {
//I don't think it should be possible for us to get here, so flip if we do
throw new RuntimeException("Dug too deply into TreeReference during intersection");
}
}
}
//The only way to get here is if a's size is -1
throw new RuntimeException("Impossible state");
}
//TODO: This should be in construction
/**
* @deprecated use #setContextType(int) instead
*/
@Deprecated
public void setContext(int contextType) {
setContextType(contextType);
}
public void setContextType(int contextType) {
this.contextType = contextType;
}
/**
* @deprecated use #getContextType() instead
*/
@Deprecated
public int getContext() {
return this.getContextType();
}
public int getContextType() {
return contextType;
}
/**
* Returns the subreference of this reference up to the level specified.
* <p>
* Used to identify the reference context for a predicate at the same level
* <p>
* Must be an absolute reference, otherwise will throw IllegalArgumentException
*/
public TreeReference getSubReference(int level) {
if (!this.isAbsolute()) {
throw new IllegalArgumentException("Cannot subreference a non-absolute ref");
}
//Copy construct
TreeReference ret = new TreeReference();
ret.refLevel = this.refLevel;
ret.contextType = this.contextType;
ret.instanceName = this.instanceName;
ret.data = new ArrayList<TreeReferenceLevel>(level);
for (int i = 0; i <= level; ++i) {
ret.data.add(this.data.get(i));
}
return ret;
}
public boolean hasPredicates() {
for (TreeReferenceLevel level : data) {
if (level.getPredicates() != null) {
return true;
}
}
return false;
}
public TreeReference removePredicates() {
TreeReference predicateless = clone();
for (int i = 0; i < predicateless.data.size(); ++i) {
predicateless.data.set(i, predicateless.data.get(i).setPredicates(null));
}
return predicateless;
}
public TreeReference removePredicates(int i) {
TreeReference predicateless = clone();
predicateless.data.set(i, predicateless.data.get(i).setPredicates(null));
return predicateless;
}
}