田源
2025-01-16 404966637eda6881a0f17683c5aacc7c1c34aed8
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
/**
 * $Id: mxObjectCodec.java,v 1.1 2012/11/15 13:26:47 gaudenz Exp $
 * Copyright (c) 2006, Gaudenz Alder
 */
package com.mxgraph.io;
 
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
 
import com.mxgraph.util.mxUtils;
import com.vci.rmip.workflow.client.editor.ui.IProcessProperty;
 
/**
 * Generic codec for Java objects. See below for a detailed description of
 * the encoding/decoding scheme.
 * 
 * Note: Since booleans are numbers in JavaScript, all boolean values are
 * encoded into 1 for true and 0 for false.
 */
@SuppressWarnings("unchecked")
public class mxObjectCodec
{
 
    /**
     * Immutable empty set.
     */
    private static Set<String> EMPTY_SET = new HashSet<String>();
 
    /**
     * Holds the template object associated with this codec.
     */
    protected Object template;
 
    /**
     * Array containing the variable names that should be ignored by the codec.
     */
    protected Set<String> exclude;
 
    /**
     * Array containing the variable names that should be turned into or
     * converted from references. See <mxCodec.getId> and <mxCodec.getObject>.
     */
    protected Set<String> idrefs;
 
    /**
     * Maps from from fieldnames to XML attribute names.
     */
    protected Map<String, String> mapping;
 
    /**
     * Maps from from XML attribute names to fieldnames.
     */
    protected Map<String, String> reverse;
 
    /**
     * Caches accessors for the given method names.
     */
    protected Map<String, Method> accessors;
 
    /**
     * Caches fields for faster access.
     */
    protected Map<Class, Map<String, Field>> fields;
 
    /**
     * Constructs a new codec for the specified template object.
     */
    public mxObjectCodec(Object template)
    {
        this(template, null, null, null);
    }
 
    /**
     * Constructs a new codec for the specified template object. The variables
     * in the optional exclude array are ignored by the codec. Variables in the
     * optional idrefs array are turned into references in the XML. The
     * optional mapping may be used to map from variable names to XML
     * attributes. The argument is created as follows:
     * 
     * @param template Prototypical instance of the object to be encoded/decoded.
     * @param exclude Optional array of fieldnames to be ignored.
     * @param idrefs Optional array of fieldnames to be converted to/from references.
     * @param mapping Optional mapping from field- to attributenames.
     */
    public mxObjectCodec(Object template, String[] exclude, String[] idrefs,
            Map<String, String> mapping)
    {
        this.template = template;
 
        if (exclude != null)
        {
            this.exclude = new HashSet<String>();
 
            for (int i = 0; i < exclude.length; i++)
            {
                this.exclude.add(exclude[i]);
            }
        }
        else
        {
            this.exclude = EMPTY_SET;
        }
 
        if (idrefs != null)
        {
            this.idrefs = new HashSet<String>();
 
            for (int i = 0; i < idrefs.length; i++)
            {
                this.idrefs.add(idrefs[i]);
            }
        }
        else
        {
            this.idrefs = EMPTY_SET;
        }
 
        if (mapping == null)
        {
            mapping = new Hashtable<String, String>();
        }
 
        this.mapping = mapping;
 
        reverse = new Hashtable<String, String>();
        Iterator<Map.Entry<String, String>> it = mapping.entrySet().iterator();
 
        while (it.hasNext())
        {
            Map.Entry<String, String> e = it.next();
            reverse.put(e.getValue(), e.getKey());
        }
    }
 
    /**
     * Returns the name used for the nodenames and lookup of the codec when
     * classes are encoded and nodes are decoded. For classes to work with
     * this the codec registry automatically adds an alias for the classname
     * if that is different than what this returns. The default implementation
     * returns the classname of the template class.
     * 
     * Here is an example on how to use this for renaming mxCell nodes:
     * <code>
     * mxCodecRegistry.register(new mxCellCodec()
     * {
     *   public String getName()
     *   {
     *     return "anotherName";
     *   }
     * });
     * </code>
     */
    public String getName()
    {
        return mxCodecRegistry.getName(getTemplate());
    }
 
