-
Notifications
You must be signed in to change notification settings - Fork 4
/
repository-mediator.lisp
1165 lines (930 loc) · 56.2 KB
/
repository-mediator.lisp
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
;;; -*- Mode: lisp; Syntax: ansi-common-lisp; Base: 10; Package: de.setf.resource.implementation; -*-
(in-package :de.setf.resource.implementation)
(:documentation
"This file defines the linked data repository interface for the `de.setf.resource` CLOS linked data library."
(copyright
"Copyright 2010 [james anderson](mailto:[email protected]) All Rights Reserved"
"'de.setf.resource' is free software: you can redistribute it and/or modify it under the terms of version 3
of the GNU Affero General Public License as published by the Free Software Foundation.
'de.setf.resource' is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the Affero General Public License for more details.
A copy of the GNU Affero General Public License should be included with 'de.setf.resource' as `agpl.txt`.
If not, see the GNU [site](http://www.gnu.org/licenses/).")
(description
"The abstract repository-mediator class embodies the interface to linked data models and repositories.
It comprises metadata required to manage access to a concrete in-memory model or an external persistent
repository, maintains object identity, transforms representations, and bridges from an uniform operation
interface to the each concrete implementation. The interface comprises an operators set adapted from several
established RDF libraries, [RDF2Go](http://semanticweb.org/wiki/RDF2Go), [RDF.rb]
including default method implementations for any abstract operators.
The operators fall into three classes:
- concrete api operators, for which 'api.lisp' defines the interface and this files defines some
default implementations. Each concrete class may implement its own method.
For the inquiry functions, the abstract class defines class-allocated slots.
- load-repository
- repository-clear
- repository-count
- repository-empty?
- repository-indelible?
- repository-persistent?
- repository-readable?
- repository-transient?
- repository-writable?
- save-repository
- concrete operators, for which this file defines a default implementation
- find-class
- ensure-vocabulary
- find-vocabulary
- load-vocabulary
- model-value
- repository-class-definition
- repository-value
- repository-property-definition
- abstract operators, for which this file defines a default implementation in terms of
primitive functions. A concrete mediator class either defines those primitives or implements
the entire operator
- has-context?
- has-predicate?
- has-object?
- has-statement?
- has-subject?
- insert-statement
- map-contexts
- map-objects
- map-predicates
- map-statements
- map-subjects
- project-graph
- query
- delete-statement
- concrete primitive operators, for which this file defines the interface and each concrete class
implements its own method.
- add-statement*
- delete-statement*
- map-statement*
"))
(defclass repository-mediator ()
((repository
:initform (error "repository required") :initarg :repository
:reader mediator-repository
:documentation "The repository store instance. Each concrete class entails its own specification form
and must provide a default value if no initialization argument is given.")
(id
:initform (uuid:make-v1-uuid) :initarg :id
:reader mediator-id
:documentation "Used to identify the mediator in transactions.")
(transaction-cache
:initform (make-hash-table)
:reader mediator-transaction-cache
:documentation "Caches the instances created and/or modified during a transaction.")
(instance-cache
:initform (make-hash-table :test 'equal)
:reader mediator-instance-cache
:documentation "URI-keyed cache for the instances present in the repository and read into the
application. Registers both transactiona and non-transactional instances to support interned
instantiation. It needs to be weak, but that is not possible portably. An alternative would be weak
entries, in which case it could as well be a weak avl/b+tree.")
(state
:initform de.setf.rdf:non-transactional
:reader mediator-state :writer setf-mediator-state
:documentation "Indicates the mediated transaction state.")
(vocabularies
:initform nil :type list
:reader mediator-vocabularies :writer setf-mediator-vocabularies
:documentation "A list of URI namestrings which designate the vocabularies known to the source.
The value is initialized from (subject . (query nil {rdf}:type {owl}:Ontology)) when the source is
connected and is updated whenever a vocabulary is loaded.")
(identifier-function
:initform 'identifier-identity :initarg :identifier-function
:reader mediator-identifier-function
:documentation "The canonicalization function for term names mapped between the storage and the model
representations according to the convention that model terms are symbols while storage terms
are strings.")
(repository2model-value-map
:initform (make-hash-table :test 'equal)
:reader mediator-repository2model-value-map
:documentation "Maps resource URI to program symbols. The URI representation depends on the repository.")
(model2repository-value-map
:initform (make-hash-table :test 'equal)
:reader mediator-model2repository-value-map
:documentation "Maps model identifiers to repository value. The representation depends on the repository.")
(default-context
:initform (concatenate 'string "urn:sha1:" (compute-spoc-sha1-hex-id ))
:reader mediator-default-context
:documentation "The URN used to identify the graph to used as the repository's default context.")
(indelible
:initarg :indelible :initform nil :allocation :class
:reader de.setf.rdf:repository-indelible? :writer setf-repository-indelible
:documentation "If true, any delete-statement call signals an error. Initially nil.")
(persistent
:initarg :persistent :initform nil :allocation :class
:reader de.setf.rdf:repository-persistent? :writer setf-repository-persistent
:documentation "Indicate if the mediated repository is persistent. Initially nil. (see transient)")
(readable
:initarg :readable :initform t :allocation :class
:reader de.setf.rdf:repository-readable? :writer setf-repository-readable
:documentation "Indicate if the mediated repository is readable. Initially t")
(writable
:initarg :writable :initform t :allocation :class
:reader de.setf.rdf:repository-writable? :writer setf-repository-writable
:documentation "Indicate if the mediated repository supports insert and (if it is not indelible)
delete operations. Initially t.")
(maps-dynamic-extent
:initform t :allocation :class
:reader mediator-maps-dynamic-extent?
:documentation "Indicates the mapping operators pass statements with dynamic extent."))
(:default-initargs
:vocabularies (list *rdf-vocabulary* *rdfs-vocabulary* *owl-vocabulary*
*xsd-vocabulary*))
(:documentation "A repository-mediator encapsulates a concrete triple store to provide a standard repository
interface to that repository's operators and state and mediates between resource instances and the repository.
Concrete specializations are defined as
- wilbur-mediator : for wilbur[1]
- cassandra-mediator_<version> : for cassandra[3] versions
- agraph-mediator : for allegrograph[2]
---
[1]: http://wilbur-rdf.sourceforge.net/
[2]: http://www.franz.com/allegrograph
[3]: cassandra.apache.org/
"))
(define-condition duplicate-statement (simple-error)
((repository :initarg :repository :reader error-repository)
(statement :initarg :statement :reader error-statement))
(:report (lambda (c stream)
(format stream "Statement exists in repository: ~a, ~s."
(error-repository c) (error-statement c)))))
(defmethod print-object ((mediator repository-mediator) (stream t))
(print-unreadable-object (mediator stream :identity t :type t)
(format stream "mediating: ~a x ~a"
(mediator-repository mediator)
(mediator-state mediator))))
(def-class-constructor repository-mediator (object &rest args)
(:method ((null null) &key)
nil)
(:method ((default (eql t)) &key)
(repository-mediator *repository-mediator.default*)))
(defmethod initialize-instance :after ((instance repository-mediator)
&key vocabularies)
"Complete initialization by incorporating vocabularies"
(dolist (vocabulary vocabularies)
(ensure-vocabulary instance vocabulary))
#+ccl
(ccl:terminate-when-unreachable instance))
#+ccl
(defmethod ccl:terminate ((object repository-mediator))
(repository-close object))
(defgeneric mediator-clear-instance-cache (mediator)
(:method ((mediator repository-mediator))
(clrhash (mediator-instance-cache mediator))))
;;;
;;; concrete api operators
(defmethod de.setf.rdf:load-repository ((mediator repository-mediator) (location pathname))
(de.setf.rdf:project-graph location mediator)
(values (de.setf.rdf:repository-count mediator)
location))
(defmethod de.setf.rdf:repository-close ((mediator repository-mediator))
;; the base method does nothing
nil)
(defmethod de.setf.rdf:repository-transient? ((mediator repository-mediator))
(not (de.setf.rdf:repository-persistent? mediator)))
(defmethod de.setf.rdf:save-repository ((mediator repository-mediator) location)
(de.setf.rdf:save-repository (mediator-repository mediator) location))
;;;
;;; default implementations for concrete operators
(defmethod de.setf.rdf:find-class ((mediator repository-mediator) (name symbol) &key (error-p t))
(or (de.setf.rdf:find-class (class-of mediator) name :error-p nil)
(let ((vocabulary (ensure-vocabulary mediator name)))
(when vocabulary
(or (let ((definition (de.setf.rdf:find-class vocabulary name :error-p nil)))
(when definition
(prog1 (eval definition)
(dolist (superclass (third definition))
(de.setf.rdf:find-class mediator superclass)))))
(let ((definition (de.setf.rdf:repository-class-definition mediator (repository-uri mediator name)))
(succeeded nil))
(when definition
;; handle circular references, but don't leave erroneous definitions registered
(setf (de.setf.rdf:find-class vocabulary name) definition)
(unwind-protect (prog1 (eval definition)
(dolist (superclass (third definition))
(de.setf.rdf:find-class mediator superclass))
(setf succeeded t))
(unless succeeded
(setf (de.setf.rdf:find-class vocabulary name) nil)
(setf (find-class name) nil))))))))
(when error-p
(de.setf.rdf:class-not-found (find-class 'resource-class) name))))
(defmethod de.setf.rdf:find-class ((mediator repository-mediator) (identifier t) &rest args)
(declare (dynamic-extent args))
(apply #'de.setf.rdf:find-class mediator (de.setf.rdf:model-value mediator identifier) args))
(defmethod de.setf.rdf:find-instance ((mediator repository-mediator) (subject t))
"Return the instance which is registered with the MEDIATOR for the SUBJECT value's interned equivalent."
(gethash (de.setf.rdf:repository-value mediator subject) (mediator-instance-cache mediator)))
(:documentation de.setf.rdf:ensure-vocabulary de.setf.rdf:find-vocabulary de.setf.rdf:load-vocabulary
"Support RDF schema by translating them into CLOS. Integrate them into the respective repository
mediator to govern term mapping and to provide class definitions. Mediate the definition process through
the repository's repository in order to mitigate variations, inconsistencies, and general insufficiency
in RDF schema documents. This leaves just the variations between RDFS and OWL schema models.
This approach delegates all responsibility for schema discovery to the storage infrastructure, which is
expedient, but admittedly does little to advance issues raised by valkenburg[1].
This mechanism serves two purposes
- During development, one can extract the definitions, augment the terms and/or types, and save them as
Lisp source code for static vocabulary declarations - packages, types, and classes respective one or
more RDF vocabularies.
- At run-time, it generates ephemeral vocabulary definitions on demand, as required to reconcile data to
existing data and procesing models.
The primary interface operations are
- de.setf.rdf:type-of : (identifier) given a resource identifier, return the type as cached or as asserted in the
repository.
- de.setf.rdf:find-class : (mediator identifier) given a class URI, locate or import the class definition.
- de.setf.rdf:load-vocabulary (mediator &key uri) : retrieve the vocabulary specification, parse it to
extract the namespace and the schema and save them in the namespace registry. succeeds only
with self-contained schema - those which are just properties of other schema yield just the
terms, but no classes. (eg. http://purl.org/net/vocab/2003/11/photo.rdf)
---
[1] : http://www.ilrt.bris.ac.uk/discovery/rdf-dev/purls/papers/QL98-distributed/
")
(defmethod de.setf.rdf:ensure-vocabulary ((mediator repository-mediator) (uri string) &rest args)
(or (find-vocabulary mediator uri)
;; otherwise continue to load it and incorporate its terms
(ensure-vocabulary mediator (apply #'load-vocabulary mediator uri args))))
(defmethod de.setf.rdf:ensure-vocabulary ((mediator repository-mediator) (vocabulary vocabulary) &key)
(unless (find vocabulary (mediator-vocabularies mediator))
(de.setf.rdf:load-vocabulary mediator vocabulary))
vocabulary)
(defmethod de.setf.rdf:ensure-vocabulary ((mediator repository-mediator) (uri symbol) &rest args)
(apply #'de.setf.rdf:ensure-vocabulary mediator (package-name (symbol-package uri)) args))
(defmethod de.setf.rdf:find-vocabulary ((mediator repository-mediator) (uri string))
(dolist (vocabulary (mediator-vocabularies mediator))
(when (uri-match-p uri (vocabulary-uri vocabulary))
;; if the namespace is already present - on the basis of bindings, then return.
(return vocabulary))))
(defmethod (setf de.setf.rdf:find-vocabulary) ((value null) (mediator repository-mediator) (uri string))
(flet ((vocabulary-match-p (vocabulary)
(let ((v-uri (vocabulary-uri vocabulary)))
(or (uri-match-p uri v-uri) (uri-match-p v-uri uri)))))
(declare (dynamic-extent #'vocabulary-match-p))
(setf-mediator-vocabularies (remove-if #'vocabulary-match-p (mediator-vocabularies mediator))
mediator))
nil)
(defmethod (setf de.setf.rdf:find-vocabulary) ((vocabulary vocabulary) (mediator repository-mediator) (uri string))
(flet ((vocabulary-match-p (vocabulary)
(let ((v-uri (vocabulary-uri vocabulary)))
(or (uri-match-p uri v-uri) (uri-match-p v-uri uri)))))
(declare (dynamic-extent #'vocabulary-match-p))
(setf-mediator-vocabularies (cons vocabulary
(remove-if #'vocabulary-match-p (mediator-vocabularies mediator)))
mediator))
vocabulary)
(defmethod de.setf.rdf:load-vocabulary ((mediator repository-mediator) (vocabulary vocabulary)
&key (resource-uri (vocabulary-uri vocabulary)))
"Incorporate a vocabulary definition into a repository.
MEDIATOR : repository-mediator
VOCABULARY : vocabulary
Add the vocabulary to the repository and include its terms in the repository's identifier map.
Replaces an existing instance, but an existing instance, but does not attempt to expunge its terms."
;; update the local registry
(setf (de.setf.rdf:find-vocabulary mediator resource-uri) vocabulary)
;; augment the identifier cache
(loop for (symbol . uri-namestring) in (vocabulary-identifier-map vocabulary)
do (register-value mediator symbol (repository-uri mediator uri-namestring)))
;; return the vocabulary
vocabulary)
(defmethod de.setf.rdf:load-vocabulary ((mediator repository-mediator) (uri string) &key (resource-uri nil ru-s))
"Load the schema into the repository repository based a vocabulary uri. Note the actual location and warn
if it diverges from one explicitly provided.
Extract the class definitions starting with immediate type assertions. Recurse through the precedence lists
to allow for incomplete specifications. Each class' property definitions are constructed from immediate
predicate assertions.
Add the specifications as declaration forms to the vocabulary.
Return the vocabulary instance."
(multiple-value-bind (vocabulary-package term)
(uri-vocabulary-components uri)
(declare (ignore term))
(let ((vocabulary-uri (package-name vocabulary-package)))
(multiple-value-bind (loaded-uri loaded-resource-uri)
(de.setf.rdf:load-vocabulary (mediator-repository mediator) vocabulary-uri)
(unless (equal loaded-uri vocabulary-uri)
(warn "Repository vocabulary base uri does not match given value: ~s != ~s."
loaded-uri vocabulary-uri))
(if ru-s
(unless (equal loaded-resource-uri resource-uri)
(warn "Repository vocabulary resource uri does not match given value: ~s != ~s."
loaded-resource-uri resource-uri))
(setf resource-uri loaded-resource-uri))
(let* ((name (first (rassoc vocabulary-uri (repository-namespace-bindings mediator) :test #'equal)))
(vocabulary (make-instance 'vocabulary
:name (or name vocabulary-uri)
:uri vocabulary-uri
:resource-uri resource-uri)))
(de.setf.rdf:project-graph mediator vocabulary)
vocabulary)))))
(:documentation de.setf.rdf:repository-value de.setf.rdf:model-value
"The repository-value and model-value functions map between the literal and resource domains
in the respective rdf repository and the clos data model. Each is defined in terms of two parameters, the
repository mediator and the data object. The resource identifier path relates the values in the data model,
which concerns resource instances and their designators, which are represented as symbols or various uri
objects, with those of the respective repository, each of which has its own uri representation. The literal
path concerns lisp data objects - numbers and strings, which are represented in each repository as objects
which wrap strings to combine them with type information.
The operators construct/deconstruct instances as required and chace the relation in an identity map.
For resources the map is two-way, while for literals just the data-to-rdf mapping implements an
'equal' identity.")
(defmethod de.setf.rdf:model-value :around ((mediator repository-mediator) (repository-value t))
"A default wrapper method first looks in the cache, and delegates to the repository-specific method if there
is a miss. Iff the specialized result differs, cache the correspondence."
(or (gethash repository-value (mediator-repository2model-value-map mediator))
(let ((model-value (call-next-method)))
(cond ((eq model-value repository-value)
repository-value)
(t
(register-value mediator model-value repository-value)
model-value)))))
(defmethod de.setf.rdf:repository-value :around ((mediator repository-mediator) (model-value t))
"A default wrapper method first looks in the cache, and delegates to the repository-specific method if there
is a miss. Iff the specialized result differs, cache the correspondence."
(or (gethash model-value (mediator-model2repository-value-map mediator))
(let ((repository-value (call-next-method)))
(cond ((eq repository-value model-value)
model-value)
(t
(register-value mediator model-value repository-value)
repository-value)))))
(defgeneric register-value (mediator model-value repository-value)
(:documentation "Register the equivalence between a model value (a symbol, uuid, string, or number) and a
repository value (a URI or literal) in the context of this mediated repository.
Double-check for a previous equivalent and require any found correspondence to be equivalent to the new one.
Returns the two values.")
(:method ((mediator repository-mediator) model-value repository-value)
(flet ((register (direction table key new)
(multiple-value-bind (old old-t) (gethash key table)
(if old-t
(cond ((de.setf.rdf:equal old new) old)
((and (de.setf.rdf::literal-p old) (de.setf.rdf::literal-p new))
;; if both are literals, with identical strings, ignore it
old)
(t (cerror "Replace the value." "~a values conflict: ~s: new ~s != old ~s."
direction key new old)
(setf (gethash key table) new)))
(setf (gethash key table) new)))))
(register "model->repository" (mediator-model2repository-value-map mediator) model-value repository-value)
(register "repository->model" (mediator-repository2model-value-map mediator) repository-value model-value))
(values model-value repository-value)))
(defgeneric unregister-value (mediator model-value repository-value)
(:documentation "Remove the given pair from the mediator's immediate repository-model values maps.
This does _not_ trace parent chains, as that actions depends on more context.")
(:method ((mediator repository-mediator) model-value repository-value)
(values (when model-value (remhash model-value (mediator-model2repository-value-map mediator)))
(when repository-value (remhash repository-value (mediator-repository2model-value-map mediator))))))
(defgeneric canonicalize-identifier (mediator identifier)
(:method ((mediator repository-mediator) (identifier string))
(funcall (mediator-identifier-function mediator) identifier))
(:method ((mediator repository-mediator) (identifier symbol))
(funcall (mediator-identifier-function mediator) identifier)))
;;;
;;; abstract operators
(defmethod de.setf.rdf:delete-statement :before ((mediator t) (statement t))
(if (repository-indelible? mediator)
(error "Statements are indelible.")))
(defmethod de.setf.rdf:delete-statement ((mediator repository-mediator) (statement de.setf.rdf:triple))
"if the repository is indelible cause an error, but if the
repository permits revisions, remove the statement."
(delete-statement* mediator (triple-subject statement) (triple-predicate statement) (triple-object statement)
(or (de.setf.rdf:context statement) (mediator-default-context mediator))))
(defmethod de.setf.rdf:insert-statement ((mediator repository-mediator) (statement de.setf.rdf:triple))
(unless (triple-id statement)
(add-statement* mediator (triple-subject statement) (triple-predicate statement) (triple-object statement)
(or (de.setf.rdf:context statement) (mediator-default-context mediator)))))
(defmethod de.setf.rdf:has-statement? ((mediator repository-mediator) (statement de.setf.rdf:triple))
(flet ((probe (statement)
(declare (ignore statement))
(return-from de.setf.rdf:has-statement? t)))
(declare (dynamic-extent #'probe))
(map-statements* #'probe mediator (triple-subject statement) (triple-predicate statement) (triple-object statement)
(or (de.setf.rdf:context statement) (mediator-default-context mediator)))))
(defmethod de.setf.rdf:has-context? ((mediator repository-mediator) (context t))
(flet ((probe (statement)
(declare (ignore statement))
(return-from de.setf.rdf:has-context? t)))
(declare (dynamic-extent #'probe))
(map-statements* #'probe mediator nil nil nil context)))
(defmethod de.setf.rdf:has-object? ((mediator repository-mediator) (object t))
(flet ((probe (statement)
(declare (ignore statement))
(return-from de.setf.rdf:has-object? t)))
(declare (dynamic-extent #'probe))
(map-statements* #'probe mediator nil nil object nil)))
(defmethod de.setf.rdf:has-predicate? ((mediator repository-mediator) (predicate t))
(flet ((probe (statement)
(declare (ignore statement))
(return-from de.setf.rdf:has-predicate? t)))
(declare (dynamic-extent #'probe))
(map-statements* #'probe mediator nil predicate nil nil)))
(defmethod de.setf.rdf:has-subject? ((mediator repository-mediator) (subject t))
(flet ((probe (statement)
(declare (ignore statement))
(return-from de.setf.rdf:has-subject? t)))
(declare (dynamic-extent #'probe))
(map-statements* #'probe mediator subject nil nil nil)))
(:documentation de.setf.rdf:project-graph de.setf.rdf:load-vocabulary
"Extract the stw vocabulary after having loaded it into a repository"
(de.setf.rdf:load-vocabulary (mediator-repository (wilbur-mediator))
"http://zbw.eu/namespaces/zbw-extensions/zbw-extensions.rdf")
(de.setf.rdf:load-vocabulary (mediator-repository (wilbur-mediator))
"http://zbw.eu/namespaces/zbw-extensions/")
(de.setf.rdf:project-graph (wilbur-mediator)
(make-instance 'vocabulary :name "xbw"
:uri "http://zbw.eu/namespaces/zbw-extensions/"
:resource-uri "http://zbw.eu/namespaces/zbw-extensions/zbw-extensions.rdf")))
(defmethod de.setf.rdf:project-graph ((triple de.setf.rdf:triple) (mediator repository-mediator))
"Given a QUAD statement and a MEDIATOR, add the denoted triple to the repository repository, with optional
temporally qualified association to a graph. The implementation depends on the repository schema."
(unless (triple-id triple)
(add-statement* mediator (triple-subject triple) (triple-predicate triple) (triple-object triple)
(or (de.setf.rdf:context triple) (mediator-default-context mediator)))))
(defmethod de.setf.rdf:project-graph ((enumerator function) (mediator repository-mediator))
(flet ((insert-statement (statement)
(de.setf.rdf:insert-statement mediator statement)))
(declare (dynamic-extent #'insert-statement))
(funcall enumerator #'insert-statement)))
(defmethod de.setf.rdf:project-graph ((mediator repository-mediator) (vocabulary vocabulary))
"Extract the vocabulary's definitions from the repository.
nb. query across contexts to collect definitions from all sources."
;; first, extract and collect the first-order vocabulary definitions
(let ((vocabulary-uri (de.setf.rdf:vocabulary-uri vocabulary))
(vocabulary-resource-uri (de.setf.rdf:vocabulary-resource-uri vocabulary))
(definitions ())
(definition-classes ())
(missing-classes ())
(package nil))
(map nil #'(lambda (statement)
(when (or (de.setf.rdf:query mediator :subject (de.setf.rdf:subject statement) :predicate '{rdf}type :object '{rdfs}Class
:context nil)
(de.setf.rdf:query mediator :subject (de.setf.rdf:subject statement) :predicate '{rdf}type :object '{owl}Class
:context nil))
(push (de.setf.rdf:repository-class-definition mediator (de.setf.rdf:subject statement)) definitions)))
(remove-duplicates
(append (de.setf.rdf:query mediator :predicate '{rdfs}isDefinedBy :object (repository-uri mediator vocabulary-uri)
:context nil)
(unless (equal vocabulary-resource-uri vocabulary-uri)
(de.setf.rdf:query mediator :predicate '{rdfs}isDefinedBy :object (repository-uri mediator vocabulary-resource-uri)
:context nil))
;; heavy-handed, but the way to find out what was in the document
(de.setf.rdf:query mediator :context (repository-uri mediator vocabulary-resource-uri)))
:key #'de.setf.rdf:subject))
;; next, given any first-order definitions, continue to walk the class-precedence and property type graph
;; until it closes, as many classes (eg {foaf}Agent and {foaf}Group) include no isDefinedBy assertion.
(setf definition-classes (mapcar #'second definitions))
(setf (vocabulary-definitions vocabulary) definitions)
(setf package (find-package (vocabulary-uri vocabulary)))
(assert (packagep package) () "Missing vocabulary package: ~s." vocabulary)
(do ((definition (pop definitions) (pop definitions)))
((null definition))
(dolist (sd (fourth definition))
(let ((datatype (getf (rest sd) :datatype)))
;; iff the slot's type is an unknown class, add it
(when (and (eq (symbol-package datatype) package)
(not (find datatype definition-classes))
(de.setf.rdf:query mediator :subject datatype :predicate '{rdf}type :object '{rdfs}Class :context nil))
(push datatype missing-classes))))
(dolist (superclass (third definition))
;; iff a superclass is an unknown class, add it
(when (and (eq (symbol-package superclass) package)
(not (find superclass definition-classes)))
(pushnew superclass missing-classes)))
;; generate and collect the definitions used by this class
(do ((missing (pop missing-classes) (pop missing-classes)))
((null missing))
(let ((missing-definition (repository-class-definition mediator missing)))
(push missing definition-classes)
(push missing-definition (vocabulary-definitions vocabulary))
(push missing-definition definitions)))))
;; return the elaborated vocabulary
vocabulary)
(defmethod de.setf.rdf:query ((mediator repository-mediator) &key subject predicate object
(context (mediator-default-context mediator)) continuation offset limit)
"The base method aligns the arguments, provides a default value for context, establishes a
continuation constrained by offset and limit, and invokes map-statements*. It captures the
results and arranges to either invoke an argument continuation on a statement with dynamic
extent, or if no continuation was provided, to collect and return the results as a statement list."
(dsu:collect-list (collect)
(flet ((dynamic-collect (statement)
(when (or (null offset) (minusp (decf offset)))
(if (or (null limit) (not (minusp (decf limit))))
(collect (copy-statement statement))
(return))))
(static-collect (statement)
(when (or (null offset) (minusp (decf offset)))
(if (or (null limit) (not (minusp (decf limit))))
(collect statement)
(return))))
(constrained-continue (statement)
(when (or (null offset) (minusp (decf offset)))
(if (or (null limit) (not (minusp (decf limit))))
(funcall continuation statement)))))
(declare (dynamic-extent #'dynamic-collect #'static-collect #'constrained-continue))
(map-statements* (if continuation
(if (or offset limit) #'constrained-continue continuation)
(if (mediator-maps-dynamic-extent? mediator)
#'dynamic-collect #'static-collect))
mediator subject predicate object context))))
;;;
;;; concrete primitive operators: the interfaces
(defgeneric add-statement* (mediator subject predicate object context)
(:documentation "Adds a single statement corresponding to the arguments to the repository.
All constituents must be provided. If is is determined that the statement already exists, invokes
duplicate-statement on the mediator and the constituents."))
(defgeneric delete-statement* (mediator subject predicate object context)
(:documentation "Removes the single statement corresponding to the arguments from the repository.
All constituents must be provided."))
(defgeneric map-statements* (continuation mediator subject predicate object context)
(:documentation "Maps an operator over all designated statements.
CONTINUATION : (function (statement) t) : applied to the respective statements in turn
MEDIATOR : repository-mediator
SUBJECT : (or literal identifier null)
PREDICATE : (or literal identifier null)
OBJECT : (or literal identifier null)
CONTINUATION : (or literal identifier null)
As invoked from query, if no context is provided, the repository's default context is substituted.
Other components remain null, which serves as a wild-card."))
(defgeneric duplicate-statement (mediator &key statement)
(:documentation "Invoked from add-statement* if the repository indicates that the statement
already exists. The base method signals the duplicate-statement condition, but returns if it
is not handled.")
(:method ((mediator repository-mediator) &key statement)
"The base method signals the condition and returns if it is not handled."
(signal 'duplicate-statement :mediator mediator :statement statement)))
;;;
;;; internal operators : extracting schema from a repository
(defgeneric de.setf.rdf:repository-class-definition (repository identifier)
(:documentation "Given a REPOSITORY and a class IDENTIFIER, construct a class definition based on the
repository's assertions about the class. Extract the supertypes based on {rdfs}subClassOf, slots based on
{rdfs}domain, and documentation based on {rdfs}comment. Assert the class name as the datatype.")
(:method ((mediator repository-mediator) uri)
(flet ((object-value (stmt) (model-value mediator (de.setf.rdf:object stmt))))
(declare (dynamic-extent #'object-value))
(let ((supertypes (mapcar #'object-value (de.setf.rdf:query mediator :subject uri :predicate '{rdfs}subClassOf
:context nil)))
(comments (mapcar #'object-value (de.setf.rdf:query mediator :subject uri :predicate '{rdfs}comment
:context nil)))
(properties (mapcar #'(lambda (statement) (de.setf.rdf:repository-property-definition mediator (de.setf.rdf:subject statement)))
(de.setf.rdf:query mediator :object uri :predicate '{rdfs}domain
:context nil)))
(name (de.setf.rdf:model-value mediator uri)))
`(de.setf.rdf:defclass ,name ,supertypes
,properties
(:datatype ,name)
,@(when comments `(:documentation ,(format nil "~{~a~^~}" comments))))))))
(defgeneric de.setf.rdf:repository-property-definition (repository identifier)
(:documentation "Given a REPOSITORY and a predicate IDENTIFIER, construct a property definition based on the
repository's assertions about the predicate.")
(:method ((mediator repository-mediator) uri)
(flet ((model-value (uri) (model-value mediator uri)))
(declare (dynamic-extent #'model-value))
(let ((types (mapcar #'model-value
(mapcar #'de.setf.rdf:object (de.setf.rdf:query mediator :subject uri :predicate '{rdfs}range
:context nil))))
(comments (mapcar #'de.setf.rdf:object (de.setf.rdf:query mediator :subject uri :predicate '{rdfs}comment
:context nil)))
(name (model-value uri)))
`(,name :type ,(uri-type mediator types)
:datatype ,(if types (if (rest types) `(or ,@types) (first types)) '{rdfs}Literal)
,@(when comments `(:documentation ,(format nil "~{~a~^~}" comments))))))))
(defgeneric respository-schema-types (repository vocabulary-uri)
(:method ((mediator repository-mediator) (uri t))
(loop for statement in (de.setf.rdf:query mediator :predicate '{rdfs}isDefinedBy :object (repository-uri mediator uri)
:context nil)
for subject = (de.setf.rdf:subject statement)
when (find-class (de.setf.rdf:type-of mediator subject ) nil)
collect (de.setf.rdf:model-value mediator subject))))
(defgeneric uri-type (mediator uri-list)
(:documentation "Convert a list of type resource URI into a Lisp type. A single type is mapped as a symbol.
A list is converted into a disjunctive type.")
(:method ((mediator repository-mediator) (uri-list null))
t)
(:method ((mediator repository-mediator) (uri-list cons))
(let ((types (mapcar #'(lambda (uri) (model-value mediator uri)) uri-list)))
(if (rest types)
`(or ,@types)
(first types)))))
;;; for a g5x32bit md5 / sha1 == 2.6 / 5.3
(defun compute-spoc-md5-id (&optional subject predicate object context)
(let* ((p-pos (length subject))
(o-pos (+ p-pos (length predicate)))
(c-pos (+ o-pos (length object)))
(length (+ c-pos (length context)))
(buffer (make-array length :element-type '(unsigned-byte 8))))
(declare (type fixnum length)
(type (simple-array (unsigned-byte 8) (*)) buffer)
(dynamic-extent buffer))
(replace buffer subject)
(replace buffer predicate :start1 p-pos)
(replace buffer object :start1 o-pos)
(replace buffer context :start1 c-pos)
(ironclad:digest-sequence 'crypto:md5 buffer)))
(defun compute-spoc-sha1-id (&optional subject predicate object context)
(let* ((p-pos (length subject))
(o-pos (+ p-pos (length predicate)))
(c-pos (+ o-pos (length object)))
(length (+ c-pos (length context)))
(buffer (make-array length :element-type '(unsigned-byte 8))))
(declare (type fixnum length)
(type (simple-array (unsigned-byte 8) (*)) buffer)
(dynamic-extent buffer))
(replace buffer subject)
(replace buffer predicate :start1 p-pos)
(replace buffer object :start1 o-pos)
(replace buffer context :start1 c-pos)
(ironclad:digest-sequence 'ironclad:sha1 buffer)))
(defun compute-spoc-id (subject predicate object context)
(compute-spoc-md5-id subject predicate object context))
(defun compute-spoc-sha1-hex-id (&optional subject predicate object context)
;; as long as the base function does not pad for missing elements
(with-output-to-string (stream)
(loop for elt across (compute-spoc-sha1-id subject predicate object context)
do (format stream "~(~2,'0x~)" elt))))
;;; (compute-spoc-hex-id #(1) #(2) #(3) #(4))
;;; (compute-spoc-hex-id nil #(2) #(3) nil)
;;; (compute-spoc-hex-id #(2) nil #(3) nil)
;;; (compute-spoc-hex-id nil (binary "<http://ar.to/#self>") nil nil)
;;; (compute-spoc-hex-id nil nil nil nil)
(defgeneric utf-8 (object)
(:method ((object string))
(trivial-utf-8:string-to-utf-8-bytes object)))
(:documentation de.setf.rdf:model-value de.setf.rdf:repository-value
"The default method for a repository mediator encodes values as byte vectors. The structure is
a single-element thrift struct. Each encoding method is an in-line field encoder. The single decoder
fuction decodes the field header number and uses the field number to determine the type expected for the field.
The language tags could be encoded as an additional field (#\a ?), but in order to do
anything with them, one would need combine the tag with the string in a 'string' object to represent them
outside of the repository.
The base type discrimination for numbers distinguishes:
- floating point as float and double-float
- integer as i08, i16, i32, i64, and integer
The former are always distinct, but can exclude one type if the runtime distinguishes three floating point classes.")
(defgeneric repository-uri (mediator namestring)
(:documentation " map between uri and symbol representation")
(:method ((mediator repository-mediator) (uri-namestring string))
"The base method for mediators computes the respective symbol."
(uri-namestring-identifier uri-namestring))
(:method ((mediator repository-mediator) (uri symbol))
uri))
(defgeneric camel-dash-canonicalizer (identifier)
(:method ((string string))
(let ((result (make-array (length string) :element-type 'character :fill-pointer 0 :adjustable t))
(case :upper))
(loop for c across string
do (ecase case
(:lower (cond ((upper-case-p c)
(setf case :upper)
(vector-push-extend #\- result)
(vector-push-extend c result))
(t
(vector-push-extend (char-upcase c) result))))
(:upper (cond ((upper-case-p c)
(vector-push-extend c result))
(t
(setf case :lower)
(vector-push-extend (char-upcase c) result))))))
(subseq result 0)))
(:method ((symbol symbol))
(let* ((string (symbol-name symbol))
(result (make-array (length string) :element-type 'character :fill-pointer 0 :adjustable t))
(state :letter))
(loop for c across string
do (ecase state
(:dash (setf state :letter)
(vector-push-extend (char-upcase c) result))
(:letter (case c
(#\- (setf state :dash))
(t (vector-push-extend (char-downcase c) result))))))
(subseq result 0))))
(defgeneric identifier-identity (identifier)
(:method ((string string)) string)
(:method ((identifier symbol)) (symbol-name identifier)))
(thrift:def-struct "repository_value"
"For use encoding rdf object values."
(("string" nil :id #.(char-code #\S) :type string :optional t)
("double" nil :id #.(char-code #\d) :type thrift:double :optional t)
("float" nil :id #.(char-code #\f) :type thrift:float :optional t) ; inefficient, otherwise extend thrift
("i08" nil :id #.(char-code #\B) :type thrift:i08 :optional t)
("i16" nil :id #.(char-code #\U) :type thrift:i16 :optional t)
("i32" nil :id #.(char-code #\I) :type thrift:i32 :optional t)
("i64" nil :id #.(char-code #\L) :type thrift:i64 :optional t)
("integer" nil :id #.(char-code #\n) :type string :optional t)
("symbol" nil :id #.(char-code #\y) :type thrift:binary :optional t)
("uri" nil :id #.(char-code #\r) :type thrift:binary :optional t)
("uuid" nil :id #.(char-code #\i) :type thrift:binary :optional t)
("binary" nil :id #.(char-code #\b) :type thrift:binary :optional t)))
(defun make-vector-protocol (&rest args &key vector length)
(declare (dynamic-extent args) (ignore vector length))
(let ((transport (apply #'make-instance 'thrift:vector-stream-transport args)))
(make-instance 'thrift:binary-protocol
:direction :io
:input-transport transport
:output-transport transport)))
(defun vector-input-protocol (vector)
"Return the global vector-protocol with the given VECTOR as its input source. If no protocol instance
is present make a new one."
(if *vector-input-protocol*
(setf (thrift:vector-stream-vector (thrift:protocol-output-transport *vector-input-protocol*)) vector)
(setq *vector-input-protocol* (make-vector-protocol :vector vector)))
*vector-input-protocol*)
(defun vector-output-protocol ()
(or *vector-input-protocol*
(setq *vector-input-protocol* (make-vector-protocol))))
(defmacro with-input-from-vector-stream ((vsp &key vector) &body body)
`(let ((,vsp (vector-input-protocol ,vector)))
,@body))
(defmacro with-output-to-vector-stream ((vsp &rest args) &body body)
`(let ((,vsp (vector-output-protocol ,@args)))
,@body
(thrift:vector-stream-vector (thrift:protocol-output-transport ,vsp))))
(defmethod de.setf.rdf:model-value ((mediator repository-mediator) (object vector))
(with-input-from-vector-stream (stream :vector object)
(multiple-value-bind (name id type) (thrift:stream-read-field-begin stream)
(declare (ignore name type))
(ecase id
(#.(char-code #\S) (thrift:stream-read-string stream))
(#.(char-code #\d) (thrift:stream-read-double stream))
(#.(char-code #\f) (thrift:stream-read-float stream))
(#.(char-code #\B) (thrift:stream-read-i08 stream))
(#.(char-code #\U) (thrift:stream-read-i16 stream))
(#.(char-code #\I) (thrift:stream-read-i32 stream))
(#.(char-code #\L) (thrift:stream-read-i64 stream))
(#.(char-code #\n) (parse-integer (thrift:stream-read-string stream)))
(#.(char-code #\y) (flet ((canonicalize (fragment) (canonicalize-identifier mediator fragment)))
(declare (dynamic-extent #'canonicalize))
(uri-namestring-identifier (thrift:stream-read-string stream) #'canonicalize)))
(#.(char-code #\r) (puri:parse-uri (thrift:stream-read-string stream)))
(#.(char-code #\i) (uuid:byte-array-to-uuid (thrift:stream-read-binary stream)))
(#.(char-code #\b) (thrift:stream-read-binary stream))))))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value string))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons string value)) 'repository-value)))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value float))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons float value)) 'repository-value)))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value double-float))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons double value)) 'repository-value)))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value integer))
(with-output-to-vector-stream (stream)
(etypecase value
(thrift:i08 (thrift:stream-write-struct stream (thrift:list (cons i08 value)) 'repository-value))
(thrift:i16 (thrift:stream-write-struct stream (thrift:list (cons i16 value)) 'repository-value))
(thrift:i32 (thrift:stream-write-struct stream (thrift:list (cons i32 value)) 'repository-value))
(thrift:i64 (thrift:stream-write-struct stream (thrift:list (cons i64 value)) 'repository-value))
(integer (let ((value (princ-to-string value)))
(thrift:stream-write-struct stream (thrift:list (cons integer value)) 'repository-value))))))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value symbol))
(flet ((canonicalize (symbol) (canonicalize-identifier mediator symbol)))
(declare (dynamic-extent #'canonicalize))
(let ((uri-namestring (symbol-uri-namestring value #'canonicalize)))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons symbol uri-namestring)) 'repository-value)))))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (identifier uuid:uuid))
(let ((bytes (uuid:uuid-to-byte-array identifier)))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons binary bytes)) 'repository-value))))
(defmethod de.setf.rdf:repository-value ((mediator repository-mediator) (value puri:uri))
(let ((uri-namestring (princ-to-string value)))
(with-output-to-vector-stream (stream)
(thrift:stream-write-struct stream (thrift:list (cons uri uri-namestring)) 'repository-value))))
;;; test default value representation
#-lispworks
(let ((rm (make-instance 'repository-mediator :vocabularies nil :repository nil))
(values `("asdf" 2.0s0 2.0d0 1 ,(expt 2 8) ,(expt 2 16) ,(expt 2 32) ,(expt 2 64)