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
|
package net.wotonomy.foundation;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Base64;
import java.util.Base64.Decoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import net.wotonomy.foundation.internal.ReaderInputStream;
import net.wotonomy.foundation.internal.WotonomyException;
/**
* Allows reading/writing property lists in the newer XML format instead of
* the older text-based one.
*
* @author bjculkin
*
*/
public class NSXMLPropertyList {
public static enum ErrorCodes {
INVALID_ROOT("Invalid root element, must be <plist>"),
BAD_PLIST_CHILD_COUNT("<%s> must have one child element", 1),
BAD_PLIST_CHILD("child of <%s> must be a %s"),
UNKNOWN_NODE_TYPE("unknown node type %s", 1),
INVALID_NUM("'%s' is not a valid %s", 2),
BAD_COLL_ITEM("Encountered error while parsing %s", 1),
MISSING_MAP_KEY("encountered a <%s> while parsing a map, expected <key>", 1);
public final String desc;
public final int numFormatArgs;
private ErrorCodes(String desc) {
this(desc, 0);
}
private ErrorCodes(String desc, int numFormatArgs) {
this.desc = desc;
this.numFormatArgs = numFormatArgs;
}
}
public static enum ImmutabilityType {
Immutable, MutableContainers, MutableContainersAndLeaves
}
/**
* Parse a property list from a given string, with the property list
* being immutable.
*
* @param s The string to parse the property list from
* @return The immutable property list
*/
public static NSEither<NSPropertyList, NSError> propertyListFromString(String s) {
return propertyListFromString(s, ImmutabilityType.Immutable);
}
public static NSEither<NSPropertyList, NSError> propertyListFromString(String s, ImmutabilityType immutable) {
StringReader sReader = new StringReader(s);
ReaderInputStream inp = new ReaderInputStream(sReader);
return propertyListFromStream(inp, immutable);
}
public static NSEither<NSPropertyList, NSError> propertyListFromStream(InputStream inp) {
return propertyListFromStream(inp, ImmutabilityType.Immutable);
}
public static NSEither<NSPropertyList, NSError> propertyListFromStream(InputStream inp, ImmutabilityType immutable) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// TODO allow attaching comments to each element
factory.setIgnoringComments(true);
DocumentBuilder fact = factory.newDocumentBuilder();
Document doc = fact.parse(inp);
Element plistRoot = doc.getDocumentElement();
plistRoot.normalize();
if (!plistRoot.getTagName().equals("plist")) {
return createError(ErrorCodes.INVALID_ROOT);
}
NodeList children = plistRoot.getChildNodes();
// TODO this needs to be adjusted to allow comments to exist
if (children.getLength() != 1) {
return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "plist");
}
Node initial = children.item(0);
if (initial.getNodeType() != Node.ELEMENT_NODE) {
return createError(ErrorCodes.BAD_PLIST_CHILD, "plist", "tag");
}
return parsePlistValue(initial, immutable);
} catch (ParserConfigurationException pcex) {
throw new WotonomyException("Failed to create parser", pcex);
} catch (SAXException saxex) {
throw new RuntimeException("Failed to read XML", saxex);
} catch (IOException ioex) {
throw new RuntimeException("Error parsing XML", ioex);
}
}
private static NSEither<NSPropertyList, NSError> parsePlistValue(Node nod, ImmutabilityType immutable) {
String initNodeName = nod.getNodeName();
switch(initNodeName) {
case "array":
return arrayFromNode(nod, immutable);
case "dict":
return dictFromNode(nod, immutable);
case "string": {
NodeList stringKid = nod.getChildNodes();
if (stringKid.getLength() != 1) return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "string");
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) return createError(ErrorCodes.BAD_PLIST_CHILD, "string", "text");
NSPropertyList.String ret = new NSPropertyList.String(text.getNodeValue());
if (immutable != ImmutabilityType.MutableContainersAndLeaves) ret.makeImmutable();
return NSEither.left(ret);
}
case "data": {
Decoder decoder = Base64.getDecoder();
NodeList stringKid = nod.getChildNodes();
if (stringKid.getLength() != 1) return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "data");
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) return createError(ErrorCodes.BAD_PLIST_CHILD, "data", "text");
String raw = text.getNodeValue();
NSData dat = new NSData(decoder.decode(raw));
NSPropertyList.Data ret = new NSPropertyList.Data(dat);
if (immutable != ImmutabilityType.MutableContainersAndLeaves) ret.makeImmutable();
return NSEither.left(ret);
}
case "date": {
// TODO determine what the correct default date format is
// Believe it is ISO_INSTANT from the documentation I have read
DateTimeFormatter dateFmt = DateTimeFormatter.ISO_INSTANT;
NamedNodeMap attributes = nod.getAttributes();
Node formatNode = attributes.getNamedItem("format");
// Because we got it from the attribute map, it has to be
// an attribute
if (formatNode != null) {
Attr formatAttr = (Attr) formatNode;
String format = formatAttr.getValue();
dateFmt = DateTimeFormatter.ofPattern(format);
}
// TODO abstract this chunk into a method
NodeList stringKid = nod.getChildNodes();
if (stringKid.getLength() != 1) return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "date");
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) return createError(ErrorCodes.BAD_PLIST_CHILD, "date", "text");
String val = text.getNodeValue();
TemporalAccessor tempDate = dateFmt.parse(val);
Instant inst = Instant.from(tempDate);
NSPropertyList.Date ret = new NSPropertyList.Date(new NSDate(inst));
if (immutable != ImmutabilityType.MutableContainersAndLeaves) ret.makeImmutable();
return NSEither.left(ret);
}
case "integer": {
NodeList stringKid = nod.getChildNodes();
if (stringKid.getLength() != 1) return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "integer");
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) return createError(ErrorCodes.BAD_PLIST_CHILD, "integer", "text");
String val = text.getNodeValue();
try {
int ret = Integer.parseInt(val);
NSPropertyList.Integer res = new NSPropertyList.Integer(ret);
if (immutable != ImmutabilityType.MutableContainersAndLeaves) res.makeImmutable();
return NSEither.left(res);
} catch (NumberFormatException nfex) {
return createError(ErrorCodes.INVALID_NUM, val, "integer");
}
}
case "real": {
NodeList stringKid = nod.getChildNodes();
if (stringKid.getLength() != 1) return createError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "real");
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) return createError(ErrorCodes.BAD_PLIST_CHILD, "real", "text");
String val = text.getNodeValue();
try {
double ret = Double.parseDouble(val);
NSPropertyList.Real res = new NSPropertyList.Real(ret);
if (immutable != ImmutabilityType.MutableContainersAndLeaves) res.makeImmutable();
return NSEither.left(res);
} catch (NumberFormatException nfex) {
return createError(ErrorCodes.INVALID_NUM, val, "double");
}
}
case "true": {
NSPropertyList.Bool res = new NSPropertyList.Bool(true);
if (immutable != ImmutabilityType.MutableContainersAndLeaves) res.makeImmutable();
return NSEither.left(res);
}
case "false": {
NSPropertyList.Bool res = new NSPropertyList.Bool(false);
if (immutable != ImmutabilityType.MutableContainersAndLeaves) res.makeImmutable();
return NSEither.left(res);
}
default:
return createError(ErrorCodes.UNKNOWN_NODE_TYPE, initNodeName);
}
}
private static NSEither<NSPropertyList, NSError> dictFromNode(Node nod, ImmutabilityType immutable) {
NodeList lst = nod.getChildNodes();
int numChild = lst.getLength();
boolean hasError = false;
NSDictionary<String, NSPropertyList> retDict = new NSMutableDictionary<>();
NSError retError = createRawError(ErrorCodes.BAD_COLL_ITEM, "dictionary");
for (int i = 0; i < numChild; i++) {
Node kid = lst.item(i);
short typ = kid.getNodeType();
if (typ == Node.COMMENT_NODE || typ == Node.PROCESSING_INSTRUCTION_NODE) continue;
if (typ != Node.ELEMENT_NODE) {
hasError = true;
// Skip over the corresponding value, since we don't have a key for it
i++;
retError.addUnderlyingError(createRawError(ErrorCodes.BAD_PLIST_CHILD, "dict", "tag"));
continue;
}
// First, grab the key, then we can handle the value
if (!kid.getNodeName().equals("key")) {
hasError = true;
// Skip over the corresponding value, since we don't have a key for it
i++;
retError.addUnderlyingError(createRawError(ErrorCodes.MISSING_MAP_KEY, kid.getNodeName()));
continue;
}
NodeList stringKid = kid.getChildNodes();
if (stringKid.getLength() != 1) {
hasError = true;
// Skip over the corresponding value, since we don't have a key for it
i++;
retError.addUnderlyingError(createRawError(ErrorCodes.BAD_PLIST_CHILD_COUNT, "key"));
continue;
}
Node text = stringKid.item(0);
if (text.getNodeType() != Node.TEXT_NODE) {
hasError = true;
// Skip over the corresponding value, since we don't have a key for it
i++;
retError.addUnderlyingError(createRawError(ErrorCodes.BAD_PLIST_CHILD, "key", "text"));
continue;
}
String key = text.getNodeValue();
i++;
kid = lst.item(i);
typ = kid.getNodeType();
if (typ == Node.COMMENT_NODE || typ == Node.PROCESSING_INSTRUCTION_NODE) continue;
if (typ != Node.ELEMENT_NODE) {
hasError = true;
retError.addUnderlyingError(createRawError(ErrorCodes.BAD_PLIST_CHILD, "array", "tag"));
continue;
}
var res = parsePlistValue(kid, immutable);
if (res.isLeft()) {
retDict.put(key, res.forceLeft());
} else {
hasError = true;
retError.addUnderlyingError(res.forceRight());
}
}
if (hasError) {
return NSEither.right(retError);
} else {
NSPropertyList.Dictionary res;
if (immutable == ImmutabilityType.Immutable) {
res = new NSPropertyList.Dictionary(new NSDictionary<>(retDict));
res.makeImmutable();
} else {
res = new NSPropertyList.Dictionary(new NSDictionary<>(retDict));
}
return NSEither.left(res);
}
}
private static NSEither<NSPropertyList, NSError> arrayFromNode(Node nod, ImmutabilityType immutable) {
NodeList lst = nod.getChildNodes();
int numChild = lst.getLength();
boolean hasError = false;
NSArray<NSPropertyList> retList = new NSMutableArray<>();
NSError retError = createRawError(ErrorCodes.BAD_COLL_ITEM, "array");
for (int i = 0; i < numChild; i++) {
Node kid = lst.item(i);
short typ = kid.getNodeType();
if (typ == Node.COMMENT_NODE || typ == Node.PROCESSING_INSTRUCTION_NODE) continue;
if (typ != Node.ELEMENT_NODE) {
hasError = true;
retError.addUnderlyingError(createRawError(ErrorCodes.BAD_PLIST_CHILD, "array", "tag"));
continue;
}
var res = parsePlistValue(kid, immutable);
if (res.isLeft()) {
retList.add(res.forceLeft());
} else {
hasError = true;
retError.addUnderlyingError(res.forceRight());
}
}
if (hasError) {
return NSEither.right(retError);
} else {
NSPropertyList.Array arr;
if (immutable == ImmutabilityType.Immutable) {
arr = new NSPropertyList.Array(new NSArray<>(retList));
arr.makeImmutable();
} else {
arr = new NSPropertyList.Array(retList);
}
return NSEither.left(arr);
}
}
private static NSEither<NSPropertyList, NSError> createError(ErrorCodes errorCode, Object... formatArgs) {
NSError error = createRawError(errorCode, formatArgs);
return NSEither.right(error);
}
private static NSError createRawError(ErrorCodes errorCode, Object... formatArgs) {
if (formatArgs.length != errorCode.numFormatArgs) {
String fmt = "Incorrect number of format args for error code %s; got %d, expected %d";
String msg = String.format(fmt, errorCode.name(), formatArgs.length, errorCode.numFormatArgs);
throw new WotonomyException(msg);
}
NSError error = new NSError(NSError.NSWotonomyDomain, errorCode.ordinal());
error.setDescription(String.format(errorCode.desc, formatArgs));
return error;
}
}
|