rev: c523464d146654afc9824b843bc4c543c0c3c10c dataquay/src/objectmapper/ObjectLoader.cpp -rw-r--r-- 32.8 KiB View raw Log this file
c523464d1466 — Chris Cannam Avoid compiler warning for deprecated API we can't readily replace 7 months ago
                                                                                
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
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Dataquay

    A C++/Qt library for simple RDF datastore management.
    Copyright 2009-2012 Chris Cannam.
  
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use, copy,
    modify, merge, publish, distribute, sublicense, and/or sell copies
    of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
    ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Except as contained in this notice, the name of Chris Cannam
    shall not be used in advertising or otherwise to promote the sale,
    use or other dealings in this Software without prior written
    authorization.
*/

#include "objectmapper/ObjectLoader.h"

#include "objectmapper/ObjectBuilder.h"
#include "objectmapper/ContainerBuilder.h"
#include "objectmapper/TypeMapping.h"

#include "objectmapper/ObjectMapperExceptions.h"

#include <QMetaProperty>
#include <QSet>

#include "PropertyObject.h"
#include "Store.h"

#include "../Debug.h"

namespace Dataquay {


/*
 * Generally we pass around a LoadState object recording current
 * progress and work still to do.  See LoadState for the terminology
 * used.
 *
 * We have five phases:
 *
 * 1. Collect -- given the requested node set, fill the toAllocate,
 * toInitialise, and toPopulate sets based on the FollowPolicy.
 *
 * 2. Allocate -- construct new nodes for those in toAllocate that are
 * not yet in the map.  Recurse as appropriate to parent, siblings and
 * children.  (toAllocate contains all the nodes we will need to load,
 * including those we will recurse to when assigning properties for
 * FollowObjectProperties policy later.)
 * 
 * 3. Initialise -- set the "literal" properties for each node in
 * toInitialise
 *
 * 4. Immediate callbacks -- call any registered immediate load
 * callbacks for each node (these are callbacks that may use the
 * "literal" data but should be called before related nodes are
 * loaded)

 * 5. Populate -- set all remaining properties for each node in
 * toPopulate
 *
 * 6. Final callbacks -- call any registered final load callbacks for
 * each node
 *
 * Notes
 *  
 * We should construct a new object when:
 *
 * - a node in requested does not appear in map or is null in map
 *
 * - a node called for as parent or object property does not appear in
 *   map and the relevant follows policy is set
 *
 * We should reload properties for an object node when:
 * 
 * - the node is in requested
 *
 * - the node has just been loaded
 *
 * We should delete an object when:
 * 
 * - a node in requested is in the map but not in the store
 *
 * Cycles are only a problem when loading objects -- not when setting
 * properties.  So we need to ensure that all objects that will need
 * to be loaded for object properties or parents etc are identified
 * before we start loading, then we load relationship tree (no
 * cycles), then we load property objects, then we go through setting
 * properties on the appropriate objects.
 */

class ObjectLoader::D
{
    typedef QSet<Node> NodeSet;

public:
    struct LoadState {

        LoadState() : loadFlags(0) { }

        /// Nodes the customer has explicitly asked to load or reload
        Nodes requested;

        /// Nodes whose objects will need to be constructed if possible
        NodeSet toAllocate;

        /// Nodes pending the first (literal) property assignment
        NodeSet toInitialise;

        /// Nodes pending the full property assignment
        NodeSet toPopulate;

        /// All known node-object correspondences, to be updated as we go
        NodeObjectMap map;

        enum LoadFlags {
            /// Do not throw exception if RDF type unknown (for loadAll etc)
            IgnoreUnknownTypes = 1 << 0,
        };
        unsigned int loadFlags;
    };

    D(ObjectLoader *m, Store *s) :
        m_m(m),
        m_ob(ObjectBuilder::getInstance()),
        m_cb(ContainerBuilder::getInstance()),
        m_s(s),
        m_fp(FollowNone),
        m_ap(IgnoreAbsentProperties) {
        updatePropertyNames();
    }