    /**
     * Returns the template object associated with this codec.
     * 
     * @return Returns the template object.
     */
    public Object getTemplate()
    {
        return template;
    }
 
    /**
     * Returns a new instance of the template object for representing the given
     * node.
     * 
     * @param node XML node that the object is going to represent.
     * @return Returns a new template instance.
     */
    protected Object cloneTemplate(Node node)
    {
        Object obj = null;
 
        try
        {
            if (template.getClass().isEnum())
            {
                obj = template.getClass().getEnumConstants()[0];
            }
            else
            {
                obj = template.getClass().newInstance();
            }
 
            // Special case: Check if the collection
            // should be a map. This is if the first
            // child has an "as"-attribute. This
            // assumes that all childs will have
            // as attributes in this case. This is
            // required because in JavaScript, the
            // map and array object are the same.
            if (obj instanceof Collection)
            {
                node = node.getFirstChild();
 
                // Skips text nodes
                while (node != null && !(node instanceof Element))
                {
                    node = node.getNextSibling();
                }
 
                if (node != null && node instanceof Element
                        && ((Element) node).hasAttribute("as"))
                {
                    obj = new Hashtable<Object, Object>();
                }
            }
        }
        catch (InstantiationException e)
        {
            // ignore
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            // ignore
            e.printStackTrace();
        }
 
        return obj;
    }
 
    /**
     * Returns true if the given attribute is to be ignored by the codec. This
     * implementation returns true if the given fieldname is in
     * {@link #exclude}.
     * 
     * @param obj Object instance that contains the field.
     * @param attr Fieldname of the field.
     * @param value Value of the field.
     * @param write Boolean indicating if the field is being encoded or
     * decoded. write is true if the field is being encoded, else it is
     * being decoded.
     * @return Returns true if the given attribute should be ignored.
     */
    public boolean isExcluded(Object obj, String attr, Object value,
            boolean write)
    {
        return exclude.contains(attr);
    }
 
    /**
     * Returns true if the given fieldname is to be treated as a textual
     * reference (ID). This implementation returns true if the given fieldname
     * is in {@link #idrefs}.
     * 
     * @param obj Object instance that contains the field.
     * @param attr Fieldname of the field.
     * @param value Value of the field.
     * @param isWrite Boolean indicating if the field is being encoded or
     * decoded. isWrite is true if the field is being encoded, else it is being
     * decoded.
     * @return Returns true if the given attribute should be handled as a
     * reference.
     */
    public boolean isReference(Object obj, String attr, Object value,
            boolean isWrite)
    {
        return idrefs.contains(attr);
    }
 
    /**
     * Encodes the specified object and returns a node representing then given
     * object. Calls beforeEncode after creating the node and afterEncode
     * with the resulting node after processing.
     * 
     * Enc is a reference to the calling encoder. It is used to encode complex
     * objects and create references.
     * 
     * This implementation encodes all variables of an object according to the
     * following rules:
     * 
     * <ul>
     * <li>If the variable name is in {@link #exclude} then it is ignored.</li>
     * <li>If the variable name is in {@link #idrefs} then
     * {@link mxCodec#getId(Object)} is used to replace the object with its ID.
     * </li>
     * <li>The variable name is mapped using {@link #mapping}.</li>
     * <li>If obj is an array and the variable name is numeric (ie. an index) then it
     * is not encoded.</li>
     * <li>If the value is an object, then the codec is used to create a child
     * node with the variable name encoded into the "as" attribute.</li>
     * <li>Else, if {@link com.mxgraph.io.mxCodec#isEncodeDefaults()} is true or
     * the value differs from the template value, then ...
     * <ul>
     * <li>... if obj is not an array, then the value is mapped to an
     * attribute.</li>
     * <li>... else if obj is an array, the value is mapped to an add child
     * with a value attribute or a text child node, if the value is a function.
     * </li>
     * </ul>
     * </li>
     * </ul>
     * 
     * If no ID exists for a variable in {@link #idrefs} or if an object cannot be
     * encoded, a warning is printed to System.err.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object to be encoded.
     * @return Returns the resulting XML node that represents the given object. 
     */
    public Node encode(mxCodec enc, Object obj)
    {
        Node node = enc.document.createElement(getName());
 
        obj = beforeEncode(enc, obj, node);
        encodeObject(enc, obj, node);
 
        return afterEncode(enc, obj, node);
    }
 
