This repository has been archived by the owner on Apr 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 156
/
XmlElement.java
280 lines (249 loc) 路 9.1 KB
/
XmlElement.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
/*
* Copyright (C) 2018 Nafundi
*
* 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
*
* http://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.opendatakit.briefcase.export;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static org.javarosa.xform.parse.XFormParser.getXMLText;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.opendatakit.briefcase.reused.BriefcaseException;
/**
* This class represents an Element in a Form's submission xml document.
* It can hold the root level submission or any of its fields.
*/
public class XmlElement {
private final Element element;
XmlElement(Element element) {
this.element = element;
}
/**
* Factory of {@link XmlElement} instances that takes a {@link Document}
* and extracts its root element {@link Element} instance.
*
* @param document {@link Document} instance
* @return a new {@link XmlElement} instance
*/
static XmlElement of(Document document) {
return new XmlElement(document.getRootElement());
}
/**
* Builds and returns this {@link XmlElement} instance's parent's local ID.
* This ID is used to cross-reference values in different exported files.
*/
String getParentLocalId(Model field, String instanceId) {
return isFirstLevelGroup() ? instanceId : getParent().getCurrentLocalId(field.getParent(), instanceId);
}
/**
* Builds and returns this {@link XmlElement} instance's current local ID.
* This ID is used to cross-reference values in different exported files.
*/
String getCurrentLocalId(Model field, String instanceId) {
String prefix = isFirstLevelGroup() ? instanceId : getParent().getCurrentLocalId(field.getParent(), instanceId);
return field.isRepeatable()
? prefix + "/" + getName() + "[" + getPlaceAmongSameTagSiblings() + "]"
: prefix;
}
/**
* Builds and returns this {@link XmlElement} instance's group local ID.
* This ID is used to cross-reference values in different exported files.
*/
String getGroupLocalId(Model field, String instanceId) {
String prefix = isFirstLevelGroup() ? instanceId : getParent().getCurrentLocalId(field.getParent(), instanceId);
return prefix + "/" + getName();
}
/**
* Builds and returns a {@link Map} index with all this {@link XmlElement} instance's
* descentants, grouping them with their FQN.
*
* @return the {@link Map} index of all this {@link XmlElement} instance's descendants, grouped by FQN
* @see XmlElement#fqn()
*/
Map<String, List<XmlElement>> getChildrenIndex() {
return flatten().collect(groupingBy(XmlElement::fqn));
}
/**
* Searches an element with a given name among this {@link XmlElement} instance's
* descendants and returns it.
*
* @param name {@link String} to be searched
* @return The corresponding {@link XmlElement}, wrapped inside an {@link Optional} instance,
* or {@link Optional#empty()} if no element with the given name is found.
*/
Optional<XmlElement> findElement(String name) {
return flatten().filter(e -> e.hasName(name)).findFirst();
}
/**
* Compiles and returns the list of elements following a given list of names to follow.
* <p>
* If the list of names contains only a name, the list will contain the children of some child
* element of this instance with the given name.
* <p>
* If the list of names contains more than one names, the list will be obtained by calling
* recursively to this method while traversing this instance's descendants following the given list
* of names.
*
* @param namesArray array of {@link String} names to follow
* @return The corresponding {@link List} of children elements, or an empty list if any
* descendant is not found.
*/
List<XmlElement> findElements(String... namesArray) {
if (namesArray.length == 1)
return childrenOf().stream().filter(e -> e.getName().equalsIgnoreCase(namesArray[0])).collect(Collectors.toList());
// Shift the first element on array
List<String> names = Arrays.asList(namesArray);
return findElement(names.get(0))
.map(e -> e.findElements(names.subList(1, names.size()).toArray(new String[]{})))
.orElse(Collections.emptyList());
}
/**
* Returns the value inside this element.
* <p>
* If no value is found, this method will throw an exception.
*
* @return the {@link String} value of this element
*/
String getValue() {
return maybeValue().orElseThrow(() -> new BriefcaseException("No value present on element " + element.getName()));
}
/**
* Returns the value inside this element.
*
* @return the {@link String} value of this element wrapped inside an {@link Optional} instance,
* or an {@link Optional#empty()} if no value is found
*/
Optional<String> maybeValue() {
return Optional.ofNullable(getXMLText(element, true))
.filter(s -> !s.isEmpty());
}
/**
* Returns the value of an attribute of this element.
*
* @param attribute the {@link String} name of the attribute to get the value from
* @return the {@link String} value of the given attribute wrapped inside an {@link Optional} instance,
* or an {@link Optional#empty()} if no value is found
*/
Optional<String> getAttributeValue(String attribute) {
return Optional.ofNullable(element.getAttributeValue(null, attribute)).filter(s -> !s.isEmpty());
}
/**
* Returns the Fully Qualified Name of this {@link XmlElement} instance, which
* is the concatenation of this instance's name and all its ancestors' names.
*
* @return a @{link String} with the FQN of this {@link XmlElement}
* @see XmlElement#fqn(String)
*/
String fqn() {
return fqn("");
}
/**
* Returns the Fully Qualified Name of this {@link XmlElement} instance, having
* prefixed a given base name to it.
*
* @param prefix the {@link String} base prefix
* @return a {@link String} with the prefixed FQN of this {@link XmlElement}
*/
private String fqn(String prefix) {
String newBase = prefix.isEmpty() ? element.getName() : element.getName() + "-" + prefix;
XmlElement parent = getParent();
if (!parent.isFirstLevelNode())
return parent.fqn(newBase);
return newBase;
}
/**
* Returns this element's name, which corresponds to the tag
* name in the form's submission's xml document
*
* @return the {@link String} name of this element
*/
String getName() {
return element.getName();
}
/**
* Returns whether this element holds a value or not.
*
* @return true if this element holds a value. False otherwise.
*/
boolean hasValue() {
return maybeValue().isPresent();
}
private XmlElement getParent() {
return new XmlElement((Element) element.getParent());
}
private Stream<XmlElement> flatten() {
return childrenOf().stream()
.flatMap(e -> e.size() == 0
? Stream.of(e)
: Stream.concat(Stream.of(e), e.flatten()));
}
private List<XmlElement> childrenOf() {
List<XmlElement> children = new ArrayList<>();
for (int i = 0, max = size(); i < max; i++)
if (element.getType(i) == Node.ELEMENT)
children.add(new XmlElement(element.getElement(i)));
return children;
}
private boolean hasName(String name) {
return element.getName().equalsIgnoreCase(name);
}
private boolean isFirstLevelGroup() {
return getParent().isFirstLevelNode();
}
private int size() {
return element.getChildCount();
}
private List<XmlElement> siblings() {
return getParent().childrenOf();
}
private int getPlaceAmongSameTagSiblings() {
List<XmlElement> sameTagSiblings = siblings().stream()
.filter(e -> e.hasName(element.getName()))
.collect(toList());
for (int index = 0; index < sameTagSiblings.size(); index++)
if (sameTagSiblings.get(index).equals(this))
return index + 1;
throw new BriefcaseException("Element not found");
}
private boolean isFirstLevelNode() {
return element.getParent() instanceof Document;
}
@Override
public String toString() {
return "<" + element.getName() + ">";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
XmlElement that = (XmlElement) o;
return Objects.equals(element, that.element);
}
@Override
public int hashCode() {
return Objects.hash(element);
}
}