/
JsonLDUtil.scala
1705 lines (1487 loc) · 69.8 KB
/
JsonLDUtil.scala
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
/*
* Copyright © 2015-2018 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi.messages.util.rdf
import java.io.{StringReader, StringWriter}
import java.util
import java.util.UUID
import com.apicatalog.jsonld._
import com.apicatalog.jsonld.document._
import javax.json._
import javax.json.stream.JsonGenerator
import org.apache.commons.lang3.builder.HashCodeBuilder
import org.knora.webapi._
import org.knora.webapi.exceptions._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.store.triplestoremessages.StringLiteralV2
import org.knora.webapi.messages.{OntologyConstants, SmartIri, StringFormatter}
import scala.collection.JavaConverters._
import scala.util.control.Exception._
/*
The classes in this file provide a Scala API for formatting and parsing JSON-LD, and for converting
between JSON-LD documents and RDF models. These classes also provide Knora-specific JSON-LD functionality
to facilitate reading data from Knora API requests and constructing Knora API responses.
The implementation uses the javax.json API and a Java implementation of the JSON-LD API
<https://www.w3.org/TR/json-ld11-api/> (currently <https://github.com/filip26/titanium-json-ld>).
*/
/**
* Constant keywords used in JSON-LD.
*/
object JsonLDKeywords {
val CONTEXT: String = "@context"
val ID: String = "@id"
val TYPE: String = "@type"
val GRAPH: String = "@graph"
val LANGUAGE: String = "@language"
val VALUE: String = "@value"
/**
* The set of JSON-LD keywords that are supported by [[JsonLDUtil]].
*/
val allSupported: Set[String] = Set(CONTEXT, ID, TYPE, GRAPH, LANGUAGE, VALUE)
}
/**
* Represents a value in a JSON-LD document.
*/
sealed trait JsonLDValue extends Ordered[JsonLDValue] {
/**
* Converts this JSON-LD value to a `javax.json` [[JsonValue]].
*/
def toJavaxJsonValue: JsonValue
}
/**
* Represents a string value in a JSON-LD document.
*
* @param value the underlying string.
*/
case class JsonLDString(value: String) extends JsonLDValue {
override def toJavaxJsonValue: JsonString = {
Json.createValue(value)
}
override def compare(that: JsonLDValue): Int = {
that match {
case thatStr: JsonLDString => value.compare(thatStr.value)
case _ => 0
}
}
}
/**
* Represents an integer value in a JSON-LD document.
*
* @param value the underlying integer.
*/
case class JsonLDInt(value: Int) extends JsonLDValue {
override def toJavaxJsonValue: JsonNumber = {
Json.createValue(value)
}
override def compare(that: JsonLDValue): Int = {
that match {
case thatInt: JsonLDInt => value.compare(thatInt.value)
case _ => 0
}
}
}
/**
* Represents a boolean value in a JSON-LD document.
*
* @param value the underlying boolean value.
*/
case class JsonLDBoolean(value: Boolean) extends JsonLDValue {
override def toJavaxJsonValue: JsonValue = {
if (value) {
JsonValue.TRUE
} else {
JsonValue.FALSE
}
}
override def compare(that: JsonLDValue): Int = {
that match {
case thatBoolean: JsonLDBoolean => value.compare(thatBoolean.value)
case _ => 0
}
}
}
/**
* Represents a JSON object in a JSON-LD document.
*
* @param value a map of keys to JSON-LD values.
*/
case class JsonLDObject(value: Map[String, JsonLDValue]) extends JsonLDValue {
override def toJavaxJsonValue: JsonObject = {
val builder = Json.createObjectBuilder()
for ((entryKey, entryValue) <- value) {
builder.add(entryKey, entryValue.toJavaxJsonValue)
}
builder.build
}
/**
* Flattens this JSON-LD object by extracting inlined entities with IRIs and replacing them with
* references to their IRI.
*
* @param entitiesToAddToTopLevel inlined entities that have been extracted.
* @param isAtTopLevel `true` if this JSON-LD object is the top level object, or if it is an element
* of a `@graph`.
* @return a flattened copy of this JSON-LD object.
*/
def flattened(entitiesToAddToTopLevel: collection.mutable.Set[JsonLDObject], isAtTopLevel: Boolean): JsonLDObject = {
val thisWithFlattenedContent = JsonLDObject {
// Flatten the object of each predicate.
value.map {
case (pred: String, obj: JsonLDValue) =>
// What type of object does this predicate have?
val flatObj: JsonLDValue = obj match {
case jsonLDObject: JsonLDObject =>
// A JSON-LD object. Flatten its content. It's not at the top level, so if it has an IRI,
// add it to the top level and refer to it by IRI here.
jsonLDObject.flattened(
entitiesToAddToTopLevel = entitiesToAddToTopLevel,
isAtTopLevel = false
)
case jsonLDArray: JsonLDArray =>
// An array. Flatten its elements. If the array is the object of @graph, don't
// move its elements to the top level, because they're already at the top level.
jsonLDArray.flattened(
entitiesToAddToTopLevel = entitiesToAddToTopLevel,
isAtTopLevel = pred == JsonLDKeywords.GRAPH
)
case _ =>
// Something else. Leave it as is.
obj
}
pred -> flatObj
}
}
// Is this JSON-LD object already at the top level?
if (isAtTopLevel) {
// Yes. Just return it with flattened content.
thisWithFlattenedContent
} else {
// No. Does it have an IRI?
if (isEntityWithIri) {
// Yes. Add it to the top level, and return a reference to its IRI.
entitiesToAddToTopLevel += thisWithFlattenedContent
JsonLDUtil.iriToJsonLDObject(thisWithFlattenedContent.requireString(JsonLDKeywords.ID))
} else {
// No, it's a blank node or some other type of data. Just return it with flattened content.
thisWithFlattenedContent
}
}
}
/**
* Recursively adds the contents of a JSON-LD entity to an [[RdfModel]].
*
* @param model the model being constructed.
* @return the subject of the contents of this JSON-LD object (an IRI or a blank node).
*/
def addToModel(model: RdfModel)
(implicit stringFormatter: StringFormatter): RdfResource = {
val nodeFactory: RdfNodeFactory = model.getNodeFactory
// If this object has an @id, use it as the subject, otherwise generate a blank node ID.
val rdfSubj: RdfResource = maybeStringWithValidation(JsonLDKeywords.ID, stringFormatter.toSmartIriWithErr) match {
case Some(subjectIri: SmartIri) =>
// It's an IRI.
nodeFactory.makeIriNode(subjectIri.toString)
case None =>
// Generate a blank node ID.
nodeFactory.makeBlankNode
}
// Add rdf:type statements to the model.
addRdfTypesToModel(model = model, rdfSubj = rdfSubj)
// If this object contains a @graph, add its contents to the model, without linking to them
// from this object.
addGraphToModel(model)
// Add the IRI predicates and their objects.
val iriPredicates: Set[IRI] = value.keySet -- JsonLDKeywords.allSupported
for (pred: IRI <- iriPredicates) {
val rdfPred: IriNode = nodeFactory.makeIriNode(pred)
val obj: JsonLDValue = value(pred)
addJsonLDValueToModel(
model = model,
rdfSubj = rdfSubj,
rdfPred = rdfPred,
jsonLDValue = obj
)
}
rdfSubj
}
/**
* Adds `rdf:type` statements to an [[RdfModel]] to specify the types of a JSON-LD entity.
*
* @param model the model being constructed.
* @param rdfSubj the subject of this JSON-LD object.
*/
private def addRdfTypesToModel(model: RdfModel,
rdfSubj: RdfResource)
(implicit stringFormatter: StringFormatter): Unit = {
val nodeFactory: RdfNodeFactory = model.getNodeFactory
def addRdfType(typeIri: JsonLDString): Unit = {
model.add(
subj = rdfSubj,
pred = nodeFactory.makeIriNode(OntologyConstants.Rdf.Type),
obj = nodeFactory.makeIriNode(typeIri.value)
)
}
def invalidType: Nothing = throw InvalidJsonLDException("The objects of @type must be strings")
// Does this JSON-LD object have a @type?
value.get(JsonLDKeywords.TYPE) match {
case Some(rdfTypes: JsonLDValue) =>
// Yes. How many types does it have?
rdfTypes match {
case typeIri: JsonLDString =>
// Just one.
addRdfType(typeIri)
case jsonLDArray: JsonLDArray =>
// More than one.
for (elem <- jsonLDArray.value) {
// Is the object of @type a JsonLDString?
elem match {
case typeIri: JsonLDString =>
// Yes. Add the type to the model.
addRdfType(typeIri)
case _ =>
// No. The JSON-LD is invalid.
invalidType
}
}
case _ => invalidType
}
case None =>
// This JSON-LD object doesn't have a @type.
()
}
}
/**
* Adds the contents of `@graph` to an [[RdfModel]].
*
* @param model the model being constructed.
*/
private def addGraphToModel(model: RdfModel)
(implicit stringFormatter: StringFormatter): Unit = {
def invalidGraph: Nothing = throw InvalidJsonLDException("The object of @graph must be a JSON-LD array of JSON-LD objects")
// Does this JSON-LD object have a @graph?
value.get(JsonLDKeywords.GRAPH) match {
case Some(graphContents: JsonLDValue) =>
// Yes. The object of @graph should be an array.
graphContents match {
case jsonLDArray: JsonLDArray =>
// Add each of the array's elements to the model.
for (elem <- jsonLDArray.value) {
// Is the element a JsonLDObject?
elem match {
case jsonLDObject: JsonLDObject =>
// Yes. Add it to the model.
jsonLDObject.addToModel(model)
case _ =>
// No. The JSON-LD is invalid.
invalidGraph
}
}
case _ => invalidGraph
}
case None =>
// This JSON-LD object doesn't have a @graph.
()
}
}
/**
* Recursively adds a [[JsonLDValue]] to an [[RdfModel]], using the specified subject and predicate.
*
* @param model the model being constructed.
* @param rdfSubj the subject.
* @param rdfPred the predicate.
* @param jsonLDValue the value to be added.
*/
private def addJsonLDValueToModel(model: RdfModel,
rdfSubj: RdfResource,
rdfPred: IriNode,
jsonLDValue: JsonLDValue)
(implicit stringFormatter: StringFormatter): Unit = {
val nodeFactory: RdfNodeFactory = model.getNodeFactory
// Which type of JSON-LD value is this?
jsonLDValue match {
case jsonLDObject: JsonLDObject =>
// It's a JSON-LD object. What does it represent?
val rdfObj: RdfNode = if (jsonLDObject.isIri) {
// An IRI.
nodeFactory.makeIriNode(jsonLDObject.requireString(JsonLDKeywords.ID))
} else if (jsonLDObject.isDatatypeValue) {
// A literal.
nodeFactory.makeDatatypeLiteral(
value = jsonLDObject.requireString(JsonLDKeywords.VALUE),
datatype = jsonLDObject.requireString(JsonLDKeywords.TYPE)
)
} else if (jsonLDObject.isStringWithLang) {
// A string literal with a language tag.
nodeFactory.makeStringWithLanguage(
value = jsonLDObject.requireString(JsonLDKeywords.VALUE),
language = jsonLDObject.requireString(JsonLDKeywords.LANGUAGE)
)
} else {
// Triples. Recurse to add its contents to the model.
jsonLDObject.addToModel(model)
}
// Add a triple linking the subject to the object.
model.add(
subj = rdfSubj,
pred = rdfPred,
obj = rdfObj
)
case jsonLDArray: JsonLDArray =>
// It's a JSON-LD array. Recurse to add the contents of each value to the
// model, and to add a triple linking the subject to each value.
for (elem <- jsonLDArray.value) {
addJsonLDValueToModel(
model = model,
rdfSubj = rdfSubj,
rdfPred = rdfPred,
jsonLDValue = elem
)
}
case jsonLDString: JsonLDString =>
// It's a string literal.
model.add(
subj = rdfSubj,
pred = rdfPred,
obj = nodeFactory.makeStringLiteral(jsonLDString.value)
)
case jsonLDBoolean: JsonLDBoolean =>
// It's a boolean literal.
model.add(
rdfSubj,
rdfPred,
nodeFactory.makeBooleanLiteral(jsonLDBoolean.value)
)
case jsonLDInt: JsonLDInt =>
model.add(
subj = rdfSubj,
pred = rdfPred,
obj = nodeFactory.makeDatatypeLiteral(
value = jsonLDInt.value.toString,
datatype = OntologyConstants.Xsd.Integer
)
)
}
}
/**
* Returns `true` if this JSON-LD object represents an RDF entity with an IRI,
* i.e. if it has an `@id` and a `@type`.
*/
def isEntityWithIri: Boolean = {
Set(JsonLDKeywords.ID, JsonLDKeywords.TYPE).subsetOf(value.keySet)
}
/**
* Returns `true` if this JSON-LD object represents an IRI value.
*/
def isIri: Boolean = {
value.keySet == Set(JsonLDKeywords.ID)
}
/**
* Returns `true` if this JSON-LD object represents a string literal with a language tag.
*/
def isStringWithLang: Boolean = {
value.keySet == Set(JsonLDKeywords.VALUE, JsonLDKeywords.LANGUAGE)
}
/**
* Returns `true` if this JSON-LD object represents a datatype value.
*/
def isDatatypeValue: Boolean = {
value.keySet == Set(JsonLDKeywords.TYPE, JsonLDKeywords.VALUE)
}
/**
* Converts an IRI value from its JSON-LD object value representation, validating it using the specified validation
* function.
*
* @param validationFun the validation function.
* @tparam T the type returned by the validation function.
* @return the return value of the validation function.
*/
def toIri[T](validationFun: (String, => Nothing) => T): T = {
if (isIri) {
val id: IRI = requireString(JsonLDKeywords.ID)
validationFun(id, throw BadRequestException(s"Invalid IRI: $id"))
} else {
throw BadRequestException(s"This JSON-LD object does not represent an IRI: $this")
}
}
/**
* Converts a datatype value from its JSON-LD object value representation, validating it using the specified validation
* function.
*
* @param expectedDatatype the IRI of the expected datatype.
* @param validationFun the validation function.
* @tparam T the type returned by the validation function.
* @return the return value of the validation function.
*/
def toDatatypeValueLiteral[T](expectedDatatype: SmartIri, validationFun: (String, => Nothing) => T): T = {
if (isDatatypeValue) {
val datatype: IRI = requireString(JsonLDKeywords.TYPE)
if (datatype != expectedDatatype.toString) {
throw BadRequestException(s"Expected datatype value of type <$expectedDatatype>, found <$datatype>")
}
val value: String = requireString(JsonLDKeywords.VALUE)
validationFun(value, throw BadRequestException(s"Invalid datatype value literal: $value"))
} else {
throw BadRequestException(s"This JSON-LD object does not represent a datatype value: $this")
}
}
/**
* Gets a required string value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not a string.
*
* @param key the key of the required value.
* @return the value.
*/
def requireString(key: String): String = {
value.getOrElse(key, throw BadRequestException(s"No $key provided")) match {
case JsonLDString(str) => str
case other => throw BadRequestException(s"Invalid $key: $other (string expected)")
}
}
/**
* Gets a required string value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not a string.
* Then parses the value with the specified validation function (see [[StringFormatter]]
* for examples of such functions), throwing [[BadRequestException]] if the validation fails.
*
* @param key the key of the required value.
* @param validationFun a validation function that takes two arguments: the string to be validated, and a function
* that throws an exception if the string is invalid. The function's return value is the
* validated string, possibly converted to another type T.
* @tparam T the type of the validation function's return value.
* @return the return value of the validation function.
*/
def requireStringWithValidation[T](key: String, validationFun: (String, => Nothing) => T): T = {
val str: String = requireString(key)
validationFun(str, throw BadRequestException(s"Invalid $key: $str"))
}
/**
* Gets an optional string value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not a string.
*
* @param key the key of the optional value.
* @return the value, or `None` if not found.
*/
def maybeString(key: String): Option[String] = {
value.get(key).map {
case JsonLDString(str) => str
case other => throw BadRequestException(s"Invalid $key: $other (string expected)")
}
}
/**
* Gets an optional string value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not a string. Parses the value with the specified validation
* function (see [[StringFormatter]] for examples of such functions), throwing
* [[BadRequestException]] if the validation fails.
*
* @param key the key of the optional value.
* @param validationFun a validation function that takes two arguments: the string to be validated, and a function
* that throws an exception if the string is invalid. The function's return value is the
* validated string, possibly converted to another type T.
* @tparam T the type of the validation function's return value.
* @return the return value of the validation function, or `None` if the value was not present.
*/
def maybeStringWithValidation[T](key: String, validationFun: (String, => Nothing) => T): Option[T] = {
maybeString(key).map {
str => validationFun(str, throw BadRequestException(s"Invalid $key: $str"))
}
}
/**
* Gets a required IRI value (contained in a JSON-LD object) of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not a JSON-LD object.
* Then parses the object's ID with the specified validation function (see [[StringFormatter]]
* for examples of such functions), throwing [[BadRequestException]] if the validation fails.
*
* @param key the key of the required value.
* @return the validated IRI.
*/
def requireIriInObject[T](key: String, validationFun: (String, => Nothing) => T): T = {
requireObject(key).toIri(validationFun)
}
/**
* Gets an optional IRI value (contained in a JSON-LD object) value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not a JSON-LD object. Parses the object's ID with the
* specified validation function (see [[StringFormatter]] for examples of such functions),
* throwing [[BadRequestException]] if the validation fails.
*
* @param key the key of the optional value.
* @param validationFun a validation function that takes two arguments: the string to be validated, and a function
* that throws an exception if the string is invalid. The function's return value is the
* validated string, possibly converted to another type T.
* @tparam T the type of the validation function's return value.
* @return the return value of the validation function, or `None` if the value was not present.
*/
def maybeIriInObject[T](key: String, validationFun: (String, => Nothing) => T): Option[T] = {
maybeObject(key).map(_.toIri(validationFun))
}
/**
* Gets a required datatype value (contained in a JSON-LD object) of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not a JSON-LD object.
* Then parses the object's literal value with the specified validation function (see [[StringFormatter]]
* for examples of such functions), throwing [[BadRequestException]] if the validation fails.
*
* @param key the key of the required value.
* @param expectedDatatype the IRI of the expected datatype.
* @tparam T the type of the validation function's return value.
* @return the validated literal value.
*/
def requireDatatypeValueInObject[T](key: String, expectedDatatype: SmartIri, validationFun: (String, => Nothing) => T): T = {
requireObject(key).toDatatypeValueLiteral(expectedDatatype, validationFun)
}
/**
* Gets an optional datatype value (contained in a JSON-LD object) value of a property of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not a JSON-LD object. Parses the object's literal value with the
* specified validation function (see [[StringFormatter]] for examples of such functions),
* throwing [[BadRequestException]] if the validation fails.
*
* @param key the key of the optional value.
* @param expectedDatatype the IRI of the expected datatype.
* @param validationFun a validation function that takes two arguments: the string to be validated, and a function
* that throws an exception if the string is invalid. The function's return value is the
* validated string, possibly converted to another type T.
* @tparam T the type of the validation function's return value.
* @return the return value of the validation function, or `None` if the value was not present.
*/
def maybeDatatypeValueInObject[T](key: String, expectedDatatype: SmartIri, validationFun: (String, => Nothing) => T): Option[T] = {
maybeObject(key).map(_.toDatatypeValueLiteral(expectedDatatype, validationFun))
}
/**
* Gets the required object value of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not an object.
*
* @param key the key of the required value.
* @return the required value.
*/
def requireObject(key: String): JsonLDObject = {
value.getOrElse(key, throw BadRequestException(s"No $key provided")) match {
case obj: JsonLDObject => obj
case other => throw BadRequestException(s"Invalid $key: $other (object expected)")
}
}
/**
* Gets the optional object value of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not an object.
*
* @param key the key of the optional value.
* @return the optional value.
*/
def maybeObject(key: String): Option[JsonLDObject] = {
value.get(key).map {
case obj: JsonLDObject => obj
case other => throw BadRequestException(s"Invalid $key: $other (object expected)")
}
}
/**
* Gets the required array value of this JSON-LD object. If the value is not an array,
* returns a one-element array containing the value. Throws
* [[BadRequestException]] if the property is not found.
*
* @param key the key of the required value.
* @return the required value.
*/
def requireArray(key: String): JsonLDArray = {
value.getOrElse(key, throw BadRequestException(s"No $key provided")) match {
case obj: JsonLDArray => obj
case other => JsonLDArray(Seq(other))
}
}
/**
* Gets the optional array value of this JSON-LD object. If the value is not an array,
* returns a one-element array containing the value.
*
* @param key the key of the optional value.
* @return the optional value.
*/
def maybeArray(key: String): Option[JsonLDArray] = {
value.get(key).map {
case obj: JsonLDArray => obj
case other => JsonLDArray(Seq(other))
}
}
/**
* Gets the required integer value of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not an integer.
*
* @param key the key of the required value.
* @return the required value.
*/
def requireInt(key: String): Int = {
value.getOrElse(key, throw BadRequestException(s"No $key provided")) match {
case obj: JsonLDInt => obj.value
case other => throw BadRequestException(s"Invalid $key: $other (integer expected)")
}
}
/**
* Gets the optional integer value of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not an integer.
*
* @param key the key of the optional value.
* @return the optional value.
*/
def maybeInt(key: String): Option[Int] = {
value.get(key).map {
case obj: JsonLDInt => obj.value
case other => throw BadRequestException(s"Invalid $key: $other (integer expected)")
}
}
/**
* Gets the required boolean value of this JSON-LD object, throwing
* [[BadRequestException]] if the property is not found or if its value is not a boolean.
*
* @param key the key of the required value.
* @return the required value.
*/
def requireBoolean(key: String): Boolean = {
value.getOrElse(key, throw BadRequestException(s"No $key provided")) match {
case obj: JsonLDBoolean => obj.value
case other => throw BadRequestException(s"Invalid $key: $other (boolean expected)")
}
}
/**
* Gets the optional boolean value of this JSON-LD object, throwing
* [[BadRequestException]] if the property's value is not a boolean.
*
* @param key the key of the optional value.
* @return the optional value.
*/
def maybeBoolean(key: String): Option[Boolean] = {
value.get(key).map {
case obj: JsonLDBoolean => obj.value
case other => throw BadRequestException(s"Invalid $key: $other (boolean expected)")
}
}
override def compare(that: JsonLDValue): Int = 0
/**
* Validates the `@id` of a JSON-LD object as a Knora data IRI.
*
* @return a validated Knora data IRI.
*/
def requireIDAsKnoraDataIri: SmartIri = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val iri = requireStringWithValidation(JsonLDKeywords.ID, stringFormatter.toSmartIriWithErr)
if (!iri.isKnoraDataIri) {
throw BadRequestException(s"Invalid Knora data IRI: $iri")
}
iri
}
/**
* Validates the optional `@id` of a JSON-LD object as a Knora data IRI.
*
* @return an optional validated Knora data IRI.
*/
def maybeIDAsKnoraDataIri: Option[SmartIri] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val maybeIri: Option[SmartIri] = maybeStringWithValidation(JsonLDKeywords.ID, stringFormatter.toSmartIriWithErr)
maybeIri.foreach {
iri =>
if (!iri.isKnoraDataIri) {
throw BadRequestException(s"Invalid Knora data IRI: $maybeIri")
}
}
maybeIri
}
/**
* Validates an optional Base64-encoded UUID in a JSON-LD object.
*
* @return an optional validated decoded UUID.
*/
def maybeUUID(key: String): Option[UUID] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
maybeStringWithValidation(key, stringFormatter.validateBase64EncodedUuid)
}
/**
* Validates the `@type` of a JSON-LD object as a Knora type IRI in the API v2 complex schema.
*
* @return a validated Knora type IRI.
*/
def requireTypeAsKnoraApiV2ComplexTypeIri: SmartIri = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val typeIri = requireStringWithValidation(JsonLDKeywords.TYPE, stringFormatter.toSmartIriWithErr)
if (!(typeIri.isKnoraEntityIri && typeIri.getOntologySchema.contains(ApiV2Complex))) {
throw BadRequestException(s"Invalid Knora API v2 complex type IRI: $typeIri")
}
typeIri
}
/**
* When called on a JSON-LD object representing a resource, ensures that it contains a single Knora property with
* a single value in the Knora API v2 complex schema.
*
* @return the property IRI and the value.
*/
def requireResourcePropertyApiV2ComplexValue: (SmartIri, JsonLDObject) = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val resourceProps: Map[IRI, JsonLDValue] = value - JsonLDKeywords.ID - JsonLDKeywords.TYPE
if (resourceProps.isEmpty) {
throw BadRequestException("No value submitted")
}
if (resourceProps.size > 1) {
throw BadRequestException(s"Only one value can be submitted per request using this route")
}
resourceProps.head match {
case (key: IRI, jsonLDValue: JsonLDValue) =>
val propertyIri = key.toSmartIriWithErr(throw BadRequestException(s"Invalid property IRI: $key"))
if (!(propertyIri.isKnoraEntityIri && propertyIri.getOntologySchema.contains(ApiV2Complex))) {
throw BadRequestException(s"Invalid Knora API v2 complex property IRI: $propertyIri")
}
jsonLDValue match {
case jsonLDObject: JsonLDObject => propertyIri -> jsonLDObject
case _ => throw BadRequestException(s"Invalid value for $propertyIri")
}
}
}
}
/**
* Represents a JSON array in a JSON-LD document.
*
* @param value a sequence of JSON-LD values.
*/
case class JsonLDArray(value: Seq[JsonLDValue]) extends JsonLDValue {
implicit private val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
override def equals(that: Any): Boolean = {
// Ignore the order of elements when testing equality for this class, since by default,
// order is not significant in JSON-LD arrays (see
// <https://www.w3.org/TR/json-ld11/#terms-imported-from-other-specifications>).
that match {
case otherArray: JsonLDArray => value.toSet == otherArray.value.toSet
case _ => false
}
}
override def hashCode(): Int = {
val hashCodeBuilder = new HashCodeBuilder(21, 41)
for (elem <- value.sorted) {
hashCodeBuilder.append(elem)
}
hashCodeBuilder.toHashCode
}
override def toJavaxJsonValue: JsonArray = {
val builder = Json.createArrayBuilder()
for (elem <- value) {
builder.add(elem.toJavaxJsonValue)
}
builder.build
}
/**
* Flattens this JSON-LD array by extracting inlined entities with IRIs and replacing them with
* references to their IRI.
*
* @param entitiesToAddToTopLevel inlined entities that have been extracted.
* @param isAtTopLevel `true` if this array is the object of `@graph` at the top level of the document.
* @return a flattened copy of this JSON-LD array.
*/
def flattened(entitiesToAddToTopLevel: collection.mutable.Set[JsonLDObject], isAtTopLevel: Boolean = false): JsonLDArray = {
JsonLDArray {
// Flatten the JSON-LD objects that are elements of the array.
value.map {
elem: JsonLDValue =>
// What type of element is it?
elem match {
case jsonLDObject: JsonLDObject =>
// A JSON-LD object. Flatten its content. If it has an IRI, move it to the top level,
// unless this array is a @graph, meaning that the JSON-LD object is already
// at the top level.
jsonLDObject.flattened(
entitiesToAddToTopLevel = entitiesToAddToTopLevel,
isAtTopLevel = isAtTopLevel
)
case _ =>
// Something else. Leave it as is.
elem
}
}
}
}
/**
* Tries to interpret the elements of this array as JSON-LD objects containing `@language` and `@value`,
* and returns the results as a set of [[StringLiteralV2]]. Throws [[BadRequestException]]
* if the array can't be interpreted in this way.
*
* @return a map of language keys to values.
*/
def toObjsWithLang: Seq[StringLiteralV2] = {
value.map {
case obj: JsonLDObject =>
val lang = obj.requireStringWithValidation(JsonLDKeywords.LANGUAGE, stringFormatter.toSparqlEncodedString)
if (!LanguageCodes.SupportedLanguageCodes(lang)) {
throw BadRequestException(s"Unsupported language code: $lang")
}
val text = obj.requireStringWithValidation(JsonLDKeywords.VALUE, stringFormatter.toSparqlEncodedString)
StringLiteralV2(text, Some(lang))
case other => throw BadRequestException(s"Expected JSON-LD object: $other")
}
}
override def compare(that: JsonLDValue): Int = 0
}
/**
* Represents a JSON-LD document.
*
* @param body the body of the JSON-LD document.
* @param context the context of the JSON-LD document.
* @param isFlat `true` if this JSON-LD document has been constructed as a flat document, i.e.
* without inlining entities that have IRIs.
*/
case class JsonLDDocument(body: JsonLDObject,
context: JsonLDObject = JsonLDObject(Map.empty[String, JsonLDValue]),
isFlat: Boolean = false) {
/**
* A convenience function that calls `body.requireString`.
*/
def requireString(key: String): String = body.requireString(key)
/**
* A convenience function that calls `body.requireStringWithValidation`.
*/
def requireStringWithValidation[T](key: String, validationFun: (String, => Nothing) => T): T = body.requireStringWithValidation(key, validationFun)
/**
* A convenience function that calls `body.maybeString`.
*/
def maybeString(key: String): Option[String] = body.maybeString(key)
/**
* A convenience function that calls `body.maybeStringWithValidation`.
*/
def maybeStringWithValidation[T](key: String, validationFun: (String, => Nothing) => T): Option[T] = body.maybeStringWithValidation(key, validationFun)
/**
* A convenience function that calls `body.requireIriInObject`.
*/
def requireIriInObject[T](key: String, validationFun: (String, => Nothing) => T): T = body.requireIriInObject(key, validationFun)
/**
* A convenience function that calls `body.maybeIriInObject`.
*/
def maybeIriInObject[T](key: String, validationFun: (String, => Nothing) => T): Option[T] = body.maybeIriInObject(key, validationFun)
/**
* A convenience function that calls `body.requireDatatypeValueInObject`.
*/
def requireDatatypeValueInObject[T](key: String, expectedDatatype: SmartIri, validationFun: (String, => Nothing) => T): T =
body.requireDatatypeValueInObject(
key = key,
expectedDatatype = expectedDatatype,
validationFun = validationFun
)
/**