    /**
     * Encodes the value of each member in then given obj
     * into the given node using {@link #encodeFields(mxCodec, Object, Node)}
     * and {@link #encodeElements(mxCodec, Object, Node)}.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object to be encoded.
     * @param node XML node that contains the encoded object.
     */
    protected void encodeObject(mxCodec enc, Object obj, Node node)
    {
        mxCodec.setAttribute(node, "id", enc.getId(obj));
        encodeFields(enc, obj, node);
        encodeElements(enc, obj, node);
    }
 
    /**
     * Encodes the declared fields of the given object into the given node.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object whose fields should be encoded.
     * @param node XML node that contains the encoded object.
     */
    protected void encodeFields(mxCodec enc, Object obj, Node node)
    {
        // LATER: Use PropertyDescriptors in Introspector.getBeanInfo(clazz)
        // see http://forum.jgraph.com/questions/1424
        Class<?> type = obj.getClass();
 
        while (type != null)
        {
            Field[] fields = type.getDeclaredFields();
 
            for (int i = 0; i < fields.length; i++)
            {
                Field f = fields[i];
 
                if ((f.getModifiers() & Modifier.TRANSIENT) != Modifier.TRANSIENT)
                {
                    String fieldname = f.getName();
                    Object value = getFieldValue(obj, fieldname);
                    encodeValue(enc, obj, fieldname, value, node);
                }
            }
 
            type = type.getSuperclass();
        }
    }
 
    /**
     * Encodes the child objects of arrays, maps and collections.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object whose child objects should be encoded.
     * @param node XML node that contains the encoded object.
     */
    protected void encodeElements(mxCodec enc, Object obj, Node node)
    {
        if (obj.getClass().isArray())
        {
            Object[] tmp = (Object[]) obj;
 
            for (int i = 0; i < tmp.length; i++)
            {
                encodeValue(enc, obj, null, tmp[i], node);
            }
        }
        else if (obj instanceof Map)
        {
            Iterator<Map.Entry> it = ((Map) obj).entrySet().iterator();
 
            while (it.hasNext())
            {
                Map.Entry e = it.next();
                encodeValue(enc, obj, String.valueOf(e.getKey()), e.getValue(),
                        node);
            }
        }
        else if (obj instanceof Collection)
        {
            Iterator<?> it = ((Collection<?>) obj).iterator();
 
            while (it.hasNext())
            {
                Object value = it.next();
                encodeValue(enc, obj, null, value, node);
            }
        }
    }
 
    /**
     * Converts the given value according to the mappings
     * and id-refs in this codec and uses
     * {@link #writeAttribute(mxCodec, Object, String, Object, Node)}
     * to write the attribute into the given node.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object whose field is going to be encoded.
     * @param fieldname Name if the field to be encoded.
     * @param value Value of the property to be encoded.
     * @param node XML node that contains the encoded object.
     */
    protected void encodeValue(mxCodec enc, Object obj, String fieldname,
            Object value, Node node)
    {
        if (value != null && !isExcluded(obj, fieldname, value, true))
        {
            if (isReference(obj, fieldname, value, true))
            {
                Object tmp = enc.getId(value);
 
                if (tmp == null)
                {
                    System.err.println("mxObjectCodec.encode: No ID for "
                            + getName() + "." + fieldname + "=" + value);
                    return; // exit
                }
 
                value = tmp;
            }
 
            Object defaultValue = getFieldValue(template, fieldname);
 
            if (fieldname == null || enc.isEncodeDefaults()
                    || defaultValue == null || !defaultValue.equals(value))
            {
                writeAttribute(enc, obj, getAttributeName(fieldname), value,
                        node);
            }
        }
    }
 
