-
Notifications
You must be signed in to change notification settings - Fork 28
/
BXMLSerializer.java
1780 lines (1506 loc) · 68.4 KB
/
BXMLSerializer.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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you 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.apache.pivot.beans;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.util.StreamReaderDelegate;
import org.apache.pivot.collections.Dictionary;
import org.apache.pivot.collections.HashMap;
import org.apache.pivot.collections.LinkedList;
import org.apache.pivot.collections.Map;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.json.JSON;
import org.apache.pivot.json.JSONSerializer;
import org.apache.pivot.serialization.BinarySerializer;
import org.apache.pivot.serialization.ByteArraySerializer;
import org.apache.pivot.serialization.CSVSerializer;
import org.apache.pivot.serialization.PropertiesSerializer;
import org.apache.pivot.serialization.SerializationException;
import org.apache.pivot.serialization.Serializer;
import org.apache.pivot.util.ListenerList;
import org.apache.pivot.util.Resources;
import org.apache.pivot.util.Vote;
/**
* Loads an object hierarchy from an XML document.
*/
public class BXMLSerializer implements Serializer<Object>, Resolvable {
private static class Element {
public enum Type {
INSTANCE,
READ_ONLY_PROPERTY,
WRITABLE_PROPERTY,
LISTENER_LIST_PROPERTY,
INCLUDE,
SCRIPT,
DEFINE,
REFERENCE
}
public final Element parent;
public final Type type;
public final Class<?> propertyClass;
public final String name;
public Object value;
public String id = null;
public final HashMap<String, String> properties = new HashMap<String, String>();
public final LinkedList<Attribute> attributes = new LinkedList<Attribute>();
public Element(Element parent, Type type, String name, Class<?> propertyClass, Object value) {
this.parent = parent;
this.type = type;
this.name = name;
this.propertyClass = propertyClass;
this.value = value;
}
}
private static class Attribute {
public final Element element;
public final String name;
public final Class<?> propertyClass;
public Object value;
public Attribute(Element element, String name, Class<?> propertyClass, Object value) {
this.element = element;
this.name = name;
this.propertyClass = propertyClass;
this.value = value;
}
}
private class AttributeInvocationHandler implements InvocationHandler {
private ScriptEngine scriptEngine;
private String event;
private String script;
private static final String ARGUMENTS_KEY = "arguments";
public AttributeInvocationHandler(ScriptEngine scriptEngine, String event, String script) {
this.scriptEngine = scriptEngine;
this.event = event;
this.script = script;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
String methodName = method.getName();
if (methodName.equals(event)) {
try {
SimpleBindings bindings = new SimpleBindings();
bindings.put(ARGUMENTS_KEY, args);
scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
scriptEngine.eval(script);
} catch (ScriptException exception) {
reportException(exception, script);
}
}
// If the function didn't return a value, return the default
Class<?> returnType = method.getReturnType();
if (returnType == Vote.class) {
result = Vote.APPROVE;
} else if (returnType == Boolean.TYPE) {
result = false;
}
return result;
}
}
private static class ElementInvocationHandler implements InvocationHandler {
private ScriptEngine scriptEngine;
public ElementInvocationHandler(ScriptEngine scriptEngine) {
this.scriptEngine = scriptEngine;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
String methodName = method.getName();
Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
if (bindings.containsKey(methodName)) {
Invocable invocable;
try {
invocable = (Invocable)scriptEngine;
} catch (ClassCastException exception) {
throw new SerializationException(exception);
}
result = invocable.invokeFunction(methodName, args);
}
// If the function didn't return a value, return the default
if (result == null) {
Class<?> returnType = method.getReturnType();
if (returnType == Vote.class) {
result = Vote.APPROVE;
} else if (returnType == Boolean.TYPE) {
result = false;
}
}
return result;
}
}
private static class ScriptBindMapping implements NamespaceBinding.BindMapping {
private ScriptEngine scriptEngine;
private String functionName;
public ScriptBindMapping(ScriptEngine scriptEngine, String functionName) {
this.scriptEngine = scriptEngine;
this.functionName = functionName;
}
@Override
public Object evaluate(final Object value) {
Object result = value;
Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
if (bindings.containsKey(functionName)) {
Invocable invocable;
try {
invocable = (Invocable)scriptEngine;
} catch (ClassCastException exception) {
throw new RuntimeException(exception);
}
try {
result = invocable.invokeFunction(functionName, result);
} catch (NoSuchMethodException exception) {
throw new RuntimeException(exception);
} catch (ScriptException exception) {
throw new RuntimeException(exception);
}
} else {
throw new RuntimeException("Mapping function \"" + functionName + "\" is not defined.");
}
return result;
}
}
private XMLInputFactory xmlInputFactory;
private ScriptEngineManager scriptEngineManager;
private Map<String, Object> namespace = new HashMap<String, Object>();
private URL location = null;
private Resources resources = null;
private XMLStreamReader xmlStreamReader = null;
private Element element = null;
private Object root = null;
private String language = null;
private int nextID = 0;
private LinkedList<Attribute> namespaceBindingAttributes = new LinkedList<Attribute>();
private static HashMap<String, String> fileExtensions = new HashMap<String, String>();
private static HashMap<String, Class<? extends Serializer<?>>> mimeTypes =
new HashMap<String, Class<? extends Serializer<?>>>();
public static final char URL_PREFIX = '@';
public static final char RESOURCE_KEY_PREFIX = '%';
public static final char OBJECT_REFERENCE_PREFIX = '$';
public static final char SLASH_PREFIX = '/';
public static final String NAMESPACE_BINDING_PREFIX = OBJECT_REFERENCE_PREFIX + "{";
public static final String NAMESPACE_BINDING_SUFFIX = "}";
public static final String BIND_MAPPING_DELIMITER = ":";
public static final String INTERNAL_ID_PREFIX = "$";
public static final String LANGUAGE_PROCESSING_INSTRUCTION = "language";
public static final String BXML_PREFIX = "bxml";
public static final String BXML_EXTENSION = "bxml";
public static final String ID_ATTRIBUTE = "id";
public static final String INCLUDE_TAG = "include";
public static final String INCLUDE_SRC_ATTRIBUTE = "src";
public static final String INCLUDE_RESOURCES_ATTRIBUTE = "resources";
public static final String INCLUDE_MIME_TYPE_ATTRIBUTE = "mimeType";
public static final String INCLUDE_INLINE_ATTRIBUTE = "inline";
public static final String SCRIPT_TAG = "script";
public static final String SCRIPT_SRC_ATTRIBUTE = "src";
public static final String DEFINE_TAG = "define";
public static final String REFERENCE_TAG = "reference";
public static final String REFERENCE_ID_ATTRIBUTE = "id";
public static final String DEFAULT_LANGUAGE = "javascript";
public static final String MIME_TYPE = "application/bxml";
static {
mimeTypes.put(MIME_TYPE, BXMLSerializer.class);
mimeTypes.put(BinarySerializer.MIME_TYPE, BinarySerializer.class);
mimeTypes.put(ByteArraySerializer.MIME_TYPE, ByteArraySerializer.class);
mimeTypes.put(CSVSerializer.MIME_TYPE, CSVSerializer.class);
mimeTypes.put(JSONSerializer.MIME_TYPE, JSONSerializer.class);
mimeTypes.put(PropertiesSerializer.MIME_TYPE, PropertiesSerializer.class);
fileExtensions.put(BXML_EXTENSION, MIME_TYPE);
fileExtensions.put(CSVSerializer.CSV_EXTENSION, CSVSerializer.MIME_TYPE);
fileExtensions.put(JSONSerializer.JSON_EXTENSION, JSONSerializer.MIME_TYPE);
fileExtensions.put(PropertiesSerializer.PROPERTIES_EXTENSION, PropertiesSerializer.MIME_TYPE);
}
public BXMLSerializer() {
xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
scriptEngineManager = new javax.script.ScriptEngineManager();
scriptEngineManager.setBindings(new Bindings() {
@Override
public Object get(Object key) {
return namespace.get(key.toString());
}
@Override
public Object put(String key, Object value) {
return namespace.put(key, value);
}
@Override
public void putAll(java.util.Map<? extends String, ? extends Object> map) {
for (String key : map.keySet()) {
put(key, map.get(key));
}
}
@Override
public Object remove(Object key) {
return namespace.remove(key.toString());
}
@Override
public void clear() {
namespace.clear();
}
@Override
public boolean containsKey(Object key) {
return namespace.containsKey(key.toString());
}
@Override
public boolean containsValue(Object value) {
boolean contains = false;
for (String key : namespace) {
if (namespace.get(key).equals(value)) {
contains = true;
break;
}
}
return contains;
}
@Override
public boolean isEmpty() {
return namespace.isEmpty();
}
@Override
public java.util.Set<String> keySet() {
java.util.HashSet<String> keySet = new java.util.HashSet<String>();
for (String key : namespace) {
keySet.add(key);
}
return keySet;
}
@Override
public java.util.Set<Entry<String, Object>> entrySet() {
java.util.HashMap<String, Object> hashMap = new java.util.HashMap<String, Object>();
for (String key : namespace) {
hashMap.put(key, namespace.get(key));
}
return hashMap.entrySet();
}
@Override
public int size() {
return namespace.getCount();
}
@Override
public Collection<Object> values() {
java.util.ArrayList<Object> values = new java.util.ArrayList<Object>();
for (String key : namespace) {
values.add(namespace.get(key));
}
return values;
}
});
}
/** DO NOT USE. see https://issues.apache.org/jira/browse/PIVOT-742 */
@Deprecated
public BXMLSerializer(@SuppressWarnings("unused") final ClassLoader classLoader) {
throw new UnsupportedOperationException("https://issues.apache.org/jira/browse/PIVOT-742");
}
/**
* Deserializes an object hierarchy from a BXML resource.
* <p>
* This is the base version of the method. It does not set the "location" or "resources"
* properties. Callers that wish to use this version of the method to load BXML that uses
* location or resource resolution must manually set these properties via a call to
* {@link #setLocation(URL)} or {@link #setResources(Resources)}, respectively, before calling
* this method.
*
* @return
* The deserialized object hierarchy.
*/
@Override
public Object readObject(InputStream inputStream)
throws IOException, SerializationException {
if (inputStream == null) {
throw new IllegalArgumentException("inputStream is null.");
}
root = null;
language = null;
// Parse the XML stream
try {
try {
xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
while (xmlStreamReader.hasNext()) {
int event = xmlStreamReader.next();
switch (event) {
case XMLStreamConstants.PROCESSING_INSTRUCTION: {
processProcessingInstruction();
break;
}
case XMLStreamConstants.CHARACTERS: {
processCharacters();
break;
}
case XMLStreamConstants.START_ELEMENT: {
processStartElement();
break;
}
case XMLStreamConstants.END_ELEMENT: {
processEndElement();
break;
}
default: {
break;
}
}
}
} catch (XMLStreamException exception) {
throw new SerializationException(exception);
}
} catch (IOException exception) {
logException(exception);
throw exception;
} catch (SerializationException exception) {
logException(exception);
throw exception;
} catch (RuntimeException exception) {
logException(exception);
throw exception;
}
xmlStreamReader = null;
// Apply the namespace bindings
for (Attribute attribute : namespaceBindingAttributes) {
Element elementLocal = attribute.element;
String sourcePath = (String)attribute.value;
NamespaceBinding.BindMapping bindMapping;
int i = sourcePath.indexOf(BIND_MAPPING_DELIMITER);
if (i == -1) {
bindMapping = null;
} else {
String bindFunction = sourcePath.substring(0, i);
sourcePath = sourcePath.substring(i + 1);
bindMapping = new ScriptBindMapping(scriptEngineManager.getEngineByName(language), bindFunction);
}
switch (elementLocal.type) {
case INSTANCE:
case INCLUDE: {
// Bind to <element ID>.<attribute name>
if (elementLocal.id == null) {
elementLocal.id = INTERNAL_ID_PREFIX + Integer.toString(nextID++);
namespace.put(elementLocal.id, elementLocal.value);
}
String targetPath = elementLocal.id + "." + attribute.name;
NamespaceBinding namespaceBinding = new NamespaceBinding(namespace, sourcePath, targetPath,
bindMapping);
namespaceBinding.bind();
break;
}
case READ_ONLY_PROPERTY: {
// Bind to <parent element ID>.<element name>.<attribute name>
if (elementLocal.parent.id == null) {
elementLocal.parent.id = INTERNAL_ID_PREFIX + Integer.toString(nextID++);
namespace.put(elementLocal.parent.id, elementLocal.parent.value);
}
String targetPath = elementLocal.parent.id + "." + elementLocal.name + "." + attribute.name;
NamespaceBinding namespaceBinding = new NamespaceBinding(namespace, sourcePath, targetPath,
bindMapping);
namespaceBinding.bind();
break;
}
default: {
break;
}
}
}
namespaceBindingAttributes.clear();
// Bind the root to the namespace
if (root instanceof Bindable) {
Class<?> type = root.getClass();
while (Bindable.class.isAssignableFrom(type)) {
bind(root, type);
type = type.getSuperclass();
}
Bindable bindable = (Bindable)root;
bindable.initialize(namespace, location, resources);
}
return root;
}
/**
* Deserializes an object hierarchy from a BXML resource.
*
* @see #readObject(Class, String, boolean)
*/
public final Object readObject(Class<?> baseType, String resourceName)
throws IOException, SerializationException {
return readObject(baseType, resourceName, false);
}
/**
* Deserializes an object hierarchy from a BXML resource.
* <p>
* The location of the resource is determined by a call to
* {@link Class#getResource(String)} on the given base type, passing the given
* resource name as an argument. If the resources is localized, the base type
* is also used as the base name of the resource bundle.
*
* @param baseType
* The base type.
*
* @param resourceName
* The name of the BXML resource.
*
* @param localize
* If <tt>true</tt>, the deserialized resource will be localized using the resource
* bundle specified by the base type. Otherwise, it will not be localized, and any
* use of the resource resolution operator will result in a serialization exception.
*
* @see #readObject(URL, Resources)
*/
public final Object readObject(Class<?> baseType, String resourceName, boolean localize)
throws IOException, SerializationException {
if (baseType == null) {
throw new IllegalArgumentException("baseType is null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("resourceName is null.");
}
// throw a nice error so the user knows which resource did not load
URL locationLocal = baseType.getResource(resourceName);
if (locationLocal == null) {
throw new IllegalArgumentException("could not find resource \"" + resourceName + "\".");
}
return readObject(locationLocal, localize ? new Resources(baseType.getName()) : null);
}
/**
* Deserializes an object hierarchy from a BXML resource.
* <p>
* This version of the method does not set the "resources" property. Callers
* that wish to use this version of the method to load BXML that uses resource
* resolution must manually set this property via a call to
* {@link #setResources(Resources)} before calling this method.
*
* @param locationArgument
* The location of the BXML resource.
*
* @see #readObject(URL, Resources)
*/
public final Object readObject(URL locationArgument)
throws IOException, SerializationException {
return readObject(locationArgument, null);
}
/**
* Deserializes an object hierarchy from a BXML resource.
*
* @param locationArgument
* The location of the BXML resource.
*
* @param resourcesArgument
* The resources that will be used to localize the deserialized resource.
*
* #see readObject(InputStream)
*/
public final Object readObject(URL locationArgument, Resources resourcesArgument)
throws IOException, SerializationException {
if (locationArgument == null) {
throw new IllegalArgumentException("location is null.");
}
this.location = locationArgument;
this.resources = resourcesArgument;
InputStream inputStream = new BufferedInputStream(locationArgument.openStream());
Object object;
try {
object = readObject(inputStream);
} finally {
inputStream.close();
}
this.location = null;
this.resources = null;
return object;
}
private void processProcessingInstruction() throws SerializationException {
String piTarget = xmlStreamReader.getPITarget();
String piData = xmlStreamReader.getPIData();
if (piTarget.equals(LANGUAGE_PROCESSING_INSTRUCTION)) {
if (language != null) {
throw new SerializationException("language already set.");
}
language = piData;
}
}
@SuppressWarnings("unchecked")
private void processCharacters() throws SerializationException {
if (!xmlStreamReader.isWhiteSpace()) {
// Process the text
String text = xmlStreamReader.getText();
switch (element.type) {
case INSTANCE: {
if (element.value instanceof Sequence<?>) {
Sequence<Object> sequence = (Sequence<Object>)element.value;
try {
Method addMethod = sequence.getClass().getMethod("add", String.class);
addMethod.invoke(sequence, text);
} catch (NoSuchMethodException exception) {
throw new SerializationException("Text content cannot be added to "
+ sequence.getClass().getName() + ": \"" + text + "\"", exception);
} catch (InvocationTargetException exception) {
throw new SerializationException(exception);
} catch (IllegalAccessException exception) {
throw new SerializationException(exception);
}
}
break;
}
case WRITABLE_PROPERTY:
case LISTENER_LIST_PROPERTY:
case SCRIPT: {
element.value = text;
break;
}
default: {
throw new SerializationException("Unexpected characters in "
+ element.type + " element.");
}
}
}
}
private void processStartElement() throws IOException, SerializationException {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Initialize the page language
if (language == null) {
language = DEFAULT_LANGUAGE;
}
// Get element properties
String namespaceURI = xmlStreamReader.getNamespaceURI();
String prefix = xmlStreamReader.getPrefix();
// Some stream readers incorrectly report an empty string as the prefix
// for the default namespace
if (prefix != null
&& prefix.length() == 0) {
prefix = null;
}
String localName = xmlStreamReader.getLocalName();
// Determine the type and value of this element
Element.Type elementType;
String name;
Class<?> propertyClass = null;
Object value = null;
if (prefix != null
&& prefix.equals(BXML_PREFIX)) {
// The element represents a BXML operation
if (element == null) {
throw new SerializationException("Invalid root element.");
}
if (localName.equals(INCLUDE_TAG)) {
elementType = Element.Type.INCLUDE;
} else if (localName.equals(SCRIPT_TAG)) {
elementType = Element.Type.SCRIPT;
} else if (localName.equals(DEFINE_TAG)) {
elementType = Element.Type.DEFINE;
} else if (localName.equals(REFERENCE_TAG)) {
elementType = Element.Type.REFERENCE;
} else {
throw new SerializationException("Invalid element.");
}
name = "<" + prefix + ":" + localName + ">";
} else {
if (Character.isUpperCase(localName.charAt(0))) {
int i = localName.indexOf('.');
if (i != -1
&& Character.isLowerCase(localName.charAt(i + 1))) {
// The element represents an attached property
elementType = Element.Type.WRITABLE_PROPERTY;
name = localName.substring(i + 1);
String propertyClassName = namespaceURI + "." + localName.substring(0, i);
try {
propertyClass = Class.forName(propertyClassName, true, classLoader);
} catch (Throwable exception) {
throw new SerializationException(exception);
}
} else {
// The element represents a typed object
if (namespaceURI == null) {
throw new SerializationException("No XML namespace specified for "
+ localName + " tag.");
}
elementType = Element.Type.INSTANCE;
name = "<" + ((prefix == null) ? "" : prefix + ":") + localName + ">";
String className = namespaceURI + "." + localName.replace('.', '$');
try {
Class<?> type = Class.forName(className, true, classLoader);
value = newTypedObject(type);
} catch (Throwable exception) {
throw new SerializationException(exception);
}
}
} else {
// The element represents a property
if (prefix != null) {
throw new SerializationException("Property elements cannot have a namespace prefix.");
}
if (element.value instanceof Dictionary<?, ?>) {
elementType = Element.Type.WRITABLE_PROPERTY;
} else {
BeanAdapter beanAdapter = new BeanAdapter(element.value);
if (beanAdapter.isReadOnly(localName)) {
Class<?> propertyType = beanAdapter.getType(localName);
if (propertyType == null) {
throw new SerializationException("\"" + localName
+ "\" is not a valid property of element "
+ element.name + ".");
}
if (ListenerList.class.isAssignableFrom(propertyType)) {
elementType = Element.Type.LISTENER_LIST_PROPERTY;
} else {
elementType = Element.Type.READ_ONLY_PROPERTY;
value = beanAdapter.get(localName);
assert (value != null) : "Read-only properties cannot be null.";
}
} else {
elementType = Element.Type.WRITABLE_PROPERTY;
}
}
name = localName;
}
}
// Create the element and process the attributes
element = new Element(element, elementType, name, propertyClass, value);
processAttributes();
if (elementType == Element.Type.INCLUDE) {
// Load the include
if (!element.properties.containsKey(INCLUDE_SRC_ATTRIBUTE)) {
throw new SerializationException(INCLUDE_SRC_ATTRIBUTE
+ " attribute is required for " + BXML_PREFIX + ":" + INCLUDE_TAG
+ " tag.");
}
String src = element.properties.get(INCLUDE_SRC_ATTRIBUTE);
if (src.charAt(0) == OBJECT_REFERENCE_PREFIX) {
src = src.substring(1);
if (src.length() > 0) {
if (!JSON.containsKey(namespace, src)) {
throw new SerializationException("Value \"" + src + "\" is not defined.");
}
String variableValue = JSON.get(namespace, src);
src = variableValue;
}
}
Resources resourcesLocal = this.resources;
if (element.properties.containsKey(INCLUDE_RESOURCES_ATTRIBUTE)) {
resourcesLocal = new Resources(resourcesLocal,
element.properties.get(INCLUDE_RESOURCES_ATTRIBUTE));
}
String mimeType = null;
if (element.properties.containsKey(INCLUDE_MIME_TYPE_ATTRIBUTE)) {
mimeType = element.properties.get(INCLUDE_MIME_TYPE_ATTRIBUTE);
}
if (mimeType == null) {
// Get the file extension
int i = src.lastIndexOf(".");
if (i != -1) {
String extension = src.substring(i + 1);
mimeType = fileExtensions.get(extension);
}
}
if (mimeType == null) {
throw new SerializationException("Cannot determine MIME type of include \""
+ src + "\".");
}
boolean inline = false;
if (element.properties.containsKey(INCLUDE_INLINE_ATTRIBUTE)) {
inline = Boolean.parseBoolean(element.properties.get(INCLUDE_INLINE_ATTRIBUTE));
}
// Determine an appropriate serializer to use for the include
Class<? extends Serializer<?>> serializerClass = mimeTypes.get(mimeType);
if (serializerClass == null) {
throw new SerializationException("No serializer associated with MIME type "
+ mimeType + ".");
}
Serializer<?> serializer;
try {
serializer = newIncludeSerializer(serializerClass);
} catch (InstantiationException exception) {
throw new SerializationException(exception);
} catch (IllegalAccessException exception) {
throw new SerializationException(exception);
}
// Determine location from src attribute
URL locationLocal;
if (src.charAt(0) == SLASH_PREFIX) {
locationLocal = classLoader.getResource(src.substring(1));
} else {
locationLocal = new URL(this.location, src);
}
// Set optional resolution properties
if (serializer instanceof Resolvable) {
Resolvable resolvable = (Resolvable)serializer;
if (inline) {
resolvable.setNamespace(namespace);
}
resolvable.setLocation(locationLocal);
resolvable.setResources(resourcesLocal);
}
// Read the object
InputStream inputStream = new BufferedInputStream(locationLocal.openStream());
try {
element.value = serializer.readObject(inputStream);
} finally {
inputStream.close();
}
} else if (element.type == Element.Type.REFERENCE) {
// Dereference the value
if (!element.properties.containsKey(REFERENCE_ID_ATTRIBUTE)) {
throw new SerializationException(REFERENCE_ID_ATTRIBUTE
+ " attribute is required for " + BXML_PREFIX + ":" + REFERENCE_TAG
+ " tag.");
}
String id = element.properties.get(REFERENCE_ID_ATTRIBUTE);
if (!namespace.containsKey(id)) {
throw new SerializationException("A value with ID \"" + id + "\" does not exist.");
}
element.value = namespace.get(id);
}
// If the element has an ID, add the value to the namespace
if (element.id != null) {
namespace.put(element.id, element.value);
// If the type has an ID property, use it
Class<?> type = element.value.getClass();
IDProperty idProperty = type.getAnnotation(IDProperty.class);
if (idProperty != null) {
BeanAdapter beanAdapter = new BeanAdapter(element.value);
beanAdapter.put(idProperty.value(), element.id);
}
}
}
private void processAttributes() throws SerializationException {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
for (int i = 0, n = xmlStreamReader.getAttributeCount(); i < n; i++) {
String prefix = xmlStreamReader.getAttributePrefix(i);
String localName = xmlStreamReader.getAttributeLocalName(i);
String value = xmlStreamReader.getAttributeValue(i);
if (prefix != null
&& prefix.equals(BXML_PREFIX)) {
// The attribute represents an internal value
if (localName.equals(ID_ATTRIBUTE)) {
if (value.length() == 0
|| value.contains(".")) {
throw new IllegalArgumentException("\"" + value + "\" is not a valid ID value.");
}
if (namespace.containsKey(value)) {
throw new SerializationException("ID " + value + " is already in use.");
}
if (element.type != Element.Type.INSTANCE
&& element.type != Element.Type.INCLUDE) {
throw new SerializationException("An ID cannot be assigned to this element.");
}
element.id = value;
} else {
throw new SerializationException(BXML_PREFIX + ":" + localName
+ " is not a valid attribute.");
}
} else {
boolean property = false;
switch (element.type) {
case INCLUDE: {
property = (localName.equals(INCLUDE_SRC_ATTRIBUTE)
|| localName.equals(INCLUDE_RESOURCES_ATTRIBUTE)
|| localName.equals(INCLUDE_MIME_TYPE_ATTRIBUTE)
|| localName.equals(INCLUDE_INLINE_ATTRIBUTE));
break;
}
case SCRIPT: {
property = (localName.equals(SCRIPT_SRC_ATTRIBUTE));
break;
}
case REFERENCE: {
property = (localName.equals(REFERENCE_ID_ATTRIBUTE));
break;
}
default: {
break;