    Store *getStore() {
        return m_s;
    }

    void setTypeMapping(const TypeMapping &tm) {
	m_tm = tm;
        updatePropertyNames();
    }

    const TypeMapping &getTypeMapping() const {
	return m_tm;
    }

    void setFollowPolicy(FollowPolicy fp) {
        m_fp = fp; 
    }

    FollowPolicy getFollowPolicy() const {
        return m_fp;
    }

    void setAbsentPropertyPolicy(AbsentPropertyPolicy ap) {
        m_ap = ap;
    }

    AbsentPropertyPolicy getAbsentPropertyPolicy() const {
        return m_ap;
    }

    void updatePropertyNames() {
        m_parentProp = Uri(m_tm.getRelationshipPrefix().toString() + "parent");
        m_followProp = Uri(m_tm.getRelationshipPrefix().toString() + "follows");
    }

    QObject *load(Node node) {
        LoadState state;
        state.requested << node;
        collect(state);
        load(state);
        return state.map.value(node);
    }
    
    void reload(Nodes nodes, NodeObjectMap &map) {

        DQ_DEBUG << "reload: " << nodes << endl;
        
        LoadState state;
        state.requested = nodes;
        state.map = map;
        state.loadFlags = LoadState::IgnoreUnknownTypes;

        collect(state);
        load(state);        

        map = state.map;
    }

    QObjectList loadType(Uri type) {
        NodeObjectMap map;
        return loadType(type, map);
    }

    QObjectList loadType(Uri type, NodeObjectMap &map) {
        return loadType(Node(type), map);
    }

    QObjectList loadType(Node typeNode, NodeObjectMap &map) {

        Nodes nodes;
        
        Triples candidates = m_s->match(Triple(Node(), Uri("a"), typeNode));
        foreach (Triple t, candidates) {
            if (t.c.type != Node::URI) continue;
            nodes.push_back(t.a);
        }

        LoadState state;
        state.requested = nodes;
        state.map = map;

        collect(state);
        load(state);

        QObjectList objects;
        foreach (Node n, nodes) {
            QObject *o = map.value(n);
            if (o) objects.push_back(o);
        }
        return objects;
    }

    QObjectList loadAll() {
        NodeObjectMap map;
        return loadAll(map);
    }

    QObjectList loadAll(NodeObjectMap &map) {
        
        Nodes nodes;
        
        Triples candidates = m_s->match(Triple(Node(), Uri("a"), Node()));
        foreach (Triple t, candidates) {
            if (t.c.type != Node::URI) continue;
            nodes.push_back(t.a);
        }

        LoadState state;
        state.requested = nodes;
        state.map = map;
        state.loadFlags = LoadState::IgnoreUnknownTypes;

        collect(state);
        load(state);

        map = state.map;

        QObjectList objects;
        foreach (Node n, nodes) {
            QObject *o = map.value(n);
            if (o) objects.push_back(o);
        }
        return objects;
    }
    
    void addLoadCallback(LoadCallback *cb, LoadCallbackType type) {
        switch (type) {
        case ImmediateCallback:
            m_immediateCallbacks.push_back(cb);
            break;
        case FinalCallback:
            m_finalCallbacks.push_back(cb);
            break;
        }
    }

private:
    ObjectLoader *m_m;
    ObjectBuilder *m_ob;
    ContainerBuilder *m_cb;
    Store *m_s;
    TypeMapping m_tm;
    FollowPolicy m_fp;
    AbsentPropertyPolicy m_ap;
    QList<LoadCallback *> m_immediateCallbacks;
    QList<LoadCallback *> m_finalCallbacks;
    Uri m_parentProp;
    Uri m_followProp;

