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
/
FormDefinition.java
215 lines (193 loc) 路 6.96 KB
/
FormDefinition.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
/*
* 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.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.instance.InstanceInitializationFactory;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.xform.parse.XFormParser;
import org.opendatakit.briefcase.model.BriefcaseFormDefinition;
import org.opendatakit.briefcase.model.ParsingException;
import org.opendatakit.briefcase.reused.BriefcaseException;
/**
* This class holds all the relevant information about the form being exported.
*/
public class FormDefinition {
private final String id;
private final String name;
private final Path formFile;
private final boolean isEncrypted;
private final Model model;
private final List<Model> repeatFields;
FormDefinition(String id, Path formFile, String name, boolean isEncrypted, Model model) {
this.id = id;
this.name = name;
this.formFile = formFile;
this.isEncrypted = isEncrypted;
this.model = model;
this.repeatFields = model.getRepeatableFields();
}
/**
* Factory that takes the {@link Path} to a form's definition XML file, parses it, and
* returns a new {@link FormDefinition}.
*
* @throws BriefcaseException if the given {@link Path} doesn't exist
* @throws ParsingException if there is any problem while parsing the file
*/
static FormDefinition from(Path formFile) {
if (!Files.exists(formFile))
throw new BriefcaseException("No form file found");
Path revised = formFile.getParent().resolve(formFile.getFileName() + ".revised");
try (InputStream in = Files.newInputStream(Files.exists(revised) ? revised : formFile);
InputStreamReader isr = new InputStreamReader(in, UTF_8);
BufferedReader br = new BufferedReader(isr)) {
FormDef formDef = new XFormParser(XFormParser.getXMLDocument(br)).parse();
boolean isEncrypted = Optional.ofNullable(formDef.getSubmissionProfile())
.flatMap(sp -> Optional.ofNullable(sp.getAttribute("base64RsaPublicKey")))
.filter(s -> !s.isEmpty())
.isPresent();
return new FormDefinition(
parseFormId(formDef.getMainInstance().getRoot()),
formFile,
formDef.getName(),
isEncrypted,
new Model(formDef.getMainInstance().getRoot(), getFormControls(formDef))
);
} catch (IOException e) {
throw new ParsingException(e);
}
}
/**
* Factory that reads all necessary info from a {@link BriefcaseFormDefinition} to create
* a new {@link FormDefinition} instance.
*/
public static FormDefinition from(BriefcaseFormDefinition briefcaseFormDefinition) {
return new FormDefinition(
briefcaseFormDefinition.getFormId(),
briefcaseFormDefinition.getFormDefinitionFile().toPath(),
briefcaseFormDefinition.getFormName(),
briefcaseFormDefinition.isFileEncryptedForm(),
// TODO Improve getting the FormDef out of the BriefcaseFormDefinition
new Model(briefcaseFormDefinition.getSubmissionElement(), getFormControls(briefcaseFormDefinition.formDefn.rootJavaRosaFormDef))
);
}
private static Map<String, QuestionDef> getFormControls(FormDef formDef) {
return formDef.getChildren()
.stream()
.flatMap(FormDefinition::flatten)
.filter(e -> e instanceof QuestionDef)
.map(e -> {
QuestionDef control = (QuestionDef) e;
if (control.getDynamicChoices() != null) {
formDef.initialize(false, new InstanceInitializationFactory());
formDef.populateDynamicChoices(control.getDynamicChoices(), (TreeReference) control.getBind().getReference());
}
return control;
})
.collect(toMap(FormDefinition::controlFqn, e -> e));
}
private static String controlFqn(QuestionDef e) {
IDataReference bind = e.getBind();
TreeReference reference = (TreeReference) bind.getReference();
List<String> names = new ArrayList<>();
for (int i = 0; i < reference.size(); i++) {
names.add(reference.getName(i));
}
return names
.subList(1, names.size())
.stream()
.collect(joining("-"));
}
private static Stream<IFormElement> flatten(IFormElement e) {
Stream<IFormElement> e1 = Stream.of(e);
List<IFormElement> children = childrenOf(e);
Stream<IFormElement> b = children.stream()
.flatMap(e2 -> childrenOf(e2).size() == 0 ? Stream.of(e2) : flatten(e2));
return Stream.concat(e1, b);
}
private static List<IFormElement> childrenOf(IFormElement e) {
return Optional.ofNullable(e.getChildren()).orElse(Collections.emptyList());
}
private static String parseFormId(TreeElement root) {
for (int attrIndex = 0; attrIndex < root.getAttributeCount(); attrIndex++) {
String name = root.getAttributeName(attrIndex);
if (name.equals("id"))
return root.getAttributeValue(attrIndex);
}
throw new BriefcaseException("No form ID found");
}
/**
* Returns the {@link Path} to the directory where the form's definition XMl
* file is located.
*/
Path getFormDir() {
return formFile.getParent();
}
/**
* Returns the form's name
*/
String getFormName() {
return name;
}
/**
* Returns true if the form is encrypted, false otherwise.
*/
boolean isFileEncryptedForm() {
return isEncrypted;
}
/**
* Returns the form's model
*/
Model getModel() {
return model;
}
/**
* Returns the form's ID
*/
public String getFormId() {
return id;
}
/**
* Returns the list of repeat group fields
*/
List<Model> getRepeatableFields() {
return repeatFields;
}
/**
* Returns true if the form definition includes repeat groups, false otherwise.
*/
boolean hasRepeatableFields() {
return !repeatFields.isEmpty();
}
}