Debian Codegraph @

src/main/java/com/github/markusbernhardt/proxy/util/PListParser.java

raw symbols SCIP
1 package com.github.markusbernhardt.proxy.util;
2
3 import java.io.Closeable;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.text.DateFormat;
8 import java.text.ParseException;
9 import java.text.SimpleDateFormat;
10 import java.util.ArrayList;
11 import java.util.Date;
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import java.util.TimeZone;
18
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
22
23 import org.w3c.dom.Document;
24 import org.w3c.dom.Element;
25 import org.w3c.dom.Node;
26 import org.w3c.dom.NodeList;
27 import org.xml.sax.InputSource;
28 import org.xml.sax.SAXException;
29
30 /**
31 * Plist xml handling (serialization and deserialization)
32 * <p>
33 * <em>The xml plist dtd can be found at http://www.apple.com/DTDs/PropertyList-1.0.dtd</em>
34 * <p>
35 * The plist spec handles 8 types of objects: booleans, real, integers, dates,
36 * binary data, strings, arrays (lists) and dictionaries (maps).
37 * <p>
38 * The java Plist lib handles converting xml plists to a nested
39 * {@code Map<String, Object>} that can be trivially read from java. It also
40 * provides a simple way to convert a nested {@code Map<String, Object>} into an
41 * xml plist representation.
42 * <p>
43 * The following mapping will be done when converting from plist to <tt>Map</tt>
44 * :
45 *
46 * <pre>
47 * true/false -&gt; Boolean
48 * real -&gt; Double
49 * integer -&gt; Integer/Long (depends on size, values exceeding an int will be rendered as longs)
50 * data -&gt; byte[]
51 * string -&gt; String
52 * array -&gt; List
53 * dict -&gt; Map
54 * </pre>
55 * <p>
56 * When converting from Map -&gt; plist the conversion is as follows:
57 *
58 * <pre>
59 * Boolean -&gt; true/false
60 * Float/Double -&gt; real
61 * Byte/Short/Integer/Long -&gt; integer
62 * byte[] -&gt; data
63 * List -&gt; array
64 * Map -&gt; dict
65 * </pre>
66 *
67 * @author Markus Bernhardt, Copyright 2016
68 * @author Bernd Rosstauscher, Copyright 2009
69 * @author Christoffer Lerno / Modified by Bernd Rosstauscher
70 */
71 public final class PListParser {
72 /*****************************************************************************
73 * Exception is used for XML parse problems.
74 *
75 * @author Bernd Rosstauscher ([email protected]) Copyright 2009
76 ****************************************************************************/
77
78 public static class XmlParseException extends Exception {
79
80 /** Comment for <code>serialVersionUID</code> */
81 private static final long serialVersionUID = 1L;
82
83 /*************************************************************************
84 * Constructor
85 ************************************************************************/
86
87 public XmlParseException() {
88 super();
89 }
90
91 /*************************************************************************
92 * Constructor
93 *
94 * @param msg
95 * the error message
96 ************************************************************************/
97
98 public XmlParseException(String msg) {
99 super(msg);
100 }
101
102 /*************************************************************************
103 * Constructor
104 *
105 * @param msg
106 * error message
107 * @param e
108 * the cause.
109 ************************************************************************/
110
111 public XmlParseException(String msg, Exception e) {
112 super(msg, e);
113 }
114
115 }
116
117 /*****************************************************************************
118 * Small helper class representing a tree node.
119 *
120 * @author Bernd Rosstauscher ([email protected]) Copyright 2009
121 ****************************************************************************/
122
123 public static class Dict implements Iterable<Map.Entry<String, Object>> {
124 private Map<String, Object> children;
125
126 /*************************************************************************
127 * Constructor
128 ************************************************************************/
129
130 public Dict() {
131 super();
132 this.children = new HashMap<String, Object>();
133 }
134
135 /*************************************************************************
136 * @param key
137 * of the child node.
138 * @return the child node, null if not existing.
139 ************************************************************************/
140
141 public Object get(String key) {
142 return this.children.get(key);
143 }
144
145 /*************************************************************************
146 * iterator
147 *
148 * @see java.lang.Iterable#iterator()
149 ************************************************************************/
150
151 public Iterator<Entry<String, Object>> iterator() {
152 return this.children.entrySet().iterator();
153 }
154
155 /*************************************************************************
156 * @return the size of this dictionary.
157 ************************************************************************/
158
159 public int size() {
160 return this.children.size();
161 }
162
163 /*************************************************************************
164 * Dumps a dictionary with all sub-nodes to the console.
165 ************************************************************************/
166
167 public void dump() {
168 System.out.println("PList");
169 dumpInternal(this, 1);
170 }
171
172 /*************************************************************************
173 * @param plist
174 * @param indent
175 ************************************************************************/
176
177 private static void dumpInternal(Dict plist, int indent) {
178 for (Map.Entry<String, Object> child : plist) {
179 if (child.getValue() instanceof Dict) {
180 for (int j = 0; j < indent; j++) {
181 System.out.print(" ");
182 }
183 System.out.println(child.getKey());
184 dumpInternal((Dict) child.getValue(), indent + 1);
185 } else {
186 for (int j = 0; j < indent; j++) {
187 System.out.print(" ");
188 }
189 System.out.println(child.getKey() + " = " + child.getValue());
190 }
191 }
192
193 }
194
195 /*************************************************************************
196 * Get a node at a given path.
197 *
198 * @param path
199 * a / separated path into the plist hirarchy.
200 * @return the object located at the given path, null if it does not
201 * exist.
202 ************************************************************************/
203
204 public Object getAtPath(String path) {
205 Dict currentNode = this;
206
207 String[] pathSegments = path.trim().split("/");
208 for (int i = 0; i < pathSegments.length; i++) {
209 String segment = pathSegments[i].trim();
210 if (segment.length() == 0) {
211 continue;
212 }
213 Object o = currentNode.get(segment);
214 if (i >= pathSegments.length - 1) {
215 return o;
216 }
217 if (o == null || !(o instanceof Dict)) {
218 break;
219 }
220 currentNode = (Dict) o;
221 }
222 return null;
223 }
224
225 }
226
227 /**
228 * Singleton instance.
229 */
230 private final static PListParser PLIST = new PListParser();
231
232 /**
233 * All element types possible for a plist.
234 */
235 private static enum ElementType {
236 INTEGER, STRING, REAL, DATA, DATE, DICT, ARRAY, TRUE, FALSE,
237 }
238
239 private static final String BASE64_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
240 private static final char[] BASE64_CHARS = BASE64_STRING.toCharArray();
241 private final DateFormat m_dateFormat;
242 private final Map<Class<?>, ElementType> m_simpleTypes;
243
244 /**
245 * Utility method to close a closeable.
246 *
247 * @param closeable
248 * or null.
249 */
250 static void silentlyClose(Closeable closeable) {
251 try {
252 if (closeable != null) {
253 closeable.close();
254 }
255 } catch (IOException e) {
256 // Ignore
257 }
258 }
259
260 /*************************************************************************
261 * Reads from the given input stream and parses it to a Dict.
262 *
263 * @param input
264 * the input stream to read from.
265 * @return the parsed dictionary.
266 * @throws XmlParseException
267 * on parsing error.
268 ************************************************************************/
269
270 private static Dict parse(InputSource input) throws XmlParseException {
271 try {
272 DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
273 documentBuilder.setEntityResolver(new EmptyXMLResolver());
274 Document doc = documentBuilder.parse(input);
275 Element element = doc.getDocumentElement();
276 return PLIST.parse(element);
277 } catch (ParserConfigurationException e) {
278 throw new XmlParseException("Error reading input", e);
279 } catch (SAXException e) {
280 throw new XmlParseException("Error reading input", e);
281 } catch (IOException e) {
282 throw new XmlParseException("Error reading input", e);
283 }
284 }
285
286 /**
287 * Create a nested {@code map<String, Object>} from a plist xml file using
288 * the default mapping.
289 *
290 * @param file
291 * the File containing the the plist xml.
292 * @return the resulting map as read from the plist data.
293 * @throws XmlParseException
294 * if the plist could not be properly parsed.
295 * @throws IOException
296 * if there was an issue reading the plist file.
297 */
298 public static Dict load(File file) throws XmlParseException, IOException {
299 FileInputStream byteStream = new FileInputStream(file);
300 try {
301 InputSource input = new InputSource(byteStream);
302 return parse(input);
303 } finally {
304 silentlyClose(byteStream);
305 }
306 }
307
308 /**
309 * Create a plist handler.
310 */
311 PListParser() {
312 this.m_dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
313 this.m_dateFormat.setTimeZone(TimeZone.getTimeZone("Z"));
314 this.m_simpleTypes = new HashMap<Class<?>, ElementType>();
315 this.m_simpleTypes.put(Integer.class, ElementType.INTEGER);
316 this.m_simpleTypes.put(Byte.class, ElementType.INTEGER);
317 this.m_simpleTypes.put(Short.class, ElementType.INTEGER);
318 this.m_simpleTypes.put(Short.class, ElementType.INTEGER);
319 this.m_simpleTypes.put(Long.class, ElementType.INTEGER);
320 this.m_simpleTypes.put(String.class, ElementType.STRING);
321 this.m_simpleTypes.put(Float.class, ElementType.REAL);
322 this.m_simpleTypes.put(Double.class, ElementType.REAL);
323 this.m_simpleTypes.put(byte[].class, ElementType.DATA);
324 this.m_simpleTypes.put(Boolean.class, ElementType.TRUE);
325 this.m_simpleTypes.put(Date.class, ElementType.DATE);
326 }
327
328 /**
329 * Parses a plist top element into a map dictionary containing all the data
330 * in the plist.
331 *
332 * @param element
333 * the top plist element.
334 * @return the resulting data tree structure.
335 * @throws XmlParseException
336 * if there was any error parsing the xml.
337 */
338 Dict parse(Element element) throws XmlParseException {
339 if (!"plist".equalsIgnoreCase(element.getNodeName())) {
340 throw new XmlParseException("Expected plist top element, was: " + element.getNodeName());
341 }
342
343 Node n = element.getFirstChild();
344 while (n != null && !n.getNodeName().equals("dict")) {
345 n = n.getNextSibling();
346 }
347
348 Dict result = (Dict) parseElement(n);
349 return result;
350 }
351
352 /**
353 * Parses a (non-top) xml element.
354 *
355 * @param element
356 * the element to parse.
357 * @return the resulting object.
358 * @throws XmlParseException
359 * if there was some error in the xml.
360 */
361 private Object parseElement(Node element) throws XmlParseException {
362 try {
363 return parseElementRaw(element);
364 } catch (Exception e) {
365 throw new XmlParseException("Failed to parse: " + element.getNodeName(), e);
366 }
367 }
368
369 /**
370 * Parses a (non-top) xml element.
371 *
372 * @param element
373 * the element to parse.
374 * @return the resulting object.
375 * @throws ParseException
376 * if there was some error parsing the xml.
377 */
378 private Object parseElementRaw(Node element) throws ParseException {
379 ElementType type = ElementType.valueOf(element.getNodeName().toUpperCase());
380 switch (type) {
381 case INTEGER:
382 return parseInt(getValue(element));
383 case REAL:
384 return Double.valueOf(getValue(element));
385 case STRING:
386 return getValue(element);
387 case DATE:
388 return this.m_dateFormat.parse(getValue(element));
389 case DATA:
390 return base64decode(getValue(element));
391 case ARRAY:
392 return parseArray(element.getChildNodes());
393 case TRUE:
394 return Boolean.TRUE;
395 case FALSE:
396 return Boolean.FALSE;
397 case DICT:
398 return parseDict(element.getChildNodes());
399 default:
400 throw new RuntimeException("Unexpected type: " + element.getNodeName());
401 }
402 }
403
404 /*************************************************************************
405 * Parses a string value from a node.
406 *
407 * @param n
408 * the node to extract the value from.
409 * @return the content of the node
410 ************************************************************************/
411
412 private String getValue(Node n) {
413 StringBuilder sb = new StringBuilder();
414 Node c = n.getFirstChild();
415 while (c != null) {
416 if (c.getNodeType() == Node.TEXT_NODE) {
417 sb.append(c.getNodeValue());
418 }
419 c = c.getNextSibling();
420 }
421 return sb.toString();
422 }
423
424 /**
425 * Parses a string into a Long or Integer depending on size.
426 *
427 * @param value
428 * the value as a string.
429 * @return the long value of this string is the value doesn't fit in an
430 * integer, otherwise the int value of the string.
431 */
432 private Number parseInt(String value) {
433 Long l = Long.valueOf(value);
434 if (l.intValue() == l) {
435 return l.intValue();
436 }
437 return l;
438 }
439
440 /**
441 * Parse a list of xml elements as a plist dict.
442 *
443 * @param elements
444 * the elements to parse.
445 * @return the dict deserialized as a map.
446 * @throws ParseException
447 * if there are any problems deserializing the map.
448 */
449 private Dict parseDict(NodeList elements) throws ParseException {
450 Dict dict = new Dict();
451 for (int i = 0; i < elements.getLength(); i++) {
452 Node key = elements.item(i);
453 if (key.getNodeType() != Node.ELEMENT_NODE) {
454 continue;
455 }
456 if (!"key".equals(key.getNodeName())) {
457 throw new ParseException("Expected key but was " + key.getNodeName(), -1);
458 }
459 i++;
460 Node value = elements.item(i);
461 while (value.getNodeType() != Node.ELEMENT_NODE) {
462 i++;
463 value = elements.item(i);
464 }
465 Object o = parseElementRaw(value);
466 String dictName = getValue(key);
467 dict.children.put(dictName, o);
468 }
469 return dict;
470 }
471
472 /**
473 * Parse a list of xml elements as a plist array.
474 *
475 * @param elements
476 * the elements to parse.
477 * @return the array deserialized as a list.
478 * @throws ParseException
479 * if there are any problems deserializing the list.
480 */
481 private List<Object> parseArray(NodeList elements) throws ParseException {
482 ArrayList<Object> list = new ArrayList<Object>();
483 for (int i = 0; i < elements.getLength(); i++) {
484 Node o = elements.item(i);
485 if (o.getNodeType() != Node.ELEMENT_NODE) {
486 continue;
487 }
488 list.add(parseElementRaw(o));
489 }
490 return list;
491 }
492
493 /**
494 * Encode an array of bytes to a string using base64 encoding.
495 *
496 * @param bytes
497 * the bytes to convert.
498 * @return the base64 representation of the bytes.
499 */
500 static String base64encode(byte[] bytes) {
501 StringBuilder builder = new StringBuilder(((bytes.length + 2) / 3) * 4);
502 for (int i = 0; i < bytes.length; i += 3) {
503 byte b0 = bytes[i];
504 byte b1 = i < bytes.length - 1 ? bytes[i + 1] : 0;
505 byte b2 = i < bytes.length - 2 ? bytes[i + 2] : 0;
506 builder.append(BASE64_CHARS[(b0 & 0xFF) >> 2]);
507 builder.append(BASE64_CHARS[((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4)]);
508 builder.append(i < bytes.length - 1 ? BASE64_CHARS[((b1 & 0x0F) << 2) | ((b2 & 0xC0) >> 6)] : "=");
509 builder.append(i < bytes.length - 2 ? BASE64_CHARS[b2 & 0x3F] : "=");
510 }
511 return builder.toString();
512 }
513
514 /**
515 * Converts a string to a byte array assuming the string uses
516 * base64-encoding.
517 *
518 * @param base64
519 * the string to convert.
520 * @return the resulting byte array.
521 */
522 static byte[] base64decode(String base64) {
523 base64 = base64.trim();
524 int endTrim = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
525 int length = (base64.length() / 4) * 3 - endTrim;
526 base64 = base64.replace('=', 'A');
527 byte[] result = new byte[length];
528 int stringLength = base64.length();
529 int index = 0;
530 for (int i = 0; i < stringLength; i += 4) {
531 int i0 = BASE64_STRING.indexOf(base64.charAt(i));
532 int i1 = BASE64_STRING.indexOf(base64.charAt(i + 1));
533 int i2 = BASE64_STRING.indexOf(base64.charAt(i + 2));
534 int i3 = BASE64_STRING.indexOf(base64.charAt(i + 3));
535 byte b0 = (byte) ((i0 << 2) | (i1 >> 4));
536 byte b1 = (byte) ((i1 << 4) | (i2 >> 2));
537 byte b2 = (byte) ((i2 << 6) | i3);
538 result[index++] = b0;
539 if (index < length) {
540 result[index++] = b1;
541 if (index < length) {
542 result[index++] = b2;
543 }
544 }
545 }
546 return result;
547 }
548
549 }