    /**
     * Returns true if the given object is a primitive value.
     * 
     * @param value Object that should be checked.
     * @return Returns true if the given object is a primitive value.
     */
    protected boolean isPrimitiveValue(Object value)
    {
        return value instanceof String || value instanceof Boolean
                || value instanceof Character || value instanceof Byte
                || value instanceof Short || value instanceof Integer
                || value instanceof Long || value instanceof Float
                || value instanceof Double || value.getClass().isPrimitive();
    }
 
    /**
     * Writes the given value into node using writePrimitiveAttribute
     * or writeComplexAttribute depending on the type of the value.
     */
    protected void writeAttribute(mxCodec enc, Object obj, String attr,
            Object value, Node node)
    {
        value = convertValueToXml(value);
 
        /*if (isPrimitiveValue(value))
        {
            writePrimitiveAttribute(enc, obj, attr, value, node);
        }
        else
        {
            writeComplexAttribute(enc, obj, attr, value, node);
        }*/
        if(value instanceof IProcessProperty){
            mxCodec.setAttribute(node, attr, value.toString());
        }else{
            if (isPrimitiveValue(value))
            {
                writePrimitiveAttribute(enc, obj, attr, value, node);
            }
            else
            {
                writeComplexAttribute(enc, obj, attr, value, node);
            }
        }
    }
 
    /**
     * Writes the given value as an attribute of the given node.
     */
    protected void writePrimitiveAttribute(mxCodec enc, Object obj,
            String attr, Object value, Node node)
    {
        if (attr == null || obj instanceof Map)
        {
            Node child = enc.document.createElement("add");
 
            if (attr != null)
            {
                mxCodec.setAttribute(child, "as", attr);
            }
 
            mxCodec.setAttribute(child, "value", value);
            node.appendChild(child);
        }
        else
        {
            mxCodec.setAttribute(node, attr, value);
        }
    }
 
    /**
     * Writes the given value as a child node of the given node.
     */
    protected void writeComplexAttribute(mxCodec enc, Object obj, String attr,
            Object value, Node node)
    {
        Node child = enc.encode(value);
 
        if (child != null)
        {
            if (attr != null)
            {
                mxCodec.setAttribute(child, "as", attr);
            }
 
            node.appendChild(child);
        }
        else
        {
            System.err.println("mxObjectCodec.encode: No node for " + getName()
                    + "." + attr + ": " + value);
        }
    }
 
    /**
     * Converts true to "1" and false to "0". All other values are ignored.
     */
    protected Object convertValueToXml(Object value)
    {
        if (value instanceof Boolean)
        {
            value = ((Boolean) value).booleanValue() ? "1" : "0";
        }
 
        return value;
    }
 
    /**
     * Converts XML attribute values to object of the given type.
     */
    protected Object convertValueFromXml(Class<?> type, Object value)
    {
        if (value instanceof String)
        {
            String tmp = (String) value;
 
            if (type.equals(boolean.class) || type == Boolean.class)
            {
                if (tmp.equals("1") || tmp.equals("0"))
                {
                    tmp = (tmp.equals("1")) ? "true" : "false";
                }
 
                value = Boolean.valueOf(tmp);
            }
            else if (type.equals(char.class) || type == Character.class)
            {
                value = Character.valueOf(tmp.charAt(0));
            }
            else if (type.equals(byte.class) || type == Byte.class)
            {
                value = Byte.valueOf(tmp);
            }
            else if (type.equals(short.class) || type == Short.class)
            {
                value = Short.valueOf(tmp);
            }
            else if (type.equals(int.class) || type == Integer.class)
            {
                value = Integer.valueOf(tmp);
            }
            else if (type.equals(long.class) || type == Long.class)
            {
                value = Long.valueOf(tmp);
            }
            else if (type.equals(float.class) || type == Float.class)
            {
                value = Float.valueOf(tmp);
            }
            else if (type.equals(double.class) || type == Double.class)
            {
                value = Double.valueOf(tmp);
            }
        }
 
        return value;
    }
 