    void collect(LoadState &state) {

        Nodes candidates = state.requested;
        NodeSet visited;

        // Avoid ever pushing the nil Node as a future candidate by
        // marking it as used already

        visited << Node();
        
        // Use counter to iterate, so that when additional elements
        // pushed onto the end of state.desired will be iterated over

        for (int i = 0; i < candidates.size(); ++i) {

            Node node = candidates[i];

            visited << node;

            if (!state.map.contains(node) || state.map.value(node) == 0) {

                if (!nodeHasTypeInStore(node)) {
                    continue;
                } else {
                    state.toAllocate.insert(node);
                    state.toInitialise.insert(node);
                    state.toPopulate.insert(node);
                } 

            } else if (i < state.requested.size()) {
                
                // This is one of the requested nodes, which were at
                // the start of the candidates list

                if (!nodeHasTypeInStore(node)) {
                    DQ_DEBUG << "Node " << node
                          << " has no type in store, deleting and resetting"
                          << endl;
                    delete state.map.value(node);
                    state.map.insert(node, 0);
                    continue;
                }

                state.toInitialise.insert(node);
                state.toPopulate.insert(node);
            }

            Nodes relatives;

            if (m_fp & FollowParent) {
                relatives << parentOf(node);
            }
            if (m_fp & FollowChildren) {
                relatives << childrenOf(node);
            }
            if (m_fp & FollowSiblings) {
                relatives << prevSiblingOf(node) << nextSiblingOf(node);
            }
            if (m_fp & FollowObjectProperties) {
                relatives << potentialPropertyNodesOf(node);
            }
                
            foreach (Node r, relatives) {
                if (!visited.contains(r)) {
                    candidates << r;
                }
            }
        }

        DQ_DEBUG << "ObjectLoader: collect: "
              << "requested = " << state.requested.size()
              << ", toAllocate = " << state.toAllocate.size()
              << ", toInitialise = " << state.toInitialise.size()
              << ", toPopulate = " << state.toPopulate.size()
              << endl;

        DQ_DEBUG << "Requested:";
        foreach (Node n, state.requested) DQ_DEBUG << n;

        DQ_DEBUG << "toAllocate:";
        foreach (Node n, state.toAllocate) DQ_DEBUG << n;

        DQ_DEBUG << "toInitialise:";
        foreach (Node n, state.toInitialise) DQ_DEBUG << n;

        DQ_DEBUG << "toPopulate:";
        foreach (Node n, state.toPopulate) DQ_DEBUG << n;

        DQ_DEBUG << endl;
    }

    bool nodeHasTypeInStore(Node node) {
        Triple t = m_s->matchOnce(Triple(node, Uri("a"), Node()));
        return (t.c.type == Node::URI);
    }

    Node parentOf(Node node) {
        Triple t = m_s->matchOnce(Triple(node, m_parentProp, Node()));
        if (t != Triple()) return t.c;
        else return Node();
    }

    Nodes childrenOf(Node node) {
        Nodes nn;
        Triples tt = m_s->match(Triple(Node(), m_parentProp, node));
        foreach (Triple t, tt) nn << t.a;
        return nn;
    }

    Node prevSiblingOf(Node node) {
        Triple t = m_s->matchOnce(Triple(node, m_followProp, Node()));
        if (t != Triple()) return t.c;
        else return Node();
    }

    Node nextSiblingOf(Node node) {
        Triple t = m_s->matchOnce(Triple(Node(), m_followProp, node));
        if (t != Triple()) return t.a;
        else return Node();
    }

    Nodes orderedSiblingsOf(Node node) {
        Node current = node;
        Node prior;
        while ((prior = prevSiblingOf(current)) != Node()) {
            current = prior;
        }
        Nodes siblings;
        while (current != Node()) {
            siblings << current;
            current = nextSiblingOf(current);
        }
        return siblings;
    }    

