/
TriplestoreMessages.scala
848 lines (734 loc) · 27.8 KB
/
TriplestoreMessages.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
/*
* Copyright © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package org.knora.webapi.messages.store.triplestoremessages
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.apache.commons.lang3.StringUtils
import spray.json._
import zio._
import java.nio.file.Path
import java.time.Instant
import scala.collection.mutable
import dsp.errors._
import dsp.valueobjects.V2
import org.knora.webapi._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.SmartIri
import org.knora.webapi.messages.StringFormatter
import org.knora.webapi.messages.store.StoreRequest
import org.knora.webapi.messages.util.ErrorHandlingMap
import org.knora.webapi.messages.util.rdf._
import org.knora.webapi.store.triplestore.domain
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Messages
sealed trait TriplestoreRequest extends StoreRequest
/**
* Simple message for checking the connection to the triplestore.
*/
case class CheckConnection() extends TriplestoreRequest
/**
* Simple message for acknowledging connection check
*/
case class CheckConnectionACK()
/**
* Represents a SPARQL SELECT query to be sent to the triplestore. A successful response will be a [[SparqlSelectResult]].
*
* @param sparql the SPARQL string.
*/
case class SparqlSelectRequest(sparql: String, isGravsearch: Boolean = false) extends TriplestoreRequest
/**
* Represents a SPARQL CONSTRUCT query to be sent to the triplestore. A successful response will be a
* [[SparqlConstructResponse]].
*
* @param sparql the SPARQL string.
*/
case class SparqlConstructRequest(sparql: String) extends TriplestoreRequest
/**
* Represents a SPARQL CONSTRUCT query to be sent to the triplestore. The triplestore's will be
* written to the specified file in a quad format. A successful response message will be a [[FileWrittenResponse]].
*
* @param sparql the SPARQL string.
* @param graphIri the named graph IRI to be used in the TriG file.
* @param outputFile the file to be written.
* @param outputFormat the output file format.
*/
case class SparqlConstructFileRequest(
sparql: String,
graphIri: IRI,
outputFile: Path,
outputFormat: QuadFormat
) extends TriplestoreRequest
/**
* A response to a [[SparqlConstructRequest]].
*
* @param statements a map of subject IRIs to statements about each subject.
*/
case class SparqlConstructResponse(statements: Map[IRI, Seq[(IRI, String)]])
/**
* Represents a SPARQL CONSTRUCT query to be sent to the triplestore. A successful response will be a
* [[SparqlExtendedConstructResponse]].
*
* @param sparql the SPARQL string.
*/
case class SparqlExtendedConstructRequest(sparql: String, isGravsearch: Boolean = false) extends TriplestoreRequest
/**
* Parses Turtle documents and converts them to [[SparqlExtendedConstructResponse]] objects.
*/
object SparqlExtendedConstructResponse {
/**
* A map of predicate IRIs to literal objects.
*/
type ConstructPredicateObjects = Map[SmartIri, Seq[LiteralV2]]
private val logDelimiter = "\n" + StringUtils.repeat('=', 80) + "\n"
/**
* Parses a Turtle document, converting it to a [[SparqlExtendedConstructResponse]].
*
* @param turtleStr the Turtle document.
* @param rdfFormatUtil an [[RdfFormatUtil]].
* @param log a [[Logger]].
* @return a [[SparqlExtendedConstructResponse]] representing the document.
*/
def parseTurtleResponse(
turtleStr: String
): IO[DataConversionException, SparqlExtendedConstructResponse] = {
val rdfFormatUtil: RdfFormatUtil =
RdfFeatureFactory.getRdfFormatUtil()
ZIO.attemptBlocking {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val statementMap: mutable.Map[SubjectV2, ConstructPredicateObjects] = mutable.Map.empty
val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle)
for (st: Statement <- rdfModel) {
val subject: SubjectV2 = st.subj match {
case iriNode: IriNode => IriSubjectV2(iriNode.iri)
case blankNode: BlankNode => BlankNodeSubjectV2(blankNode.id)
}
val predicateIri: SmartIri = st.pred.iri.toSmartIri
val objectLiteral: LiteralV2 = st.obj match {
case iriNode: IriNode => IriLiteralV2(value = iriNode.iri)
case blankNode: BlankNode => BlankNodeLiteralV2(value = blankNode.id)
case literal: RdfLiteral =>
literal match {
case datatypeLiteral: DatatypeLiteral =>
datatypeLiteral.datatype match {
case datatypeIri if OntologyConstants.Xsd.integerTypes.contains(datatypeIri) =>
IntLiteralV2(
datatypeLiteral
.integerValue(
throw InconsistentRepositoryDataException(s"Invalid integer: ${datatypeLiteral.value}")
)
.toInt
)
case OntologyConstants.Xsd.DateTime =>
DateTimeLiteralV2(
stringFormatter.xsdDateTimeStampToInstant(
datatypeLiteral.value,
throw InconsistentRepositoryDataException(s"Invalid xsd:dateTime: ${datatypeLiteral.value}")
)
)
case OntologyConstants.Xsd.Boolean =>
BooleanLiteralV2(
datatypeLiteral.booleanValue(
throw InconsistentRepositoryDataException(s"Invalid xsd:boolean: ${datatypeLiteral.value}")
)
)
case OntologyConstants.Xsd.String => StringLiteralV2(value = datatypeLiteral.value, language = None)
case OntologyConstants.Xsd.Decimal =>
DecimalLiteralV2(
datatypeLiteral.decimalValue(
throw InconsistentRepositoryDataException(s"Invalid xsd:decimal: ${datatypeLiteral.value}")
)
)
case OntologyConstants.Xsd.Uri => IriLiteralV2(datatypeLiteral.value)
case unknown => throw NotImplementedException(s"The literal type '$unknown' is not implemented.")
}
case stringWithLanguage: StringWithLanguage =>
StringLiteralV2(value = stringWithLanguage.value, language = Some(stringWithLanguage.language))
}
}
val currentStatementsForSubject: Map[SmartIri, Seq[LiteralV2]] =
statementMap.getOrElse(subject, Map.empty[SmartIri, Seq[LiteralV2]])
val currentStatementsForPredicate: Seq[LiteralV2] =
currentStatementsForSubject.getOrElse(predicateIri, Seq.empty[LiteralV2])
val updatedPredicateStatements = currentStatementsForPredicate :+ objectLiteral
val updatedSubjectStatements = currentStatementsForSubject + (predicateIri -> updatedPredicateStatements)
statementMap += (subject -> updatedSubjectStatements)
}
SparqlExtendedConstructResponse(statementMap.toMap)
}.foldZIO(
_ =>
ZIO.logError(s"Couldn't parse Turtle document:$logDelimiter$turtleStr$logDelimiter") *>
ZIO.fail(DataConversionException("Couldn't parse Turtle document")),
ZIO.succeed(_)
)
}
}
/**
* A response to a [[SparqlExtendedConstructRequest]].
*
* @param statements a map of subjects to statements about each subject.
*/
case class SparqlExtendedConstructResponse(
statements: Map[SubjectV2, SparqlExtendedConstructResponse.ConstructPredicateObjects]
)
/**
* Requests a named graph, which will be written to the specified file. A successful response
* will be a [[FileWrittenResponse]].
*
* @param graphIri the IRI of the named graph.
* @param outputFile the destination file.
* @param outputFormat the output file format.
*/
case class NamedGraphFileRequest(
graphIri: IRI,
outputFile: Path,
outputFormat: QuadFormat
) extends TriplestoreRequest
/**
* Requests a named graph, which will be returned as Turtle. A successful response
* will be a [[NamedGraphDataResponse]].
*
* @param graphIri the IRI of the named graph.
*/
case class NamedGraphDataRequest(graphIri: IRI) extends TriplestoreRequest
/**
* A graph of triples in Turtle format.
*/
case class NamedGraphDataResponse(turtle: String)
/**
* Represents a SPARQL Update operation to be performed.
*
* @param sparql the SPARQL string.
*/
case class SparqlUpdateRequest(sparql: String) extends TriplestoreRequest
/**
* Indicates that the requested SPARQL Update was executed and returned no errors.
*/
case class SparqlUpdateResponse()
/**
* Represents a SPARQL ASK query to be sent to the triplestore. A successful response will be a
* [[SparqlAskResponse]].
*
* @param sparql the SPARQL string.
*/
case class SparqlAskRequest(sparql: String) extends TriplestoreRequest
/**
* Represents a response to a SPARQL ASK query, containing the result.
*
* @param result of the query.
*/
case class SparqlAskResponse(result: Boolean)
/**
* Message for resetting the contents of the repository and loading a fresh set of data. The data needs to be
* stored in an accessible path and supplied via the [[RdfDataObject]].
*
* @param rdfDataObjects contains a list of [[RdfDataObject]].
* @param prependDefaults denotes if a default set defined in application.conf should be also loaded
*/
case class ResetRepositoryContent(rdfDataObjects: List[RdfDataObject], prependDefaults: Boolean = true)
extends TriplestoreRequest
/**
* Sent as a response to [[ResetRepositoryContent]] if the request was processed successfully.
*/
case class ResetRepositoryContentACK()
/**
* Message for removing all content from the repository.
*/
case class DropAllTRepositoryContent() extends TriplestoreRequest
/**
* Sent as a response to [[DropAllTRepositoryContent]] if the request was processed successfully.
*/
case class DropAllRepositoryContentACK()
/**
* Message for removing all content from the repository.
*/
case class DropDataGraphByGraph() extends TriplestoreRequest
/**
* Sent as a response to [[DropDataGraphByGraph]] if the request was processed successfully.
*/
case class DropDataGraphByGraphACK()
/**
* Inserts data into the repository.
*
* @param rdfDataObjects contains a list of [[RdfDataObject]].
*/
case class InsertRepositoryContent(rdfDataObjects: List[RdfDataObject]) extends TriplestoreRequest
/**
* Sent as a response to [[InsertRepositoryContent]] if the request was processed successfully.
*/
case class InsertTriplestoreContentACK()
/**
* Inserts raw RDF data into the repository.
*
* @param graphContent contains graph data as turtle.
* @param graphName the name of the graph.
*/
case class InsertGraphDataContentRequest(graphContent: String, graphName: String) extends TriplestoreRequest
/**
* Sent as a response to [[InsertGraphDataContentRequest]] if the request was processed successfully.
*/
case class InsertGraphDataContentResponse()
/**
* Initialize the repository. This will initiate the (re)creation of the repository and adding data to it.
*
* @param rdfDataObject contains a list of [[RdfDataObject]].
*/
case class InitRepository(rdfDataObject: RdfDataObject) extends TriplestoreRequest
/**
* Initialization ((re)creation of repository and loading of data) is finished successfully.
*/
case class InitRepositoryACK()
/**
* Ask triplestore if it is ready
*/
case class CheckTriplestoreRequest() extends TriplestoreRequest
/**
* Response indicating whether the triplestore has finished initialization and is ready for processing messages
*
* @param triplestoreStatus the state of the triplestore.
* @param msg further description.
*/
case class CheckTriplestoreResponse(triplestoreStatus: domain.TriplestoreStatus)
/**
* Simulates a triplestore timeout. Used only in testing.
*/
case class SimulateTimeoutRequest() extends TriplestoreRequest
/**
* Requests that the repository is updated to be compatible with the running version of Knora.
*/
case class UpdateRepositoryRequest() extends TriplestoreRequest
/**
* Requests that the repository is downloaded to an N-Quads file. A successful response will be a [[FileWrittenResponse]].
*
* @param outputFile the output file.
*/
case class DownloadRepositoryRequest(outputFile: Path) extends TriplestoreRequest
/**
* Indicates that a file was written successfully.
*/
case class FileWrittenResponse()
/**
* Requests that repository content is uploaded from an N-Quads. A successful response will be a
* [[RepositoryUploadedResponse]].
*
* @param inputFile a TriG file containing the content to be uploaded to the repository.
*/
case class UploadRepositoryRequest(inputFile: Path) extends TriplestoreRequest
/**
* Indicates that repository content was successfully uploaded.
*/
case class RepositoryUploadedResponse()
/**
* Indicates whether the repository is up to date.
*
* @param message a message providing details of what was done.
*/
case class RepositoryUpdatedResponse(message: String) extends TriplestoreRequest
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Components of messages
/**
* Contains the path to the 'ttl' file and the name of the named graph it should be loaded in.
*
* @param path to the 'ttl' file
* @param name of the named graph the data will be load into.
*/
case class RdfDataObject(path: String, name: String)
/**
* Represents the subject of a statement read from the triplestore.
*/
sealed trait SubjectV2
/**
* Represents an IRI used as the subject of a statement.
*/
case class IriSubjectV2(value: IRI) extends SubjectV2 {
override def toString: IRI = value
}
/**
* Represents a blank node identifier used as the subject of a statement.
*/
case class BlankNodeSubjectV2(value: String) extends SubjectV2 {
override def toString: String = value
}
/**
* Represents a literal read from the triplestore. There are different subclasses
* representing literals with the extended type information stored in the triplestore.
*/
sealed trait LiteralV2 {
/**
* Returns this [[LiteralV2]] as an [[IriLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* an [[IriLiteralV2]].
* @return an [[IriLiteralV2]].
*/
def asIriLiteral(errorFun: => Nothing): IriLiteralV2 =
this match {
case iriLiteral: IriLiteralV2 => iriLiteral
case _ => errorFun
}
/**
* Returns this [[LiteralV2]] as a [[StringLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* a [[StringLiteralV2]].
* @return a [[StringLiteralV2]].
*/
def asStringLiteral(errorFun: => Nothing): StringLiteralV2 =
this match {
case stringLiteral: StringLiteralV2 => stringLiteral
case _ => errorFun
}
/**
* Returns this [[LiteralV2]] as a [[BooleanLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* a [[BooleanLiteralV2]].
* @return a [[BooleanLiteralV2]].
*/
def asBooleanLiteral(errorFun: => Nothing): BooleanLiteralV2 =
this match {
case booleanLiteral: BooleanLiteralV2 => booleanLiteral
case _ => errorFun
}
/**
* Returns this [[LiteralV2]] as an [[IntLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* an [[IntLiteralV2]].
* @return an [[IntLiteralV2]].
*/
def asIntLiteral(errorFun: => Nothing): IntLiteralV2 =
this match {
case intLiteral: IntLiteralV2 => intLiteral
case _ => errorFun
}
/**
* Returns this [[LiteralV2]] as a [[DecimalLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* a [[DecimalLiteralV2]].
* @return a [[DecimalLiteralV2]].
*/
def asDecimalLiteral(errorFun: => Nothing): DecimalLiteralV2 =
this match {
case decimalLiteral: DecimalLiteralV2 => decimalLiteral
case _ => errorFun
}
/**
* Returns this [[LiteralV2]] as a [[DateTimeLiteralV2]].
*
* @param errorFun a function that throws an exception. It will be called if this [[LiteralV2]] is not
* a [[DateTimeLiteralV2]].
* @return a [[DateTimeLiteralV2]].
*/
def asDateTimeLiteral(errorFun: => Nothing): DateTimeLiteralV2 =
this match {
case dateTimeLiteral: DateTimeLiteralV2 => dateTimeLiteral
case _ => errorFun
}
}
/**
* Represents a literal read from an ontology in the triplestore.
*/
sealed trait OntologyLiteralV2
/**
* Represents an IRI literal.
*
* @param value the IRI.
*/
case class IriLiteralV2(value: IRI) extends LiteralV2 {
override def toString: IRI = value
}
/**
* Represents an IRI literal as a [[SmartIri]].
*
* @param value the IRI.
*/
case class SmartIriLiteralV2(value: SmartIri) extends OntologyLiteralV2 {
override def toString: IRI = value.toString
def toOntologySchema(targetSchema: OntologySchema): SmartIriLiteralV2 =
SmartIriLiteralV2(value.toOntologySchema(targetSchema))
}
/**
* Represents a blank node identifier.
*
* @param value the identifier of the blank node.
*/
case class BlankNodeLiteralV2(value: String) extends LiteralV2 {
override def toString: String = value
}
/**
* Represents a string with an optional language tag. Allows sorting inside collections by value.
*
* @param value the string value.
* @param language the optional language tag.
*/
case class StringLiteralV2(value: String, language: Option[String] = None)
extends LiteralV2
with OntologyLiteralV2
with Ordered[StringLiteralV2] {
override def toString: String = value
if (language.isDefined && value.isEmpty) {
throw BadRequestException(s"String value is missing.")
}
def compare(that: StringLiteralV2): Int = this.value.compareTo(that.value)
}
/**
* Represents a sequence of [[StringLiteralV2]].
*
* @param stringLiterals a sequence of [[StringLiteralV2]].
*/
case class StringLiteralSequenceV2(stringLiterals: Vector[StringLiteralV2]) {
/**
* Sort sequence of [[StringLiteralV2]] by their text value.
*
* @return a [[StringLiteralSequenceV2]] sorted by string value.
*/
def sortByStringValue: StringLiteralSequenceV2 =
StringLiteralSequenceV2(stringLiterals.sortBy(_.value))
/**
* Sort sequence of [[StringLiteralV2]] by their language value.
*
* @return a [[StringLiteralSequenceV2]] sorted by language value.
*/
def sortByLanguage: StringLiteralSequenceV2 = StringLiteralSequenceV2(stringLiterals.sortBy(_.language))
/**
* Gets the string value of the [[StringLiteralV2]] corresponding to the preferred language.
* If not available, returns the string value of the fallback language or any available language.
*
* @param preferredLang the preferred language.
* @param fallbackLang language to use if preferred language is not available.
*/
def getPreferredLanguage(preferredLang: String, fallbackLang: String): Option[String] = {
val stringLiteralMap: Map[Option[String], String] = stringLiterals.map { case StringLiteralV2(str, lang) =>
lang -> str
}.toMap
stringLiteralMap.get(Some(preferredLang)) match {
// Is the string value available in the user's preferred language?
case Some(strVal: String) =>
// Yes.
Some(strVal)
case None =>
// The string value is not available in the user's preferred language. Is it available
// in the system default language?
stringLiteralMap.get(Some(fallbackLang)) match {
case Some(strValFallbackLang) =>
// Yes.
Some(strValFallbackLang)
case None =>
// The string value is not available in the system default language. Is it available
// without a language tag?
stringLiteralMap.get(None) match {
case Some(strValWithoutLang) =>
// Yes.
Some(strValWithoutLang)
case None =>
// The string value is not available without a language tag. Sort the
// available `StringLiteralV2` by language code to get a deterministic result,
// and return the object in the language with the lowest sort
// order.
stringLiteralMap.toVector.sortBy { case (lang, _) =>
lang
}.headOption.map { case (_, obj) =>
obj
}
}
}
}
}
}
/**
* Represents a boolean value.
*
* @param value the boolean value.
*/
case class BooleanLiteralV2(value: Boolean) extends LiteralV2 with OntologyLiteralV2 {
override def toString: String = value.toString
}
/**
* Represents an integer value.
*
* @param value the integer value.
*/
case class IntLiteralV2(value: Int) extends LiteralV2 {
override def toString: String = value.toString
}
/**
* Represents a decimal value.
*
* @param value the decimal value.
*/
case class DecimalLiteralV2(value: BigDecimal) extends LiteralV2 {
override def toString: String = value.toString
}
/**
* Represents a timestamp.
*
* @param value the timestamp value.
*/
case class DateTimeLiteralV2(value: Instant) extends LiteralV2 {
override def toString: String = value.toString
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// JSON formatting
/**
* A spray-json protocol that parses JSON returned by a SPARQL endpoint. Empty values and empty rows are
* ignored.
*/
object SparqlResultProtocol extends DefaultJsonProtocol {
/**
* Converts a [[JsValue]] to a [[VariableResultsRow]].
*/
implicit object VariableResultsJsonFormat extends JsonFormat[VariableResultsRow] {
def read(jsonVal: JsValue): VariableResultsRow = {
// Collapse the JSON structure into a simpler Map of SPARQL variable names to values.
val mapToWrap: Map[String, String] = jsonVal.asJsObject.fields.foldLeft(Map.empty[String, String]) {
case (acc, (key, value)) =>
value.asJsObject.getFields("value") match {
case Seq(JsString(valueStr)) if valueStr.nonEmpty => // Ignore empty strings.
acc + (key -> valueStr)
case _ => acc
}
}
// Wrap that Map in an ErrorHandlingMap that will gracefully report errors about missing values when they
// are accessed later.
VariableResultsRow(
new ErrorHandlingMap(
mapToWrap,
{ key: String =>
s"No value found for SPARQL query variable '$key' in query result row"
}
)
)
}
def write(variableResultsRow: VariableResultsRow): JsValue = ???
}
/**
* Converts a [[JsValue]] to a [[SparqlSelectResultBody]].
*/
implicit object SparqlSelectResponseBodyFormat extends JsonFormat[SparqlSelectResultBody] {
def read(jsonVal: JsValue): SparqlSelectResultBody =
jsonVal.asJsObject.fields.get("bindings") match {
case Some(bindingsJson: JsArray) =>
// Filter out empty rows.
SparqlSelectResultBody(bindingsJson.convertTo[Seq[VariableResultsRow]].filter(_.rowMap.keySet.nonEmpty))
case _ => SparqlSelectResultBody(Nil)
}
def write(sparqlSelectResponseBody: SparqlSelectResultBody): JsValue = ???
}
implicit val headerFormat: JsonFormat[SparqlSelectResultHeader] = jsonFormat1(SparqlSelectResultHeader)
implicit val responseFormat: JsonFormat[SparqlSelectResult] = jsonFormat2(SparqlSelectResult)
}
/**
* A spray-json protocol for generating Knora API v1 JSON providing data about resources and their properties.
*/
trait TriplestoreJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with NullOptions {
implicit object LiteralV2Format extends JsonFormat[StringLiteralV2] {
/**
* Converts a [[StringLiteralV2]] to a [[JsValue]].
*
* @param string a [[StringLiteralV2]].
* @return a [[JsValue]].
*/
def write(string: StringLiteralV2): JsValue =
if (string.language.isDefined) {
// have language tag
JsObject(
Map(
"value" -> string.value.toJson,
"language" -> string.language.toJson
)
)
} else {
// no language tag
JsObject(
Map(
"value" -> string.value.toJson
)
)
}
/**
* Converts a [[JsValue]] to a [[StringLiteralV2]].
*
* @param json a [[JsValue]].
* @return a [[StringLiteralV2]].
*/
def read(json: JsValue): StringLiteralV2 = json match {
case stringWithLang: JsObject =>
stringWithLang.getFields("value", "language") match {
case Seq(JsString(value), JsString(language)) =>
StringLiteralV2(
value = value,
language = Some(language)
)
case Seq(JsString(value)) =>
StringLiteralV2(
value = value,
language = None
)
case _ =>
throw DeserializationException("JSON object with 'value', or 'value' and 'language' fields expected.")
}
case JsString(value) => StringLiteralV2(value, None)
case _ => throw DeserializationException("JSON object with 'value', or 'value' and 'language' expected. ")
}
}
// TODO-mpro: below object needs to be here because of moving value object to separate project which are also partially used in V2.
// Once dsp.valueobjects.V2.StringLiteralV2 is replaced by LangString value object, it can be removed.
// By then it is quick fix solution.
implicit object V2LiteralV2Format extends JsonFormat[V2.StringLiteralV2] {
/**
* Converts a [[StringLiteralV2]] to a [[JsValue]].
*
* @param string a [[StringLiteralV2]].
* @return a [[JsValue]].
*/
def write(string: V2.StringLiteralV2): JsValue =
if (string.language.isDefined) {
// have language tag
JsObject(
Map(
"value" -> string.value.toJson,
"language" -> string.language.toJson
)
)
} else {
// no language tag
JsObject(
Map(
"value" -> string.value.toJson
)
)
}
/**
* Converts a [[JsValue]] to a [[StringLiteralV2]].
*
* @param json a [[JsValue]].
* @return a [[StringLiteralV2]].
*/
def read(json: JsValue): V2.StringLiteralV2 = json match {
case stringWithLang: JsObject =>
stringWithLang.getFields("value", "language") match {
case Seq(JsString(value), JsString(language)) =>
V2.StringLiteralV2(
value = value,
language = Some(language)
)
case Seq(JsString(value)) =>
V2.StringLiteralV2(
value = value,
language = None
)
case _ =>
throw DeserializationException("JSON object with 'value', or 'value' and 'language' fields expected.")
}
case JsString(value) => V2.StringLiteralV2(value, None)
case _ => throw DeserializationException("JSON object with 'value', or 'value' and 'language' expected. ")
}
}
implicit val rdfDataObjectFormat: RootJsonFormat[RdfDataObject] = jsonFormat2(RdfDataObject)
implicit val resetTriplestoreContentFormat: RootJsonFormat[ResetRepositoryContent] = jsonFormat2(
ResetRepositoryContent
)
}