    /**
     * Returns the XML node attribute name for the given Java field name. That
     * is, it returns the mapping of the field name.
     */
    protected String getAttributeName(String fieldname)
    {
        if (fieldname != null)
        {
            Object mapped = mapping.get(fieldname);
 
            if (mapped != null)
            {
                fieldname = mapped.toString();
            }
        }
 
        return fieldname;
    }
 
    /**
     * Returns the Java field name for the given XML attribute name. That is, it
     * returns the reverse mapping of the attribute name.
     * 
     * @param attributename
     *            The attribute name to be mapped.
     * @return String that represents the mapped field name.
     */
    protected String getFieldName(String attributename)
    {
        if (attributename != null)
        {
            Object mapped = reverse.get(attributename);
 
            if (mapped != null)
            {
                attributename = mapped.toString();
            }
        }
 
        return attributename;
    }
 
    /**
     * Returns the field with the specified name.
     */
    protected Field getField(Object obj, String fieldname)
    {
        Class<?> type = obj.getClass();
 
        // Creates the fields cache
        if (fields == null)
        {
            fields = new HashMap<Class, Map<String, Field>>();
        }
 
        // Creates the fields cache entry for the given type
        Map<String, Field> map = fields.get(type);
 
        if (map == null)
        {
            map = new HashMap<String, Field>();
            fields.put(type, map);
        }
 
        // Tries to get cached field
        Field field = map.get(fieldname);
 
        if (field != null)
        {
            return field;
        }
 
        while (type != null)
        {
            try
            {
                field = type.getDeclaredField(fieldname);
 
                if (field != null)
                {
                    // Adds field to fields cache
                    map.put(fieldname, field);
 
                    return field;
                }
            }
            catch (Exception e)
            {
                // ignore
            }
 
            type = type.getSuperclass();
        }
 
        return null;
    }
 
    /**
     * Returns the accessor (getter, setter) for the specified field.
     */
    protected Method getAccessor(Object obj, Field field, boolean isGetter)
    {
        String name = field.getName();
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
 
        if (!isGetter)
        {
            name = "set" + name;
        }
        else if (boolean.class.isAssignableFrom(field.getType()))
        {
            name = "is" + name;
        }
        else
        {
            name = "get" + name;
        }
 
        Method method = (accessors != null) ? accessors.get(name) : null;
 
        if (method == null)
        {
            try
            {
                if (isGetter)
                {
                    method = getMethod(obj, name, null);
                }
                else
                {
                    method = getMethod(obj, name,
                            new Class[] { field.getType() });
                }
            }
            catch (Exception e1)
            {
                // ignore
            }
 
            // Adds accessor to cache
            if (method != null)
            {
                if (accessors == null)
                {
                    accessors = new Hashtable<String, Method>();
                }
 
                accessors.put(name, method);
            }
        }
 
        return method;
    }
 
    /**
     * Returns the method with the specified signature.
     */
    protected Method getMethod(Object obj, String methodname, Class[] params)
    {
        Class<?> type = obj.getClass();
 
        while (type != null)
        {
            try
            {
                Method method = type.getDeclaredMethod(methodname, params);
 
                if (method != null)
                {
                    return method;
                }
            }
            catch (Exception e)
            {
                // ignore
            }
 
            type = type.getSuperclass();
        }
        return null;
    }
 
    /**
     * Returns the value of the field with the specified name in the specified
     * object instance.
     */
    protected Object getFieldValue(Object obj, String fieldname)
    {
        Object value = null;
 
        if (obj != null && fieldname != null)
        {
            Field field = getField(obj, fieldname);
 
            try
            {
                if (field != null)
                {
                    if (Modifier.isPublic(field.getModifiers()))
                    {
                        value = field.get(obj);
                    }
                    else
                    {
                        value = getFieldValueWithAccessor(obj, field);
                    }
                }
            }
            catch (IllegalAccessException e1)
            {
                value = getFieldValueWithAccessor(obj, field);
            }
            catch (Exception e)
            {
                // ignore
            }
        }
 
        return value;
    }
 