    Nodes orderedChildrenOf(Node node) {
        // We're not certain to find follows properties for all
        // children; if some or all are missing, we still need to
        // return the right number of children -- they just won't
        // actually be ordered
        Nodes children = childrenOf(node);
        if (children.empty()) return children;
        
        // Qt 5.14 deprecates QSet::fromList, but its suggested
        // replacement (a constructor taking begin and end iterators)
        // was only added the same 5.14 release!
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

        NodeSet remaining = NodeSet::fromList(children);
        Nodes ordered = orderedSiblingsOf(children[0]);
        remaining.subtract(NodeSet::fromList(ordered));
        foreach (Node n, remaining) ordered.push_back(n);
        DQ_DEBUG << "orderedChildrenOf: Node " << node << " has " << ordered.size()
              << " children: " << ordered << endl;
        return ordered;
    }
        
    Nodes potentialPropertyNodesOf(Node node) {
        //!!! what to do about nodes that end up in candidates and so are loaded, but are never actually needed?
        Nodes nn;
        Triples tt = m_s->match(Triple(node, Node(), Node()));
        foreach (Triple t, tt) {
            if (nodeHasTypeInStore(t.c)) {
                nn << t.c;
            } else {
                Nodes sequence = sequenceStartingAt(t.c);
                foreach (Node sn, sequence) {
                    if (nodeHasTypeInStore(sn)) {
                        nn << sn;
                    }
                }
            }
        }
        return nn;
    }

    Nodes sequenceStartingAt(Node node) {

        Nodes nn;
        Triple t;

        Node itr = node;
        Node nil = m_s->expand("rdf:nil");
        
        while ((t = m_s->matchOnce(Triple(itr, m_s->expand("rdf:first"), Node())))
               != Triple()) {

            nn << t.c;

            t = m_s->matchOnce(Triple(itr, m_s->expand("rdf:rest"), Node()));
            if (t == Triple()) break;

            itr = t.c;
            if (itr == nil) break;
        }

        if (!nn.empty()) {
            DQ_DEBUG << "sequenceStartingAt " << node << " has " << nn.size() << " item(s)" << endl;
        }

        return nn;
    }

    void load(LoadState &state) {
        foreach (Node node, state.toAllocate) {
            DQ_DEBUG << "load: calling allocate(" << node << ")" << endl;
            try {
                allocate(state, node);
            } catch (const UnknownTypeException &e) {
                if (state.loadFlags & LoadState::IgnoreUnknownTypes) {
                    DQ_DEBUG << "load: IgnoreUnknownTypes is set, removing object of unknown type and continuing" << endl;
                    delete state.map.value(node);
                    state.map.insert(node, 0);
                    state.toInitialise.remove(node);
                    state.toPopulate.remove(node);
                } else {
                    throw;
                }
            }
        }

        // allocate() also calls initialise(), because we want the
        // initialise to happen before children are added to a node --
        // this is just belt and braces
        foreach (Node node, state.toInitialise) {
            DQ_DEBUG << "load: calling initialise(" << node << ")" << endl;
            initialise(state, node);
        }

        // populate() removes from state.toPopulate, so we need to
        // make a note of the original set for calling load callbacks
        NodeSet tp = state.toPopulate;

        foreach (Node node, tp) {
            DQ_DEBUG << "load: calling populate(" << node << ")" << endl;
            populate(state, node);
        }
        foreach (Node node, tp) {
            DQ_DEBUG << "load: calling callLoadCallbacks(" << node << ")" << endl;
            callLoadCallbacks(state, node, m_finalCallbacks);
        }
    }

    QObject *parentObjectOf(LoadState &state, Node node) {
        
        Node parent = parentOf(node);
        QObject *parentObject = 0;

        if (parent != Node()) {
            allocate(state, parent);
            parentObject = state.map.value(parent);
        }

        return parentObject;
    }

    void allocate(LoadState &state, Node node) {

        //!!! too many of these tests, some must be redundant
        if (!state.toAllocate.contains(node)) return;

        QObject *parentObject = parentObjectOf(state, node);

        allocate(state, node, parentObject);
    }

