-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.cljc
executable file
·1445 lines (1301 loc) · 48 KB
/
core.cljc
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
(ns ont-app.rdf.core
{:doc "This is a backstop for shared logic between various RDF-based
implementations of IGraph.
It includes:
- support for LangStr using the #voc/lstr custom reader
- support for typed literals using the #voc/dstr custom reader
- support for ^^transit:json datatype tags
- templating utilities for the standard IGraph member access methods.
- i/o methods `load-rdf` `read-rdf` and `write-rdf`.
"
:author "Eric D. Scott"
;; These errors were found to be spurious, related to cljs ...
:clj-kondo/config '{:linters {:unresolved-symbol {:level :off}
:unresolved-namespace {:level :off}}}
} ;; meta
(:require
[clojure.string :as s]
[clojure.spec.alpha :as spec]
;; 3rd party
[cljstache.core :as stache]
;; ont-app
[ont-app.igraph.core :as igraph :refer [unique]]
[ont-app.igraph.graph :as native-normal]
[ont-app.vocabulary.core :as voc]
[ont-app.rdf.ont :as ont]
;; reader conditionals
#?(:clj [clj-http.client :as http]) ;; todo add cljs-http.client?
#?(:clj [clojure.java.io :as io])
#?(:clj [cognitect.transit :as transit]) ;; todo remove conditional after issue 4
#?(:clj [ont-app.graph-log.levels :as levels
:refer [warn debug trace value-trace value-debug]]
:cljs [ont-app.graph-log.levels :as levels
:refer-macros [warn debug value-trace value-debug]])
#?(:clj [ont-app.vocabulary.lstr :as lstr :refer [->LangStr]]) ;; todo remove conditional after issue 4
#?(:clj [ont-app.vocabulary.dstr :as dstr :refer [->DatatypeStr]]);; todo remove conditional after issue 4
) ;; require
#?(:clj
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.io File]
[ont_app.vocabulary.lstr LangStr]
[ont_app.vocabulary.dstr DatatypeStr]
)))
(voc/put-ns-meta! 'ont-app.rdf.core {:voc/mapsTo 'ont-app.rdf.ont})
;; aliases
(def prefixed
"Returns `query`, with prefix declarations prepended
Where
- `query` is presumed to be a SPARQL query"
voc/prepend-prefix-declarations)
(def ontology
"The supporting vocabulary for the RDF module"
@ont/ontology-atom)
;; FUN WITH READER MACROS
#?(:cljs
(enable-console-print!)
)
#?(:cljs
(defn on-js-reload [] )
)
;; standard clojure containers are declared by default as descendents of
;; :rdf-app/TransitData, which keys to the render-literal method for rendering
;; transit data. renders as transit by default.
;; Note that you can undo this with 'underive', in which case
;; it will probably be rendered as a string, unless you want
;; to write your own method...
(derive #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentList
:cljs cljs.core.PersistentList )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.Cons
:cljs cljs.core.Cons )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq )
:rdf-app/TransitData)
#?(:clj (derive java.lang.Long ::number)
:cljs (derive cljs.core.Long ::number)
)
#?(:clj (derive java.lang.Double ::number)
:cljs (derive cljs.core..Double ::number)
)
(declare transit-read-handlers)
(defn read-transit-json
"Returns a value parsed from transit string `s`
Where
- `s` is a "-escaped string encoded as transit
Note: custom datatypes will be informed by @transit-read-handlers
"
[^String s]
(tap> {:type ::starting-read-transit-json
::s s})
#?(:clj
(transit/read
(transit/reader
(ByteArrayInputStream. (.getBytes (clojure.string/replace
s
""" "\"")
"UTF-8"))
:json
{:handlers @transit-read-handlers}))
:cljs
(throw (ex-info "read-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'read-transit-json
::args [s]
}))
#_(transit/read
(transit/reader
:json
{:handlers @transit-read-handlers})
(clojure.string/replace
s
""" "\""))))
(defmethod voc/untag :transit/json
[datum & _]
(-> datum str read-transit-json))
(declare transit-write-handlers)
(defn render-transit-json
"Returns a string of transit for `value`
Where
- `value` is any value that be handled by cognitict/transit
- Note: custom datatypes will be informed by @transit-write-handlers
"
[value]
#?(:clj
(let [output-stream (ByteArrayOutputStream.)
]
(transit/write
(transit/writer output-stream :json {:handlers @transit-write-handlers})
value)
(String. (.toByteArray output-stream)))
:cljs
(throw (ex-info "render-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'render-transit-json
::args [value]
}))
#_(transit/write
(transit/writer :json {:handlers @transit-write-handlers})
value)))
(defmethod voc/tag :transit/json
[datum _]
(dstr/->DatatypeStr (render-transit-json datum) "transit:json"))
(defn cljc-file-exists?
"True when `path` exists in the local file system"
[path]
#?(:clj
(.exists (io/file path))
:cljs
(let []
(warn ::FileExistsCheckInCljs
:glog/message "Checking for existence of local file {{path}} in clojurescript (returning false)"
::path path)
false
)))
(defn cljc-is-local-file?
"True when `f` is a file in the local file system"
[f]
#?(:clj
(instance? java.io.File f)
:cljs
(let []
(warn ::IsLocalFileCheckInCljs
:glog/message "Checking whether {{f}} is local file in clojurescript (returning false)"
::f f)
false)))
(defn cljc-make-file
"Returns new file object for `path`. not yet supported under cljs."
[path]
#?(:clj
(io/file path)
:cljs
(throw (ex-info "Make-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-file
::args [path]
}))))
(defn cljc-file-length
"Returns length of file `f`. not yet supported under cljs."
[f]
#?(:clj
(.length f)
:cljs
(throw (ex-info "File-length not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-file-length
::args [f]
}))))
(defn cljc-make-parents
"Ensures directory path for file `f`. not yet supported under cljs."
[f]
#?(:clj
(io/make-parents f)
:cljs
(throw (ex-info "Make-parents not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-parents
::args [f]
}))))
(defn cljc-resource
"Returns the resource named by `r`. not yet supported under cljs."
[r]
#?(:clj
(io/resource r)
:cljs
(throw (ex-info "Resource not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-resource
::args [r]
}))))
(defn cljc-create-temp-file
"Returns a temporary file named per `stem` and `ext`. not yet supported under cljs.
- where
- `stem` is a general name for the file
- `ext` is a file extension typically starting with '.'
"
[stem ext]
#?(:clj
(File/createTempFile stem ext)
:cljs
(throw (ex-info "Create-temp-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-create-temp-file
::args [stem ext]
}))))
(defn cljc-http-get
"Makes a GET call to `url` with `req`. Not yet supported in cljs.
- Where
- `url` is a URL or a URL string
- `req` is an http request map
"
[url req]
#?(:clj
(http/get (str url) req)
:cljs
;; TODO: probably need to import cljs-http. Pending issue 4
(throw (ex-info "Http-get not yet supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-http-get
::args [url req]
}))))
;; NO READER MACROS BELOW THIS POINT
;; except in try/catch clauses
;; SPECS
(def transit-re
"Matches data tagged as transit:json"
(re-pattern (str "^\"" ;; start with quote
"(.*)" ;; anything (group 1)
"\"" ;; terminal quote
"\\^\\^" ;; ^^
"transit:json$" ;; end with type tag
)))
(spec/def ::transit-tag (spec/and string? (fn [s] (re-matches transit-re s))))
;;(def bnode-re #"^_.*")
(def bnode-name-re "A regex to parse bnodes"
(re-pattern
(str "^"
"_" ;; starts with _
"[:]" ;; followed by colon
"(" ;; start group
".*" ;; anything after the colon
")" ;; end group
)))
(defn bnode-kwi?
"True when `kwi` matches the canonical bnode representation."
[kwi]
(and (keyword? kwi)
(= (namespace kwi) "rdf-app")
(some->> (name kwi)
(str)
(re-matches bnode-name-re))))
(spec/def ::bnode-kwi bnode-kwi?)
(spec/def ::file-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"file" "jar"}))))
(spec/def ::web-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"http" "https"}))))
(defn normalize-bnode-string
"Returns `b`, possibly prepending '_:', checking for match to bnode-name-re"
[b]
{:post [(re-matches bnode-name-re %)]}
(if (re-matches bnode-name-re b)
b
(str "_:" b)))
;;;;;;;;;;;;;;;;;;
;; Vocabulary
;;;;;;;;;;;;;;;;;;
(voc/register-resource-type-context! ::resource-type-context ::voc/resource-type-context)
(defmethod voc/resource-type [::resource-type-context (type "")]
[this]
;; check for a string formatted like a bnode...
(if (re-matches #"^_[:].*" this)
:rdf-app/BnodeString
;; else handle it like any other string....
(let [m (methods voc/resource-type)
f (m [::voc/resource-type-context (type this)])]
(f this))))
(defmethod voc/resource-type [::resource-type-context (type :x)] ;; keyword
[this]
;; Check for a bnode kwi...
(if (bnode-kwi? this)
:rdf-app/BnodeKwi
;; else handle like any other keyword...
(let [m (methods voc/resource-type)
f (m [::voc/resource-type-context (type this)])]
(f this))))
(defmethod voc/as-uri-string :rdf-app/BnodeKwi
[this]
;; Non-re-trippable. Typically appearing in code
(let [[_ parsed-name] (re-matches bnode-name-re (name this))]
(when (not parsed-name)
(throw (ex-info (str "Cound not parse bnode kwi " this)
{:type ::CoundNotParseBnodeKwi
::this this})))
(str "_:" parsed-name)))
(defmethod voc/as-kwi :rdf-app/BnodeString
[this]
{:post [(spec/assert :voc/kwi-spec %)]}
(let [kw-method (get-method voc/as-kwi :voc/Kwi)
default (get-method voc/as-kwi :default)]
(cond
(re-matches bnode-name-re this)
(kw-method (keyword "rdf-app" this ))
:else
(default this))))
(defmethod voc/as-uri-string :rdf-app/BnodeKwi
[this]
(name this))
(defmethod voc/as-kwi :rdf-app/BnodeKwi
[this]
this)
(defmethod voc/as-qname :rdf-app/BnodeKwi
[this]
(voc/as-uri-string this))
;;;;;;;;;;;;;;;;;;
;; INPUT/OUTPUT
;;;;;;;;;;;;;;;;;;
;; KWI/URI conversion for catalog contents
(defn coerce-graph-element
"Returns `x`, possibly coerced to either a kwi or a java.net.URI per `policy`
- where
- `policy` := m s.t. (keys m) :- #{::kwi-if ::uri-if}
- `x` is any candidate as an element in an IGraph
- `kwi-if` := fn [x] -> truthy if `x` should be translated to a keyword id
- `uri-if` := fn [x] -> truthy if `x` should be translated to a java.net.URI
- NOTE: Some implementations of IGraph may be a lot more tolarant of datatypes
in s/p/o position than the URI/URI/URI-or-literal that RDF expects.
"
([x]
(coerce-graph-element {::kwi-if (fn [x] (re-matches (voc/namespace-re) (str x)))
::uri-if (fn [x] (or
(re-matches voc/ordinary-iri-str-re (str x))
(re-matches voc/exceptional-iri-str-re (str x))))
}
x))
([policy x]
(cond
((::kwi-if policy) x)
(if (keyword? x)
x
(voc/as-kwi (str x)))
((::uri-if policy) x)
(if (instance? java.net.URI x)
x
(java.net.URI. (str x)))
:else x
)))
(defn collect-ns-catalog-metadata
"Reducing function outputs `gacc'` given voc metadata assigned to namespace
- NOTE: typically used to initialize the resource catalog.
"
[gacc _prefix ns]
(let [m (voc/get-ns-meta ns)
uri (:vann/preferredNamespaceUri m)
prefix (:vann/preferredNamespacePrefix m)
download-url (:dcat/downloadURL m)
appendix (:voc/appendix m)
]
(if (and download-url appendix)
;; appendix is one or more triples expressed as vectors
(-> gacc
(igraph/add [(coerce-graph-element uri)
:dcat/downloadURL (coerce-graph-element download-url)
:vann/preferredNamespacePrefix prefix
])
(igraph/add (mapv (fn [v] (mapv coerce-graph-element v))
appendix)))
gacc)))
(def resource-catalog
"A native normal graph using this vocabulary:
- [`namespace-uri` :dcat/downloadURL `download-url`]
- [`namespace-uri` :vann/preferredNamespacePrefix `prefix`]
- [`download-url` :dcat/mediaType `media-type`]
- where
- `download-url` is a URL string
- `media-type` := :rdf/type :dct/MediaTypeOrExtent
"
(atom (->> (voc/prefix-to-ns)
(reduce-kv collect-ns-catalog-metadata
(native-normal/make-graph)))))
(defn add-catalog-entry!
"Adds an entry in @resource-catalog for `download-url` `namespace-uri` `prefix` `media-type`
- Where
- `download-url` is a URL (or string) naming a place on the web containing an RDF file
- `namespace-uri` is the primary URI, associated with `prefix`
- `prefix` is the preferred prefix for `namespace-uri`
- `media-type` is the MIME type, of `download-url` eg 'text/turtle'
"
[download-url namespace-uri prefix media-type]
(swap! resource-catalog
igraph/add
[[(coerce-graph-element namespace-uri)
:vann/preferredNamespacePrefix prefix
:dcat/downloadURL (coerce-graph-element download-url)]
[(coerce-graph-element download-url)
:dcat/mediaType media-type
]]))
(def default-io-context
"An atom containing a native-normal graph with default i/o context configurations.
- NOTE: This would typically be the starting point for the i/o context of individual
implementations.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/directory `URL cache directory`]
"
(atom (-> (native-normal/make-graph)
(igraph/add [[:rdf-app/UrlCache
:rdf-app/directory "/tmp/rdf-app/UrlCache"]
]))))
(defn standard-data-transfer-dispatch
"Returns a standard `dispatch-key` for `to-transfer`, defaulting to (type to-transfer)
- Where
- `to-transfer` is typically an argument to the `load-rdf`, `read-rdf` or `write-rdf` methods.
- `dispatch-key` :~ #{:rdf-app/LocalFile, :rdf-app/FileResource :rdf/WebResource}
or the type of `to-transfer`.
- :rdf-app/LocalFile indicates that `to-transfer` is a local path string
- :rdf-app/FileResource indicates that `to-transfer` is a file resource (maybe from a jar)
- :rdf-app/WebResource indicates something accessible through a curl call.
"
[to-transfer]
(cond
(and (string? to-transfer)
(cljc-file-exists? to-transfer))
:rdf-app/LocalFile
(cljc-is-local-file? to-transfer)
:rdf-app/LocalFile
(spec/valid? ::file-resource to-transfer)
:rdf-app/FileResource
(spec/valid? ::web-resource to-transfer)
:rdf-app/WebResource
:else (type to-transfer))
)
(declare load-rdf-dispatch)
(defmulti load-rdf
"Returns a new IGraph with contents for `to-load`,
- args: [`context` `to-load`]
- dispatched on: [`graph-dispatch` `to-load-rdf-dispatch`]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-load` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-load-rdf-dispatch` is the dispatch value derived for `to-load-rdf`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'load-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'load-rdf` :rdf-app/toImportDispatchFn (fn [to-load] -> to-load-dispatch)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'load-rdf` :rdf-app/extensionFn (fn [to-load] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-load`
- [rdf-app/UrlCache rdf-app/directory `cache-directory`]
- [rdf-app/UrlCache rdf-app/cacheMaintenance :rdf-app/DeleteOnRead]
... optional. specifies that a cached file should be deleted after a read.
- by default it will not be deleted.
"
;; There's a tricky circular dependency here in reference to #'load-rdf....
(fn [context to-load] (load-rdf-dispatch context to-load)))
(defn load-rdf-dispatch
"Returns [graph-dispatch to-load-dispatch]. See docstring for `rdf/load-rdf`"
[context to-load]
{:pre [(fn [context _] (context #'load-rdf :rdf-app/hasGraphDispatch))
]
}
(value-trace
::load-rdf-dispatch
[::context context
::to-load to-load
]
;; return [graph-dispatch, to-load-dispatch] ...
[(unique (context #'load-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-load-dispatch (unique (context #'load-rdf :rdf-app/toImportDispatchFn))]
(to-load-dispatch to-load)
;; else no dispatch function was provided
(standard-data-transfer-dispatch to-load))
]))
;; URL caching
(defn cached-file-path
"Returns a canonical path for cached contents read from a URL."
[& {:keys [dir url stem ext]}]
(assert dir)
(str dir "/" stem "_hash=" (hash url) "." ext))
(defn catalog-lookup
"Returns `catalog-entry` for `url`
- Where
- `catalog-entry` := m s.t. (keys m) :~ #{?media-type :?prefix :?suffix :?media-url}
- `url` is a URL that may be in the resource catalog
- `:?prefix` is the preferred prefix associated with `url` (which informs the stem)
- `:?suffix` is the suffix associated with the `:?media-url` (informs the extension)
"
[url]
(let [g (igraph/union @resource-catalog
ontology)
url (coerce-graph-element url)
]
(-> (igraph/query g
[[url :dcat/mediaType :?media-type]
[:?media-url :formats/media_type :?media-type]
[:?media-url :formats/preferred_suffix :?suffix]
[:?namespace-uri :dcat/downloadURL url]
[:?namespace-uri :vann/preferredNamespacePrefix :?prefix]
])
(unique))))
(defn lookup-file-specs-in-catalog
"Returns `file-specs` for `url`
- Where
- `file-specs` := m s.t. (keys m) :~ #{:url :path :stem :ext}
- `url` (as arg) is a URL we may want to get from an http call
- `url` (as key) is the string version of `url`
- `path` is the file path of `url`
- `stem` is the preferred prefix for `url` in the catalog
- `ext` is the file suffix associated with the media type of `url` in the catalog
"
[url]
(when-let [lookup (catalog-lookup url)
]
{:url (str url)
:path (.getPath url)
:stem (:?prefix lookup)
:ext (clojure.string/replace (:?suffix lookup) #"\." "")
}))
(defn http-get-from-catalog
"returns an http response to a GET request for `url`
- Where
- `url` is a URL with an entry in the @`resource-catalog`
"
[url]
(let [lookup (catalog-lookup url)
]
(when lookup
(cljc-http-get (str url)
{:accept (:?media-type lookup)})
)))
(def parse-url-re
"A regex to parse a file URL string with a file name and an extension.
- matches :~ [_ stem ext]
"
(re-pattern
(str "^.*/" ;; start with anything ending in slash
"([^/]+)" ;; at least one non-slash (group 1)
"\\." ;; dot
"(.*)$" ;; any ending, (group 2)
)))
(defn parse-url
"Returns a file specification parsed directly from a URL (not in the catalog), or nil
- where
- `url` is a URL, probably a file resource"
[url]
(let [path (.getPath url)
matches (re-matches parse-url-re path)
]
(when-let [[_ stem ext] matches]
{:url (str url)
:path path
:stem stem
:ext ext
})))
(defn get-cached-file-path-spec
"Returns `m` s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
- Where
- `url` (as arg) is x s.t. (str x) -> a URL string
- `context` is an native-normal graph describing the I/O context
- `url` (as key) is a URL string
- `path` is the path component of `url`
- `stem` is the 'stem portion of /path/to/<stem>.<ext>
- `ext` is the 'ext' portion of /path/to/<stem>.<ext>
- `dir` is the directory containing cache files
- NOTE: this should be sufficient to create a unique temp file path for caching
contents of `url`.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to infer `m` from `url` automatically
Either through `lookup-file-specs-in-catalog` or by parsing `url` itself.
- [:rdf-app/UrlCache :rdf-app/directory `dir`]
- `cached-file-path-fn` := fn (uri) -> `m`
"
[context url]
(value-trace
::get-cached-file-spec
[::context context
::url url
]
(if-let [cached-file-path-fn (unique (context :rdf-app/UrlCache :rdf-app/pathFn))
]
(cached-file-path-fn url)
;; else there is no pathFn, try to parse the URL...
(let [dir (unique (context :rdf-app/UrlCache :rdf-app/directory))
]
(assoc (or (lookup-file-specs-in-catalog url)
(parse-url url))
:dir dir)))))
(defn infer-media-type
"Returns the `media-type` associated with the extension of `url`, if it exists
- Where
- `url` is a URL or URL string
- `media-type` is appropriate for an HTTP 'accept' header, e.g. 'text/turtle'
"
[url]
{:pre [(= (type url) java.net.URL)]}
(->
(igraph/query ontology [[:?media-url
:formats/preferred_suffix (str "."
(-> (parse-url url)
:ext))]
[:?media-url :formats/media_type :?media-type]])
unique
:?media-type))
(defn cache-url-as-local-file
"RETURNS `cached-file`, with contents of `url` loaded
SIDE-EFFECT: creates file named `cached-file` if it does not already exist.
- Where
- `context` is a native-normal graph informed by vocabulary below.
- `url` := a URL or string naming URL
- `cached-file-path` names a local file to contain contents from `url`
- VOCABULARY (for `context`)
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to derive `parse-map` from `url` first by looking
it up in the @`resource-catalog` and then by parsing the `url` itself
- [:rdf-app/UrlCache :rdf-app/directory `cache-directory`]
- `cached-file-path-fn` := fn (uri) -> `parse-map`
- `parse-map` := m s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
"
[context url]
(value-trace
::cache-url-as-local-file
[::context context
::url url
]
(if-let [temp-file-path (some-> (get-cached-file-path-spec context url)
(cached-file-path))
]
(let [cached-file (cljc-make-file temp-file-path)
]
(when (not (and (cljc-file-exists? cached-file)
(> (cljc-file-length cached-file) 0)))
(cljc-make-parents cached-file)
(spit cached-file
(cond
(context url :rdf/type :rdf-app/FileResource)
(slurp url)
(context url :rdf/type :rdf-app/WebResource)
(-> (or (http-get-from-catalog url)
(when-let [media-type (infer-media-type url)]
(-> (cljc-http-get (str url)
{:accept media-type}))))
:body)
:else
(throw (ex-info "Resource type not sufficiently specified in context"
{:type ::ResourceNotSufficientlySpecifiedInContext
::context context
::url url
})))))
cached-file)
;; else no cached-file-path
(throw (ex-info (str "No caching path could be inferred for %s" url)
{:type ::NOCachingPathCouldBeInferredForURL
::context context
::url url
})))))
(defn clear-url-cache!
"Side-effect: deleletes cached local files for `url` in `urls` per `context`, or the whole cache if only `context` is specified.
- Where
- `context` is a native-normal graph informed by vocabulary below.
- `urls` := [`url`, ...]
- `url` is an instance of `java.net.URL`
- VOCABULARY (for `context`)
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to derive `parse-map` from `url` first by looking
it up in the @`resource-catalog` and then by parsing the `url` itself
- [:rdf-app/UrlCache :rdf-app/directory `cache-directory`]
- `cached-file-path-fn` := fn (uri) -> `parse-map`
- `parse-map` := m s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
"
[context & urls]
(let [cache-dir (->> (unique (context :rdf-app/UrlCache :rdf-app/directory))
(io/file))
]
(if (empty? urls)
(doseq [f (filter #(not (.isDirectory %)) (file-seq cache-dir))
]
(io/delete-file f))
;; else we specified which URLs to delete
(doseq [url urls]
(let [to-delete (->> url
(get-cached-file-path-spec context)
(cached-file-path)
(io/file))
]
(if (.exists to-delete)
(io/delete-file to-delete)
;; else it does not exist
(warn ::no-cache-file-to-delete
:glog/message "URL {{url}} is not cached. Nothing to clear."
:url url
::to-delete to-delete)))))))
(defmethod load-rdf [:rdf-app/IGraph :rdf-app/CachedResource]
;; This will make a local copy of the resource and defer to your implementation's
;; to enable (derive <my-Igraph> :rdf-app/IGraph)
[context url]
(->> (cache-url-as-local-file (igraph/add context
[url
:rdf/type
(standard-data-transfer-dispatch url)])
url)
(load-rdf context)))
(defmethod load-rdf :default
[context file-id]
(throw (ex-info "No method for rdf/load-rdf"
{:type ::NoMethodForLoadRdf
::context context
::file file-id
::dispatch (load-rdf-dispatch context file-id)
})))
(declare read-rdf-dispatch)
(defmulti read-rdf
"Side-effect: updates `g` with added contents from `to-read`,
Returns: modified `g`
- args: [context g to-read]
- dispatched on: [graph-dispatch to-read-dispatch]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-read` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-read-dispatch` is the dispatch value derived for `to-read`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'read-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'read-rdf` :rdf-app/toImportDispatchFn (fn [to-read] -> `to-read-dispatch`)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'read-rdf` :rdf-app/extensionFn (fn [to-read] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-read`
"
;; There's a tricky circular dependency here in reference to #'read-rdf....
(fn [context g to-read] (read-rdf-dispatch context g to-read)))
(defn read-rdf-dispatch
"Returns [graph-dispatch to-read-dispatch]. See docstring for `rdf/read-rdf`"
[context g to-read]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'read-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-read-rdf-dispatch
::context context
::g g
::to-read to-read
)
(value-trace
::value-of-read-rdf-dispatch
[::context context
::g g
::to-read to-read
]
;; return vector...
[(unique (context #'read-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-read-dispatch (unique (context #'read-rdf :rdf-app/toImportDispatchFn))]
(to-read-dispatch to-read)
;; else no despatch function was provided
(standard-data-transfer-dispatch to-read))
]))
(defmethod read-rdf [:rdf-app/IGraph :rdf-app/CachedResource]
[context g url]
(->> (cache-url-as-local-file (igraph/add context
[url
:rdf/type
(standard-data-transfer-dispatch url)
]
)
url)
(read-rdf context g)))
(defmethod read-rdf :default
[context g file-id]
(throw (ex-info "No method for rdf/read-rdf"
{:type ::NoMethodForReadRdf
::context context
::g g
::file file-id
::dispatch (read-rdf-dispatch context g file-id)
})))
;; write-rdf
(declare write-rdf-dispatch)
(defmulti write-rdf
"Side-effect: writes contents of `g` to `to-write` in `fmt`,
Returns: modified `g`
- args: [context g to-write fmt]
- dispatched on: [graph-dispatch to-write-dispatch fmt]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-write` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-write-dispatch` is the dispatch value derived for `to-write`
- `fmt` is typically a KWI derived from `:dct/MediaTypeOrExtent`
- VOCABULARY (in `context`)
- [`#'write-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'write-rdf` :rdf-app/toExportDispatchFn (fn [to-write] -> `to-write-dispatch`)]
... optional. Defaults to (type to-write)
"
;; There's a tricky circular dependency here in reference to #'write-rdf....
(fn [context g to-write fmt] (write-rdf-dispatch context g to-write fmt)))
(defn write-rdf-dispatch
"Returns [graph-dispatch to-write-dispatch fmt]. See docstring for `rdf/write-rdf`"
[context g to-write fmt]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'write-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-write-rdf-dispatch
::context context
::g g
::to-write to-write
::fmt fmt
)
(value-trace
::value-of-write-rdf-dispatch
[::context context
::g g
::to-write to-write
::fmt fmt
]
;; return vector...
[(unique (context #'write-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-write-dispatch (unique (context #'write-rdf :rdf-app/toExportDispatchFn))]
(to-write-dispatch to-write)
;; else no despatch function was provided
(standard-data-transfer-dispatch to-write))
,
fmt
]))
(defmethod write-rdf :default
[context g file-id fmt]
(throw (ex-info "No method for rdf/write-rdf"
{:type ::NoMethodForWriteRdf
::context context
::g g
::file file-id
::fmt fmt
::dispatch (write-rdf-dispatch context g file-id fmt)
})))
;;;;;;;;;;;;;;;;;;;;
;; LITERAL SUPPORT
;;;;;;;;;;;;;;;;;;;;
(defn quote-str
"Returns `s`, in escaped quotation marks.
Where
- `s` is a string, typically to be rendered in a query or RDF source.
"
[s]
(str "\"" s "\"")
)
(defn remove-newlines
"Returns `s` with \n removed. Addresses a lot of RDF parse errors."
[s]
(clojure.string/replace s #"\n" " "))
(def transit-write-handlers
"Atom of the form {`Class` `write-handler`, ...}
Where
- `Class`, a symbol, is a direct reference to the class instance to be encoded
- `write-handler` := fn [s] -> {`field` `value`, ...}
"
(atom
#?(:clj
{LangStr
(cognitect.transit/write-handler