    /**
     * Returns the value of the field using the accessor for the field if one exists.
     */
    protected Object getFieldValueWithAccessor(Object obj, Field field)
    {
        Object value = null;
 
        if (field != null)
        {
            try
            {
                Method method = getAccessor(obj, field, true);
 
                if (method != null)
                {
                    value = method.invoke(obj, (Object[]) null);
                }
            }
            catch (Exception e2)
            {
                // ignore
            }
        }
 
        return value;
    }
 
    /**
     * Sets the value of the field with the specified name
     * in the specified object instance.
     */
    protected void setFieldValue(Object obj, String fieldname, Object value)
    {
        Field field = null;
 
        try
        {
            field = getField(obj, fieldname);
 
            if (field != null)
            {
                if (field.getType() == Boolean.class)
                {
                    value = (value.equals("1") || String.valueOf(value)
                            .equalsIgnoreCase("true")) ? Boolean.TRUE
                            : Boolean.FALSE;
                }
 
                if (Modifier.isPublic(field.getModifiers()))
                {
                    field.set(obj, value);
                }
                else
                {
                    setFieldValueWithAccessor(obj, field, value);
                }
            }
        }
        catch (IllegalAccessException e1)
        {
            setFieldValueWithAccessor(obj, field, value);
        }
        catch (Exception e)
        {
            // ignore
        }
    }
 
    /**
     * Sets the value of the given field using the accessor if one exists.
     */
    protected void setFieldValueWithAccessor(Object obj, Field field,
            Object value)
    {
        if (field != null)
        {
            try
            {
                Method method = getAccessor(obj, field, false);
 
                if (method != null)
                {
                    Class<?> type = method.getParameterTypes()[0];
                    value = convertValueFromXml(type, value);
 
                    // Converts collection to a typed array before setting
                    if (type.isArray() && value instanceof Collection)
                    {
                        Collection<?> coll = (Collection<?>) value;
                        value = coll.toArray((Object[]) Array.newInstance(
                                type.getComponentType(), coll.size()));
                    }
 
                    method.invoke(obj, new Object[] { value });
                }
            }
            catch (Exception e2)
            {
                System.err.println("setFieldValue: " + e2 + " on "
                        + obj.getClass().getSimpleName() + "."
                        + field.getName() + " ("
                        + field.getType().getSimpleName() + ") = " + value
                        + " (" + value.getClass().getSimpleName() + ")");
            }
        }
    }
 
    /**
     * Hook for subclassers to pre-process the object before encoding. This
     * returns the input object. The return value of this function is used in
     * encode to perform the default encoding into the given node.
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object to be encoded.
     * @param node XML node to encode the object into.
     * @return Returns the object to be encoded by the default encoding.
     */
    public Object beforeEncode(mxCodec enc, Object obj, Node node)
    {
        return obj;
    }
 
    /**
     * Hook for subclassers to post-process the node for the given object after
     * encoding and return the post-processed node. This implementation returns
     * the input node. The return value of this method is returned to the
     * encoder from <encode>.
     * 
     * Parameters:
     * 
     * @param enc Codec that controls the encoding process.
     * @param obj Object to be encoded.
     * @param node XML node that represents the default encoding.
     * @return Returns the resulting node of the encoding.
     */
    public Node afterEncode(mxCodec enc, Object obj, Node node)
    {
        return node;
    }
 
    /**
     * Parses the given node into the object or returns a new object
     * representing the given node.
     * 
     * @param dec Codec that controls the encoding process.
     * @param node XML node to be decoded.
     * @return Returns the resulting object that represents the given XML node.
     */
    public Object decode(mxCodec dec, Node node)
    {
        return decode(dec, node, null);
    }
 