    void allocate(LoadState &state, Node node, QObject *parentObject) {

        //!!! too many of these tests, some must be redundant
        if (!state.toAllocate.contains(node)) return;

        if (m_fp & FollowSiblings) {
            Nodes siblings = orderedSiblingsOf(node);
            foreach (Node s, siblings) {
                //!!! Hmm. Do we want to recurse to children of siblings if FollowChildren is set? Trouble is we don't want to recurse to siblings of siblings (that would lead to a cycle)
                allocateSingle(state, s, parentObject);
            }
        }

        QObject *o = allocateSingle(state, node, parentObject);

        if (state.toInitialise.contains(node)) {
            DQ_DEBUG << "load: calling initialise(" << node << ") from allocate" << endl;
            initialise(state, node);
        }

        if (m_fp & FollowChildren) {
            Nodes children = orderedChildrenOf(node);
            foreach (Node c, children) {
                allocate(state, c, o);
            }
        }
    }

    QObject *allocateSingle(LoadState &state, Node node) {
        QObject *parentObject = parentObjectOf(state, node);
        return allocateSingle(state, node, parentObject);
    }

    QObject *allocateSingle(LoadState &state, Node node, QObject *parentObject) {

        DQ_DEBUG << "allocateSingle: " << node << " (parent = " << parentObject << ")" << endl;

        //!!! too many of these tests, some must be redundant
        if (!state.toAllocate.contains(node)) {
            DQ_DEBUG << "already loaded: returning existing value (" << state.map.value(node) << ")" << endl;
            return state.map.value(node);
        }

        QObject *o = allocateObject(node, parentObject);

        DQ_DEBUG << "Setting object " << o << " to map for node " << node << endl;

        QObject *old = state.map.value(node);
        if (o != old) {
            DQ_DEBUG << "Deleting old object " << old << endl;
            delete old;
        }

        state.map.insert(node, o);
        state.toAllocate.remove(node);

        QObject *x = state.map.value(node);
        DQ_DEBUG << "New value is " << x << endl;

        return o;
    }

    void callLoadCallbacks(LoadState &state, Node node,
                           QList<LoadCallback *> &callbacks) {

        QObject *o = state.map.value(node);

        DQ_DEBUG << "callLoadCallbacks: " << node << " -> " << o << endl;

        if (!o) return;

        foreach (LoadCallback *cb, callbacks) {
            cb->loaded(m_m, state.map, node, o);
        }
    }

    QString getClassNameForNode(Node node);

    QObject *allocateObject(Node node, QObject *parent);

    void initialise(LoadState &, Node node);
    void populate(LoadState &, Node node);

    enum PropertyLoadType {
        LoadAllProperties,
        LoadLiteralProperties,
        LoadNonLiteralProperties
    };
    void loadProperties(LoadState &, Node node, PropertyLoadType);

