/
ResourcesV1R2RSpec.scala
2269 lines (1829 loc) · 104 KB
/
ResourcesV1R2RSpec.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 © 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.e2e.v1
import akka.actor.ActorSystem
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.testkit.RouteTestTimeout
import akka.pattern._
import org.scalatest.Assertion
import org.xmlunit.builder.DiffBuilder
import org.xmlunit.builder.Input
import org.xmlunit.diff.Diff
import spray.json._
import java.io.ByteArrayInputStream
import java.net.URLEncoder
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import scala.concurrent.Await
import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.Random
import scala.xml.Node
import scala.xml.NodeSeq
import scala.xml.XML
import dsp.errors.AssertionException
import dsp.errors.InvalidApiJsonException
import dsp.errors.NotFoundException
import org.knora.webapi._
import org.knora.webapi.http.directives.DSPApiDirectives
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.util.rdf.SparqlSelectResult
import org.knora.webapi.messages.util.rdf.VariableResultsRow
import org.knora.webapi.messages.v1.responder.resourcemessages.PropsGetForRegionV1
import org.knora.webapi.messages.v1.responder.resourcemessages.ResourceV1JsonProtocol._
import org.knora.webapi.routing.v1.ResourcesRouteV1
import org.knora.webapi.routing.v1.ValuesRouteV1
import org.knora.webapi.routing.v2.ResourcesRouteV2
import org.knora.webapi.sharedtestdata.SharedOntologyTestDataADM._
import org.knora.webapi.sharedtestdata.SharedTestDataADM
import org.knora.webapi.sharedtestdata.SharedTestDataADM._
import org.knora.webapi.store.triplestore.errors.TriplestoreResponseException
import org.knora.webapi.util.AkkaHttpUtils
import org.knora.webapi.util.MutableTestIri
/**
* End-to-end test specification for the resources endpoint.
*/
class ResourcesV1R2RSpec extends R2RSpec {
private val resourcesPathV1 =
DSPApiDirectives.handleErrors(system, appConfig)(new ResourcesRouteV1(routeData).makeRoute)
private val resourcesPathV2 =
DSPApiDirectives.handleErrors(system, appConfig)(new ResourcesRouteV2(routeData, null).makeRoute)
private val valuesPathV1 =
DSPApiDirectives.handleErrors(system, appConfig)(new ValuesRouteV1(routeData).makeRoute)
private val superUser = SharedTestDataADM.superUser
private val superUserEmail = superUser.email
private val imagesUser = SharedTestDataADM.imagesUser01
private val imagesUserEmail = imagesUser.email
private val incunabulaUser = SharedTestDataADM.incunabulaProjectAdminUser
private val incunabulaUserEmail = incunabulaUser.email
private val incunabulaUser2 = SharedTestDataADM.incunabulaCreatorUser
private val incunabulaUserEmail2 = incunabulaUser2.email
private val anythingUser = SharedTestDataADM.anythingUser1
private val anythingUserEmail = anythingUser.email
private val anythingAdmin = SharedTestDataADM.anythingAdminUser
private val anythingAdminEmail = anythingAdmin.email
private val beolUser = SharedTestDataADM.beolUser
private val beolUserEmail = beolUser.email
private val password = SharedTestDataADM.testPass
implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(
appConfig.defaultTimeoutAsDuration * 2
)
implicit val ec: ExecutionContextExecutor = system.dispatcher
override lazy val rdfDataObjects = List(
RdfDataObject(
path = "test_data/ontologies/example-box.ttl",
name = "http://www.knora.org/ontology/shared/example-box"
),
RdfDataObject(
path = "test_data/ontologies/example-ibox.ttl",
name = "http://www.knora.org/ontology/shared/example-ibox"
),
RdfDataObject(
path = "test_data/ontologies/empty-thing-onto.ttl",
name = "http://www.knora.org/ontology/0001/empty-thing"
),
RdfDataObject(path = "test_data/all_data/anything-data.ttl", name = "http://www.knora.org/data/0001/anything"),
RdfDataObject(path = "test_data/demo_data/images-demo-data.ttl", name = "http://www.knora.org/data/00FF/images"),
RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/0803/incunabula")
)
private val firstThingIri = new MutableTestIri
private val firstTextValueIRI = new MutableTestIri
private val secondThingIri = new MutableTestIri
private val thirdThingIri = new MutableTestIri
private val fourthThingIri = new MutableTestIri
private val fifthThingIri = new MutableTestIri
private val sixthThingIri = new MutableTestIri
private val seventhThingIri = new MutableTestIri
private val eighthThingIri = new MutableTestIri
private val abelAuthorIri = new MutableTestIri
private val mathIntelligencerIri = new MutableTestIri
private val deutschesDingIri = new MutableTestIri
private val standoffLangDingIri = new MutableTestIri
private val thingWithString = new MutableTestIri
private val thingWithCreationDate = new MutableTestIri
// incunabula book with title "Eyn biechlin ..."
private val incunabulaBookBiechlin = "http://rdfh.ch/0803/9935159f67"
// incunabula book with title Quadragesimale
private val incunabulaBookQuadra = "http://rdfh.ch/0803/861b5644b302"
private val notTheMostBoringComment = "This is not the most boring comment I have seen."
private val mappingIri = OntologyConstants.KnoraBase.StandardMapping
private val xml1 =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text><strong>Test</strong><br/>text</text>
""".stripMargin
private val xml2 =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text>a <strong>new</strong> value</text>
""".stripMargin
private val xml3 =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text>
| This text links to <a href="http://www.google.ch">Google</a> and a Knora <a class="salsah-link" href="$incunabulaBookBiechlin">resource</a>.
|</text>
""".stripMargin
private val xml4 =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text>
| This text links to <a href="http://www.google.ch">Google</a> and a Knora <a class="salsah-link" href="$incunabulaBookBiechlin">resource</a> and another Knora resource <a class="salsah-link" href="$incunabulaBookQuadra">resource</a>.
|</text>
""".stripMargin
/**
* Gets the field `res_id` from a JSON response to resource creation.
*
* @param response the response sent back from the API.
* @return the value of `res_id`.
*/
private def getResIriFromJsonResponse(response: HttpResponse) =
AkkaHttpUtils.httpResponseToJson(response).fields.get("res_id") match {
case Some(JsString(resourceId)) => resourceId
case None => throw InvalidApiJsonException(s"The response does not contain a field called 'res_id'")
case other =>
throw InvalidApiJsonException(s"The response does not contain a res_id of type JsString, but $other")
}
/**
* Gets the field `id` from a JSON response to value creation (new value).
*
* @param response the response sent back from the API.
* @return the value of `res_id`.
*/
private def getNewValueIriFromJsonResponse(response: HttpResponse) =
AkkaHttpUtils.httpResponseToJson(response).fields.get("id") match {
case Some(JsString(resourceId)) => resourceId
case None => throw InvalidApiJsonException(s"The response does not contain a field called 'res_id'")
case other =>
throw InvalidApiJsonException(s"The response does not contain a res_id of type JsString, but $other")
}
/**
* Gets the given property's values from a resource full response.
*
* @param response the response to a resource full request.
* @param prop the given property IRI.
* @return the property's values.
*/
private def getValuesForProp(response: HttpResponse, prop: IRI): JsValue =
AkkaHttpUtils.httpResponseToJson(response).fields("props").asJsObject.fields(prop).asJsObject.fields("values")
/**
* Gets the given property's comments from a resource full response.
*
* @param response the response to a resource full request.
* @param prop the given property IRI.
* @return the property's comments.
*/
private def getCommentsForProp(response: HttpResponse, prop: IRI): JsValue =
AkkaHttpUtils.httpResponseToJson(response).fields("props").asJsObject.fields(prop).asJsObject.fields("comments")
/**
* Creates a SPARQL query string to get the standoff links (direct links) for a given resource.
*
* @param resIri the resource whose standoff links are to be queried.
* @return SPARQL query string.
*/
private def getDirectLinksSPARQL(resIri: IRI): String =
s"""
|PREFIX knora-base: <http://www.knora.org/ontology/knora-base#>
|
|SELECT ?referredResourceIRI WHERE {
| BIND(IRI("$resIri") as ?resIRI)
| ?resIRI knora-base:hasStandoffLinkTo ?referredResourceIRI .
|}
""".stripMargin
/**
* Creates a SPARQL query to get the standoff links reifications to check for the target resource and the reference count.
*
* @param resIri the resource whose standoff reifications are to be queried.
* @return SPARQL query string.
*/
private def getRefCountsSPARQL(resIri: IRI): String =
s"""
|PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
|PREFIX knora-base: <http://www.knora.org/ontology/knora-base#>
|
|SELECT DISTINCT ?reificationIRI ?object ?refCnt WHERE {
| BIND(IRI("$resIri") as ?resIRI)
| ?resIRI knora-base:hasStandoffLinkToValue ?reificationIRI .
| ?reificationIRI rdf:object ?object .
| ?reificationIRI knora-base:valueHasRefCount ?refCnt .
|}
""".stripMargin
private val search = "/v1/resources?restype_id=http%3A%2F%2Fwww.knora.org%2Fontology%2F0001%2Fanything%23Thing"
private val filter = "&searchstr=value*"
/**
* Test the result of two subsequent requests nearly identical requests
* (used here for requesting different number of properties to be displayed)
* @param search : search query as a string
* @return : nothing, assert is called within this function
*/
private def checkSearchWithDifferentNumberOfProperties(search: String): Assertion =
Get(search) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response)
val resources = responseJson
.fields("resources")
.asInstanceOf[JsArray]
.elements
val labels: Set[String] = resources.map { element =>
element.asJsObject.fields("value").asInstanceOf[JsArray].elements.head.asInstanceOf[JsString].value
}.toSet
val expectedLabels = Set(
"A thing that has a BCE date value",
"A thing that has a list value",
"A thing that has two list values",
"visible thing with hidden int values"
)
assert(expectedLabels.subsetOf(labels))
}
"The Resources Endpoint" should {
"provide a HTML representation of the resource properties " in {
/* Incunabula resources*/
/* A Book without a preview image */
Get(
"/v1/resources.html/http%3A%2F%2Frdfh.ch%2F0803%2Fc5058f3a?noresedit=true&reqtype=properties"
) ~> resourcesPathV1 ~> check {
// log.debug("==>> " + responseAs[String])
assert(status === StatusCodes.OK)
assert(responseAs[String] contains "Physical description")
assert(responseAs[String] contains "Location")
assert(responseAs[String] contains "Publication location")
assert(responseAs[String] contains "URI")
assert(responseAs[String] contains "Title")
assert(responseAs[String] contains "Datum der Herausgabe")
assert(responseAs[String] contains "Citation/reference")
assert(responseAs[String] contains "Publisher")
}
/* A Page with a preview image */
Get(
"/v1/resources.html/http%3A%2F%2Frdfh.ch%2F0803%2Fde6c38ce3401?noresedit=true&reqtype=properties"
) ~> resourcesPathV1 ~> check {
// log.debug("==>> " + responseAs[String])
assert(status === StatusCodes.OK)
assert(responseAs[String] contains "preview")
assert(responseAs[String] contains "Original filename")
assert(responseAs[String] contains "Page identifier")
}
}
"get the regions of a page when doing a context query with resinfo set to true" in {
Get(
"/v1/resources/http%3A%2F%2Frdfh.ch%2F0803%2F9d626dc76c03?resinfo=true&reqtype=context"
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields
val resourceContext: Map[String, JsValue] = responseJson("resource_context").asJsObject.fields
val resinfo: Map[String, JsValue] = resourceContext("resinfo").asJsObject.fields
resinfo.get("regions") match {
case Some(JsArray(regionsVector)) =>
val regions: Vector[PropsGetForRegionV1] = regionsVector.map(_.convertTo[PropsGetForRegionV1])
val region1 = regions.filter { region =>
region.res_id == "http://rdfh.ch/0803/021ec18f1735"
}
val region2 = regions.filter { region =>
region.res_id == "http://rdfh.ch/0803/b6b64a62b006"
}
assert(region1.length == 1, "No region found with Iri 'http://rdfh.ch/0803/021ec18f1735'")
assert(region2.length == 1, "No region found with Iri 'http://rdfh.ch/0803/b6b64a62b006'")
case None => throw AssertionException("No regions given, but 2 were expected")
case _ => throw AssertionException("No valid regions given")
}
}
}
"create a resource of type 'images:person' in 'images' project" in {
val params =
s"""
|{
| "restype_id": "$IMAGES_ONTOLOGY_IRI#person",
| "label": "Testperson",
| "project_id": "$IMAGES_PROJECT_IRI",
| "properties": {
| "$IMAGES_ONTOLOGY_IRI#lastname": [{"richtext_value":{"utf8str":"Testname"}}],
| "$IMAGES_ONTOLOGY_IRI#firstname": [{"richtext_value":{"utf8str":"Name"}}]
| }
|}
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(imagesUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
}
}
"get a resource of type 'knora-base:Resource' with text with standoff" in {
val expectedXML =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text><p>Derselbe Holzschnitt wird auf Seite <a href="http://rdfh.ch/0803/c9824353ae06" class="salsah-link">c7r</a> der lateinischen Ausgabe des Narrenschiffs verwendet.</p></text>
""".stripMargin
Get("/v1/resources/http%3A%2F%2Frdfh.ch%2F0803%2F047db418ae06") ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val text: JsValue = getValuesForProp(response, "http://www.knora.org/ontology/knora-base#hasComment")
val xml: String = text match {
case vals: JsArray =>
vals.elements.head.asJsObject.fields("xml") match {
case JsString(xml: String) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
case _ =>
throw new InvalidApiJsonException("values is not an array")
}
// Compare the original XML with the regenerated XML.
val xmlDiff: Diff = DiffBuilder.compare(Input.fromString(expectedXML)).withTest(Input.fromString(xml)).build()
xmlDiff.hasDifferences should be(false)
}
}
"get a resource of type 'anything:thing' with two text with standoff" in {
val expectedXML1 =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text>Na ja, die <a href="http://rdfh.ch/0001/a-thing" class="salsah-link">Dinge</a> sind OK.</text>
""".stripMargin
val expectedXML2 =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text>Ich liebe die <a href="http://rdfh.ch/0001/a-thing" class="salsah-link">Dinge</a>, sie sind alles für mich.</text>
""".stripMargin
Get("/v1/resources/http%3A%2F%2Frdfh.ch%2F0001%2Fa-thing-with-text-values") ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val text: JsValue = getValuesForProp(response, "http://www.knora.org/ontology/0001/anything#hasText")
val textValues: Seq[JsValue] = text match {
case vals: JsArray =>
vals.elements
case _ =>
throw new InvalidApiJsonException("values is not an array")
}
val xmlStrings: Seq[String] = textValues.map { textVal: JsValue =>
textVal.asJsObject.fields("xml") match {
case JsString(xml: String) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
}
assert(xmlStrings.length == 2)
// determine the index of the first and the second expected text value
val (dingeOk: Int, allesFuerMich: Int) = if (xmlStrings.head.contains("sind OK")) {
// expectedXML1 comes first, expectedXML2 comes second
(0, 1)
} else {
// expectedXML1 comes second, expectedXML2 comes first
(1, 0)
}
// Compare the original XML with the regenerated XML.
val xmlDiff1: Diff =
DiffBuilder.compare(Input.fromString(expectedXML1)).withTest(Input.fromString(xmlStrings(dingeOk))).build()
val xmlDiff2: Diff = DiffBuilder
.compare(Input.fromString(expectedXML2))
.withTest(Input.fromString(xmlStrings(allesFuerMich)))
.build()
xmlDiff1.hasDifferences should be(false)
xmlDiff2.hasDifferences should be(false)
}
}
"perform a search for an anything:Thing matching 'thing'" in {
checkSearchWithDifferentNumberOfProperties(search + filter)
}
"perform a search for an anything:Thing matching 'thing' with 2 numprops displayed" in {
checkSearchWithDifferentNumberOfProperties(search + filter + "&numprops=2")
}
"create a first resource of type anything:Thing" in {
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml": ${xml1.toJson.compactPrint}, "mapping_id": "$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}],
| "http://www.knora.org/ontology/0001/anything#hasTimeStamp": [{"time_value": "2019-08-28T15:13:10.968318Z"}],
| "http://www.knora.org/ontology/0001/anything#hasBoolean": [{"boolean_value":true}]
| }
|}
""".stripMargin
// TODO: these properties have been commented out in the thing test ontology because of compatibility with the GUI
// "http://www.knora.org/ontology/0001/anything#hasGeoname": [{"geoname_value": "2661602"}]
// "http://www.knora.org/ontology/0001/anything#hasGeometry": [{"geom_value":"{\"status\":\"active\",\"lineColor\":\"#ff3333\",\"lineWidth\":2,\"points\":[{\"x\":0.5516074450084602,\"y\":0.4444444444444444},{\"x\":0.2791878172588832,\"y\":0.5}],\"type\":\"rectangle\",\"original_index\":0}"}],
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val resId = getResIriFromJsonResponse(response)
firstThingIri.set(resId)
}
}
"get the created resource and check its standoff in the response" in {
Get("/v1/resources/" + URLEncoder.encode(firstThingIri.get, "UTF-8")) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val text: JsValue = getValuesForProp(response, "http://www.knora.org/ontology/0001/anything#hasText")
val xml: String = text match {
case vals: JsArray =>
vals.elements.head.asJsObject.fields("xml") match {
case JsString(xml: String) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
case _ =>
throw new InvalidApiJsonException("values is not an array")
}
// Compare the original XML with the regenerated XML.
val xmlDiff: Diff = DiffBuilder.compare(Input.fromString(xml1)).withTest(Input.fromString(xml)).build()
xmlDiff.hasDifferences should be(false)
}
}
"create a new text value for the first thing resource" in {
val newValueParams =
s"""
|{
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "res_id": "${firstThingIri.get}",
| "prop": "http://www.knora.org/ontology/0001/anything#hasText",
| "richtext_value": {
| "xml": ${xml2.toJson.compactPrint},
| "mapping_id": "$mappingIri"
| }
|}
""".stripMargin
Post("/v1/values", HttpEntity(ContentTypes.`application/json`, newValueParams)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> valuesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val xml = AkkaHttpUtils.httpResponseToJson(response).fields.get("value") match {
case Some(value: JsObject) =>
value.fields.get("xml") match {
case Some(JsString(xml: String)) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
case _ => throw new InvalidApiJsonException("member 'value' not given")
}
// Compare the original XML with the regenerated XML.
val xmlDiff: Diff = DiffBuilder.compare(Input.fromString(xml2)).withTest(Input.fromString(xml)).build()
xmlDiff.hasDifferences should be(false)
val resId = getNewValueIriFromJsonResponse(response)
firstTextValueIRI.set(resId)
}
}
"change the created text value above for the first thing resource so it has a standoff link to incunabulaBookBiechlin" in {
val xml =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text>a <u>new</u> value with a standoff <a class="salsah-link" href="$incunabulaBookBiechlin">link</a></text>
""".stripMargin
val newValueParams =
s"""
|{
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "richtext_value": {
| "xml": ${xml.toJson.compactPrint},
| "mapping_id": "$mappingIri"
| }
|}
""".stripMargin
Put(
"/v1/values/" + URLEncoder.encode(firstTextValueIRI.get, "UTF-8"),
HttpEntity(ContentTypes.`application/json`, newValueParams)
) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) ~> valuesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val resId = getNewValueIriFromJsonResponse(response)
firstTextValueIRI.set(resId)
}
}
"make sure that the first thing resource contains a direct standoff link to incunabulaBookBiechlin now" in {
val sparqlQuery = getDirectLinksSPARQL(firstThingIri.get)
implicit val timeout = akka.util.Timeout(30.seconds)
Await.result(appActor ? SparqlSelectRequest(sparqlQuery), timeout.duration) match {
case response: SparqlSelectResult =>
val ref: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("referredResourceIRI") == incunabulaBookBiechlin
}
assert(ref, s"No direct link to '$incunabulaBookBiechlin' found")
case _ => throw TriplestoreResponseException("Expected a SparqlSelectResponse")
}
}
"check that the first thing resource's standoff link reification has the correct reference count" in {
val sparqlQuery = getRefCountsSPARQL(firstThingIri.get)
implicit val timeout = akka.util.Timeout(30.seconds)
Await.result(appActor ? SparqlSelectRequest(sparqlQuery), timeout.duration) match {
case response: SparqlSelectResult =>
val refCnt: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("object") == incunabulaBookBiechlin &&
row.rowMap("refCnt").toInt == 1
}
assert(refCnt, s"Ref count for '$incunabulaBookBiechlin' should be 1")
case _ => throw TriplestoreResponseException("Expected a SparqlSelectResponse")
}
}
"create a second resource of type anything:Thing linking to the first thing via standoff" in {
val xml =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text>This text <a class="salsah-link" href="${firstThingIri.get}">links</a> to a thing</text>
""".stripMargin
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A second thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml":${xml.toJson.compactPrint},"mapping_id" :"$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}]
| }
|}
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val resId = getResIriFromJsonResponse(response)
secondThingIri.set(resId)
}
}
"get the second resource of type anything:Thing, containing the correct standoff link" in {
Get("/v1/resources/" + URLEncoder.encode(secondThingIri.get, "UTF-8")) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val text: JsValue = getValuesForProp(response, "http://www.knora.org/ontology/0001/anything#hasText")
val xmlString: String = text match {
case vals: JsArray =>
vals.elements.head.asJsObject.fields("xml") match {
case JsString(xml: String) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
case _ =>
throw new InvalidApiJsonException("values is not an array")
}
// make sure that the xml contains a link to "firstThingIri"
val xml = XML.loadString(xmlString)
val link: NodeSeq = xml \ "a"
assert(link.nonEmpty)
val target: Seq[Node] = link.head.attributes("href")
assert(target.nonEmpty && target.head.text == firstThingIri.get)
}
}
"get the first thing resource that is referred to by the second thing resource" in {
Get("/v1/resources/" + URLEncoder.encode(firstThingIri.get, "UTF-8")) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
// check if this resource is referred to by the second thing resource
val incoming = AkkaHttpUtils.httpResponseToJson(response).fields.get("incoming") match {
case Some(incomingRefs: JsArray) => incomingRefs
case None => throw InvalidApiJsonException(s"The response does not contain a field called 'incoming'")
case other =>
throw InvalidApiJsonException(s"The response does not contain a res_id of type JsObject, but $other")
}
val firstElement = incoming.elements.headOption match {
case Some(incomingRef: JsObject) => incomingRef
case None => throw NotFoundException("Field 'incoming' is empty, but one incoming reference is expected")
case _ => throw InvalidApiJsonException("First element in 'incoming' is not a JsObject")
}
firstElement.fields.get("ext_res_id") match {
case Some(extResObj: JsObject) =>
// get the Iri of the referring resource
val idJsString = extResObj.fields.getOrElse("id", throw InvalidApiJsonException("No member 'id' given"))
// get the Iri of the property pointing to this resource
val propIriJsString =
extResObj.fields.getOrElse("pid", throw InvalidApiJsonException("No member 'pid' given"))
idJsString match {
case JsString(id) =>
assert(id == secondThingIri.get, "This resource should be referred to by the second thing resource")
case _ => throw InvalidApiJsonException("Id is not a JsString")
}
propIriJsString match {
case JsString(pid) =>
assert(
pid == OntologyConstants.KnoraBase.HasStandoffLinkTo,
s"This resource should be referred to by ${OntologyConstants.KnoraBase.HasStandoffLinkTo}"
)
case _ => throw InvalidApiJsonException("pid is not a JsString")
}
case None => throw InvalidApiJsonException("Element in 'incoming' does not have a member 'ext_res_id'")
case _ => throw InvalidApiJsonException("Element in 'incoming' is not a JsObject")
}
}
}
"not create a resource of type thing with an invalid standoff tag name" in {
// use a tag name that is not defined in the standard mapping ("trong" instead of "strong")
val xml =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text>This <trong>text</trong></text>
""".stripMargin
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A second thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml":${xml.toJson.compactPrint}, "mapping_id": "$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}]
| }
|}
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
// the route should reject the request because `trong` is not a tag name supported by the standard mapping
assert(status == StatusCodes.BadRequest, response.toString)
}
}
"not create a resource of type thing submitting a wrong standoff link" in {
val xml =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text><u><strong>This</strong></u> <u>text</u> <a class="salsah-link" href="$incunabulaBookQuadra">links</a> to <a class="salsah-link" href="http://rdfh.ch/0803/9935159f">two</a> things</text>
""".stripMargin
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A second thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml":${xml.toJson.compactPrint},"mapping_id": "$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}]
| }
|}
|
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
// println(response)
// the route should reject the request because an IRI is wrong (formally valid though)
assert(status == StatusCodes.NotFound, response.toString)
}
}
"create a third resource of type thing with two standoff links to the same resource and a standoff link to another one" in {
val firstXML =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text><u><strong>This</strong></u> <u>text</u> <a class="salsah-link" href="$incunabulaBookQuadra">links</a> to a thing</text>
""".stripMargin
val secondXML =
s"""<?xml version="1.0" encoding="UTF-8"?>
|<text><u><strong>This</strong></u> <u>text</u> <a class="salsah-link" href="$incunabulaBookBiechlin">links</a> to the same thing <a class="salsah-link" href="$incunabulaBookBiechlin">twice</a> and to another <a class="salsah-link" href="$incunabulaBookQuadra">thing</a></text>
""".stripMargin
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A second thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml":${firstXML.toJson.compactPrint},"mapping_id": "$mappingIri"}}, {"richtext_value":{"xml":${secondXML.toJson.compactPrint},"mapping_id": "$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}]
| }
|}
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val resId = getResIriFromJsonResponse(response)
thirdThingIri.set(resId)
}
}
"check that the third thing resource has two direct standoff links" in {
val sparqlQuery = getDirectLinksSPARQL(thirdThingIri.get)
implicit val timeout = akka.util.Timeout(30.seconds)
Await.result(appActor ? SparqlSelectRequest(sparqlQuery), timeout.duration) match {
case response: SparqlSelectResult =>
val ref1: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("referredResourceIRI") == incunabulaBookQuadra
}
val ref2: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("referredResourceIRI") == incunabulaBookBiechlin
}
assert(ref1, s"No direct link to '$incunabulaBookQuadra' found")
assert(ref2, s"No direct link to '$incunabulaBookBiechlin' found")
case _ => throw TriplestoreResponseException("Expected a SparqlSelectResponse")
}
}
"check that the third thing resource's standoff link reifications have the correct reference counts" in {
val sparqlQuery = getRefCountsSPARQL(thirdThingIri.get)
implicit val timeout = akka.util.Timeout(30.seconds)
Await.result(appActor ? SparqlSelectRequest(sparqlQuery), timeout.duration) match {
case response: SparqlSelectResult =>
val refCnt1: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("object") == incunabulaBookQuadra &&
row.rowMap("refCnt").toInt == 2
}
val refCnt2: Boolean = response.results.bindings.exists { row: VariableResultsRow =>
row.rowMap("object") == incunabulaBookBiechlin &&
row.rowMap("refCnt").toInt == 1
}
assert(refCnt1, s"Ref count for '$incunabulaBookQuadra' should be 2")
assert(refCnt2, s"Ref count for '$incunabulaBookBiechlin' should be 1")
case _ => throw TriplestoreResponseException("Expected a SparqlSelectResponse")
}
}
"mark a resource as deleted" in {
Delete(
"/v1/resources/http%3A%2F%2Frdfh.ch%2F0803%2F9d626dc76c03?deleteComment=deleted%20for%20testing"
) ~> addCredentials(BasicHttpCredentials(incunabulaUserEmail2, password)) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
}
}
"create a fourth resource of type anything:Thing with a hyperlink in standoff" in {
val xml =
"""<?xml version="1.0" encoding="UTF-8"?>
|<text>This text links to <a href="http://www.google.ch">Google</a>.</text>
""".stripMargin
val params =
s"""
|{
| "restype_id": "http://www.knora.org/ontology/0001/anything#Thing",
| "label": "A second thing",
| "project_id": "http://rdfh.ch/projects/Lw3FC39BSzCwvmdOaTyLqQ",
| "properties": {
| "http://www.knora.org/ontology/0001/anything#hasText": [{"richtext_value":{"xml":${xml.toJson.compactPrint},"mapping_id":"$mappingIri"}}],
| "http://www.knora.org/ontology/0001/anything#hasInteger": [{"int_value":12345}],
| "http://www.knora.org/ontology/0001/anything#hasDecimal": [{"decimal_value":5.6}],
| "http://www.knora.org/ontology/0001/anything#hasUri": [{"uri_value":"http://dhlab.unibas.ch"}],
| "http://www.knora.org/ontology/0001/anything#hasDate": [{"date_value":"JULIAN:1291-08-01:1291-08-01"}],
| "http://www.knora.org/ontology/0001/anything#hasColor": [{"color_value":"#4169E1"}],
| "http://www.knora.org/ontology/0001/anything#hasListItem": [{"hlist_value":"http://rdfh.ch/lists/0001/treeList10"}],
| "http://www.knora.org/ontology/0001/anything#hasInterval": [{"interval_value": [1000000000000000.0000000000000001, 1000000000000000.0000000000000002]}]
| }
|}
""".stripMargin
Post("/v1/resources", HttpEntity(ContentTypes.`application/json`, params)) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val resId = getResIriFromJsonResponse(response)
fourthThingIri.set(resId)
}
}
"get the fourth resource of type anything:Thing, containing the hyperlink in standoff" in {
Get("/v1/resources/" + URLEncoder.encode(fourthThingIri.get, "UTF-8")) ~> addCredentials(
BasicHttpCredentials(anythingUserEmail, password)
) ~> resourcesPathV1 ~> check {
assert(status == StatusCodes.OK, response.toString)
val text: JsValue = getValuesForProp(response, "http://www.knora.org/ontology/0001/anything#hasText")
val xmlString: String = text match {
case vals: JsArray =>
vals.elements.head.asJsObject.fields("xml") match {
case JsString(xml: String) => xml
case _ => throw new InvalidApiJsonException("member 'xml' not given")
}
case _ =>
throw new InvalidApiJsonException("values is not an array")
}
// make sure that the xml contains a link to http://www.google.ch
val xml = XML.loadString(xmlString)