    /**
     * Parses the given node into the object or returns a new object
     * representing the given node.
     * 
     * Dec is a reference to the calling decoder. It is used to decode complex
     * objects and resolve references.
     * 
     * If a node has an id attribute then the object cache is checked for the
     * object. If the object is not yet in the cache then it is constructed
     * using the constructor of <template> and cached in <mxCodec.objects>.
     * 
     * This implementation decodes all attributes and childs of a node according
     * to the following rules:
     *  - If the variable name is in <exclude> or if the attribute name is "id"
     * or "as" then it is ignored. - If the variable name is in <idrefs> then
     * <mxCodec.getObject> is used to replace the reference with an object. -
     * The variable name is mapped using a reverse <mapping>. - If the value has
     * a child node, then the codec is used to create a child object with the
     * variable name taken from the "as" attribute. - If the object is an array
     * and the variable name is empty then the value or child object is appended
     * to the array. - If an add child has no value or the object is not an
     * array then the child text content is evaluated using <mxUtils.eval>.
     * 
     * If no object exists for an ID in <idrefs> a warning is issued in
     * System.err.
     * 
     * @param dec Codec that controls the encoding process.
     * @param node XML node to be decoded.
     * @param into Optional object to encode the node into.
     * @return Returns the resulting object that represents the given XML node
     * or the object given to the method as the into parameter.
     */
    public Object decode(mxCodec dec, Node node, Object into)
    {
        Object obj = null;
 
        if (node instanceof Element)
        {
            String id = ((Element) node).getAttribute("id");
            obj = dec.objects.get(id);
 
            if (obj == null)
            {
                obj = into;
 
                if (obj == null)
                {
                    obj = cloneTemplate(node);
                }
 
                if (id != null && id.length() > 0)
                {
                    dec.putObject(id, obj);
                }
            }
 
            node = beforeDecode(dec, node, obj);
            decodeNode(dec, node, obj);
            obj = afterDecode(dec, node, obj);
        }
 
        return obj;
    }
 
    /**
     * Calls decodeAttributes and decodeChildren for the given node.
     */
    protected void decodeNode(mxCodec dec, Node node, Object obj)
    {
        if (node != null)
        {
            decodeAttributes(dec, node, obj);
            decodeChildren(dec, node, obj);
        }
    }
 
    /**
     * Decodes all attributes of the given node using decodeAttribute.
     */
    protected void decodeAttributes(mxCodec dec, Node node, Object obj)
    {
        NamedNodeMap attrs = node.getAttributes();
 
        if (attrs != null)
        {
            for (int i = 0; i < attrs.getLength(); i++)
            {
                Node attr = attrs.item(i);
                decodeAttribute(dec, attr, obj);
            }
        }
    }
 
    /**
     * Reads the given attribute into the specified object.
     */
    protected void decodeAttribute(mxCodec dec, Node attr, Object obj)
    {
        String name = attr.getNodeName();
 
        if (!name.equalsIgnoreCase("as") && !name.equalsIgnoreCase("id"))
        {
            Object value = attr.getNodeValue();
            String fieldname = getFieldName(name);
 
            if (isReference(obj, fieldname, value, false))
            {
                Object tmp = dec.getObject(String.valueOf(value));
 
                if (tmp == null)
                {
                    System.err.println("mxObjectCodec.decode: No object for "
                            + getName() + "." + fieldname + "=" + value);
                    return; // exit
                }
 
                value = tmp;
            }
 
            if (!isExcluded(obj, fieldname, value, false))
            {
                setFieldValue(obj, fieldname, value);
            }
        }
    }
 
    /**
     * Decodec all children of the given node using decodeChild.
     */
    protected void decodeChildren(mxCodec dec, Node node, Object obj)
    {
        Node child = node.getFirstChild();
 
        while (child != null)
        {
            if (child.getNodeType() == Node.ELEMENT_NODE
                    && !processInclude(dec, child, obj))
            {
                decodeChild(dec, child, obj);
            }
 
            child = child.getNextSibling();
        }
    }
 
    /**
     * Reads the specified child into the given object.
     */
    protected void decodeChild(mxCodec dec, Node child, Object obj)
    {
        String fieldname = getFieldName(((Element) child).getAttribute("as"));
 
        if (fieldname == null || !isExcluded(obj, fieldname, child, false))
        {
            Object template = getFieldTemplate(obj, fieldname, child);
            Object value = null;
 
            if (child.getNodeName().equals("add"))
            {
                value = ((Element) child).getAttribute("value");
 
                if (value == null)
                {
                    value = child.getTextContent();
                }
            }
            else
            {
                value = dec.decode(child, template);
                // System.out.println("Decoded " + child.getNodeName() + "."
                // + fieldname + "=" + value);
            }
 
            addObjectValue(obj, fieldname, value, template);
        }
    }
 