    QVariant propertyNodeListToVariant(LoadState &, QString typeName, Nodes pnodes);
    QObject *propertyNodeToObject(LoadState &, Node pnode);
    QVariant propertyNodeToVariant(LoadState &, QString typeName, Node pnode);
    QVariantList propertyNodeToList(LoadState &, QString typeName, Node pnode);
};

void
ObjectLoader::D::initialise(LoadState &state, Node node)
{
    loadProperties(state, node, LoadLiteralProperties);
    callLoadCallbacks(state, node, m_immediateCallbacks);
    state.toInitialise.remove(node);
}

void
ObjectLoader::D::populate(LoadState &state, Node node)
{
    loadProperties(state, node, LoadNonLiteralProperties);
    state.toPopulate.remove(node);
}

void
ObjectLoader::D::loadProperties(LoadState &state, Node node,
                                PropertyLoadType loadType)
{
    QObject *o = state.map.value(node);
    if (!o) return;

    QString cname = o->metaObject()->className();

    CacheingPropertyObject *po = new CacheingPropertyObject
        (m_s, m_tm.getPropertyPrefix().toString(), node);

    QObject *defaultsObject = 0;

    for (int i = 0; i < o->metaObject()->propertyCount(); ++i) {

        QMetaProperty property = o->metaObject()->property(i);

        if (!property.isStored() ||
            !property.isReadable() ||
            !property.isWritable()) {
            continue;
        }

        QString pname = property.name(); // name to use when setting on QObject
        QString plookup(pname);          // name or URI for PropertyObject

	Uri puri;
	if (m_tm.getPropertyUri(cname, pname, puri)) {
	    plookup = puri.toString();
	}

        Nodes pnodes;
        bool haveProperty = po->hasProperty(plookup);
        if (haveProperty) {
            pnodes = po->getPropertyNodeList(plookup);
            if (pnodes.empty()) {
                haveProperty = false;
            }
        }

        if (loadType != LoadAllProperties) {
            bool literal = true;
            foreach (Node n, pnodes) {
                if (n.type != Node::Literal) {
                    literal = false;
                    break;
                }
            }
            if ( literal && (loadType == LoadNonLiteralProperties)) continue;
            if (!literal && (loadType == LoadLiteralProperties)) continue;
        }
        
        DQ_DEBUG << "For property " << pname << " of " << node << " have "
              << pnodes.size() << " node(s)" << endl;

        if (!haveProperty && m_ap == IgnoreAbsentProperties) continue;

        QVariant value;
        QByteArray pnba = pname.toLocal8Bit();

        if (!haveProperty) {
            if (!defaultsObject) {
                if (m_ob->knows(cname)) {
                    defaultsObject = m_ob->build(cname, 0);
                } else {
                    DQ_DEBUG << "Can't reset absent property " << pname
                          << " of object " << node << ": object builder "
                          << "doesn't know type " << cname << " so cannot "
                          << "build defaults object" << endl;
                }
            }

            if (defaultsObject) {
                DQ_DEBUG << "Resetting property " << pname << " to default" << endl;
                value = defaultsObject->property(pnba.data());
            }

        } else {
            QString typeName = property.typeName();
            DQ_DEBUG << "Setting property " << pname << " of type " << typeName << endl;
            value = propertyNodeListToVariant(state, typeName, pnodes);
        }

        if (!value.isValid()) {
            DQ_DEBUG << "Ignoring invalid variant for value of property "
                  << pname << ", type " << property.typeName()
                  << " of object " << node << endl;
            continue;
        }

        if (!o->setProperty(pnba.data(), value)) {
            DQ_DEBUG << "loadProperties: Property set failed "
                  << "for property " << pname << " of type "
                  << property.typeName() << " (" << property.userType()
                  << ") to value of type " << value.type() 
                  << " and value " << value
                  << " from (first) node " << pnodes[0].value
                  << endl;
            DQ_DEBUG << "loadProperties: If the RDF datatype is correct, check "
                  << "[1] that the datatype is known to Dataquay::Node for "
                  << "node-variant conversion"
                  << "(datatype is one of the standard set, "
                  << "or registered with Node::registerDatatype) and "
                  << "[2] that the Q_PROPERTY type declaration "
                  << property.typeName()
                  << " matches the name passed to qRegisterMetaType (including namespace)"
                  << endl;
            std::cerr << "ObjectLoader::loadProperties: Failed to set property on object, ignoring" << std::endl;
        }
    }

    delete defaultsObject;
    delete po;
}

QVariant
ObjectLoader::D::propertyNodeListToVariant(LoadState &state, 
                                           QString typeName, Nodes pnodes)
{
    if (pnodes.empty()) return QVariant();

    Node firstNode = pnodes[0];

    DQ_DEBUG << "propertyNodeListToVariant: typeName = " << typeName << endl;

    if (typeName == "") {
        return firstNode.toVariant();
    }

    if (m_cb->canInjectContainer(typeName)) {

        QString inContainerType = m_cb->getTypeNameForContainer(typeName);
        ContainerBuilder::ContainerKind k = m_cb->getContainerKind(typeName);

        if (k == ContainerBuilder::SequenceKind) {
            QVariantList list =
                propertyNodeToList(state, inContainerType, firstNode);
            return m_cb->injectContainer(typeName, list);

        } else if (k == ContainerBuilder::SetKind) {
            QVariantList list;
            foreach (Node pnode, pnodes) {
                Nodes sublist;
                sublist << pnode;
                list << propertyNodeListToVariant(state, inContainerType, sublist);
            }
            return m_cb->injectContainer(typeName, list);

        } else {
            return QVariant();
        }

    } else if (m_ob->canInject(typeName)) {

        QObject *obj = propertyNodeToObject(state, firstNode);
        QVariant v;
        if (obj) {
            v = m_ob->inject(typeName, obj);
            if (v == QVariant()) {
                DQ_DEBUG << "propertyNodeListToVariant: "
                      << "Type of node " << firstNode
                      << " is incompatible with expected "
                      << typeName << endl;
                std::cerr << "ObjectLoader::propertyNodeListToVariant: "
                          << "Incompatible node type, ignoring" << std::endl;
                //!!! don't delete the object without removing it from the map!
                // but which to do -- remove it, or leave it?
//                delete obj;
            }
        }
        return v;

    } else if (QString(typeName).contains("*") ||
               QString(typeName).endsWith("Star")) {
        // do not attempt to read binary pointers!
        return QVariant();

    } else {

        return propertyNodeToVariant(state, typeName, firstNode);
    }
}

QVariant
ObjectLoader::D::propertyNodeToVariant(LoadState & /* state */,
                                       QString typeName, Node pnode)
{
    // Usually we can take the default conversion from node to
    // QVariant.  But in two cases this will fail in ways we need to
    // correct:
    // 
    // - The node is an untyped literal and the property is known to
    // have a type other than string (default conversion would produce
    // a string)
    // 
    // - The node is a URI and the property is known to have a type
    // other than Uri (several legitimate property types could
    // reasonably receive data from a URI node)
    //
    // One case should not be corrected:
    //
    // - The node has a type but it doesn't match that of the property
    //
    // We have to fail that one, because we're not in any position to
    // do general type conversion here.

    DQ_DEBUG << "propertyNodeToVariant: typeName = " << typeName << endl;

    if (typeName == "") {
        return pnode.toVariant();
    }

    bool acceptDefault = true;

    if (pnode.type == Node::URI && typeName != Uri::metaTypeName()) {

        DQ_DEBUG << "ObjectLoader::propertyNodeListToVariant: "
              << "Non-URI property is target for RDF URI, converting" << endl;
        
        acceptDefault = false;

    } else if (pnode.type == Node::Literal &&
               pnode.datatype == Uri() && // no datatype
               typeName != QMetaType::typeName(QMetaType::QString)) {

        DQ_DEBUG << "ObjectLoader::propertyNodeListToVariant: "
              << "No datatype for RDF literal, deducing from typename \""
              << typeName << "\"" << endl;

        acceptDefault = false;
    }

    if (acceptDefault) {
        return pnode.toVariant();
    }

    QByteArray ba = typeName.toLocal8Bit();
    int metatype = QMetaType::type(ba.data());
    if (metatype != 0) return pnode.toVariant(metatype);
    else return pnode.toVariant();
}

QObject *
ObjectLoader::D::propertyNodeToObject(LoadState &state, Node pnode)
{
    QObject *o = 0;

    if (pnode.type == Node::URI || pnode.type == Node::Blank) {
        o = allocateSingle(state, pnode);
    } else {
        DQ_DEBUG << "Not an object node, ignoring" << endl;
    }

    return o;
}

QVariantList
ObjectLoader::D::propertyNodeToList(LoadState &state, 
                                    QString typeName, Node pnode)
{
    Nodes sequence = sequenceStartingAt(pnode);

    QVariantList list;

    foreach (Node node, sequence) {

        Nodes vnodes;
        vnodes << node;
        QVariant value = propertyNodeListToVariant(state, typeName, vnodes);

        if (value.isValid()) {
            DQ_DEBUG << "Found value: " << value << endl;
            list.push_back(value);
        } else {
            DQ_DEBUG << "propertyNodeToList: Invalid value in list, skipping" << endl;
        }
    }

    DQ_DEBUG << "propertyNodeToList: list has " << list.size() << " item(s)" << endl;
    return list;
}

QString
ObjectLoader::D::getClassNameForNode(Node node)
{
    Uri typeUri;
    Triple t = m_s->matchOnce(Triple(node, Uri("a"), Node()));
    if (t.c.type == Node::URI) typeUri = Uri(t.c.value);

    QString className;
    if (typeUri != Uri()) {
        try {
            className = m_tm.synthesiseClassForTypeUri(typeUri);
        } catch (const UnknownTypeException &) {
            DQ_DEBUG << "getClassNameForNode: Unknown type URI " << typeUri << endl;
            throw;
        }
    } else {
        DQ_DEBUG << "getClassNameForNode: No type URI for " << node << endl;
        throw UnknownTypeException("");
    }
        
    if (!m_ob->knows(className)) {
        DQ_DEBUG << "ObjectLoader::getClassNameForNode: Unknown object class "
              << className << endl;
        throw UnknownTypeException(className);
    }

    return className;
}

QObject *
ObjectLoader::D::allocateObject(Node node, QObject *parent)
{
    // Note that we cannot rely on the object class from a property
    // declaration to know what type to construct.  For example, if we
    // have been called as part of a process of loading something
    // declared as container of base-class pointers, but each
    // individual object is actually of a derived class, then the RDF
    // should specify the derived class but we will only have been
    // passed the base class.  So we must use the RDF type.

    QString className = getClassNameForNode(node);
    
    DQ_DEBUG << "Making object " << node.value << " of type "
          << className << " with parent " << parent << endl;

    QObject *o = m_ob->build(className, parent);
    if (!o) throw ConstructionFailedException(className);
	
    if (node.type == Node::URI) {
        o->setProperty("uri", QVariant::fromValue(m_s->expand(node.value)));
    }

    DQ_DEBUG << "Made object: " << o << endl;

    return o;
}

ObjectLoader::ObjectLoader(Store *s) :
    m_d(new D(this, s))
{ }

ObjectLoader::~ObjectLoader()
{
    delete m_d;
}

Store *
ObjectLoader::getStore()
{
    return m_d->getStore();
}

void
ObjectLoader::setTypeMapping(const TypeMapping &tm)
{
    m_d->setTypeMapping(tm);
}

const TypeMapping &
ObjectLoader::getTypeMapping() const
{
    return m_d->getTypeMapping();
}

void
ObjectLoader::setFollowPolicy(FollowPolicy policy)
{
    m_d->setFollowPolicy(policy);
}

ObjectLoader::FollowPolicy
ObjectLoader::getFollowPolicy() const
{
    return m_d->getFollowPolicy();
}

void
ObjectLoader::setAbsentPropertyPolicy(AbsentPropertyPolicy policy)
{
    m_d->setAbsentPropertyPolicy(policy);
}

ObjectLoader::AbsentPropertyPolicy
ObjectLoader::getAbsentPropertyPolicy() const
{
    return m_d->getAbsentPropertyPolicy();
}

QObject *
ObjectLoader::load(Node node)
{
    return m_d->load(node);
}

void
ObjectLoader::reload(Nodes nodes, NodeObjectMap &map)
{
    m_d->reload(nodes, map);
}

QObjectList
ObjectLoader::loadType(Uri type)
{
    return m_d->loadType(type);
}

QObjectList
ObjectLoader::loadType(Uri type, NodeObjectMap &map)
{
    return m_d->loadType(type, map);
}

QObjectList
ObjectLoader::loadAll()
{
    return m_d->loadAll();
}

QObjectList
ObjectLoader::loadAll(NodeObjectMap &map)
{
    return m_d->loadAll(map);
}

void
ObjectLoader::addLoadCallback(LoadCallback *cb, LoadCallbackType type)
{
    m_d->addLoadCallback(cb, type);
}

}