    /**
     * Returns the template instance for the given field. This returns the
     * value of the field, null if the value is an array or an empty collection
     * if the value is a collection. The value is then used to populate the
     * field for a new instance. For strongly typed languages it may be
     * required to override this to return the correct collection instance
     * based on the encoded child.
     */
    protected Object getFieldTemplate(Object obj, String fieldname, Node child)
    {
        Object template = getFieldValue(obj, fieldname);
 
        // Arrays are replaced completely
        if (template != null && template.getClass().isArray())
        {
            template = null;
        }
        // Collections are cleared
        else if (template instanceof Collection)
        {
            ((Collection<?>) template).clear();
        }
 
        return template;
    }
 
    /**
     * Sets the decoded child node as a value of the given object. If the
     * object is a map, then the value is added with the given fieldname as a
     * key. If the fieldname is not empty, then setFieldValue is called or
     * else, if the object is a collection, the value is added to the
     * collection. For strongly typed languages it may be required to
     * override this with the correct code to add an entry to an object.
     */
    protected void addObjectValue(Object obj, String fieldname, Object value,
            Object template)
    {
        if (value != null && !value.equals(template))
        {
            if (fieldname != null && obj instanceof Map)
            {
                ((Map) obj).put(fieldname, value);
            }
            else if (fieldname != null && fieldname.length() > 0)
            {
                setFieldValue(obj, fieldname, value);
            }
            // Arrays are treated as collections and
            // converted in setFieldValue
            else if (obj instanceof Collection)
            {
                ((Collection) obj).add(value);
            }
        }
    }
 
    /**
     * Returns true if the given node is an include directive and executes the
     * include by decoding the XML document. Returns false if the given node is
     * not an include directive.
     * 
     * @param dec Codec that controls the encoding/decoding process.
     * @param node XML node to be checked.
     * @param into Optional object to pass-thru to the codec.
     * @return Returns true if the given node was processed as an include.
     */
    public boolean processInclude(mxCodec dec, Node node, Object into)
    {
        if (node.getNodeType() == Node.ELEMENT_NODE
                && node.getNodeName().equalsIgnoreCase("include"))
        {
            String name = ((Element) node).getAttribute("name");
 
            if (name != null)
            {
                try
                {
                    Node xml = mxUtils.loadDocument(
                            mxObjectCodec.class.getResource(name).toString())
                            .getDocumentElement();
 
                    if (xml != null)
                    {
                        dec.decode(xml, into);
                    }
                }
                catch (Exception e)
                {
                    System.err.println("Cannot process include: " + name);
                }
            }
 
            return true;
        }
 
        return false;
    }
 
    /**
     * Hook for subclassers to pre-process the node for the specified object
     * and return the node to be used for further processing by
     * {@link #decode(mxCodec, Node)}. The object is created based on the
     * template in the calling method and is never null.
     * 
     * This implementation returns the input node. The return value of this
     * function is used in {@link #decode(mxCodec, Node)} to perform the
     * default decoding into the given object.
     * 
     * @param dec Codec that controls the decoding process.
     * @param node XML node to be decoded.
     * @param obj Object to encode the node into.
     * @return Returns the node used for the default decoding.
     */
    public Node beforeDecode(mxCodec dec, Node node, Object obj)
    {
        return node;
    }
 
    /**
     * Hook for subclassers to post-process the object after decoding. This
     * implementation returns the given object without any changes. The return
     * value of this method is returned to the decoder from
     * {@link #decode(mxCodec, Node)}.
     * 
     * @param dec Codec that controls the decoding process.
     * @param node XML node to be decoded.
     * @param obj Object that represents the default decoding.
     * @return Returns the result of the decoding process.
     */
    public Object afterDecode(mxCodec dec, Node node, Object obj)
    {
        return obj;
    }
 
}