/
KnoraSipiIntegrationV2ITSpec.scala
678 lines (564 loc) · 32.1 KB
/
KnoraSipiIntegrationV2ITSpec.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
package org.knora.webapi.e2e.v2
import java.io.File
import java.net.URLEncoder
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.unmarshalling.Unmarshal
import com.typesafe.config.{Config, ConfigFactory}
import org.knora.webapi._
import org.knora.webapi.messages.store.triplestoremessages.{RdfDataObject, TriplestoreJsonProtocol}
import org.knora.webapi.messages.v2.routing.authenticationmessages._
import org.knora.webapi.util.IriConversions._
import org.knora.webapi.util.jsonld._
import org.knora.webapi.util.{MutableTestIri, SmartIri, StringFormatter}
import spray.json._
import scala.concurrent.Await
import scala.concurrent.duration._
object KnoraSipiIntegrationV2ITSpec {
val config: Config = ConfigFactory.parseString(
"""
|akka.loglevel = "DEBUG"
|akka.stdout-loglevel = "DEBUG"
""".stripMargin)
}
/**
* Tests interaction between Knora and Sipi using Knora API v2.
*/
class KnoraSipiIntegrationV2ITSpec extends ITKnoraLiveSpec(KnoraSipiIntegrationV2ITSpec.config) with AuthenticationV2JsonProtocol with TriplestoreJsonProtocol {
private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
private val anythingUserEmail = SharedTestDataADM.anythingUser1.email
private val incunabulaUserEmail = SharedTestDataADM.incunabulaMemberUser.email
private val password = SharedTestDataADM.testPass
private val stillImageResourceIri = new MutableTestIri
private val stillImageFileValueIri = new MutableTestIri
private val pdfResourceIri = new MutableTestIri
private val pdfValueIri = new MutableTestIri
private val marblesOriginalFilename = "marbles.tif"
private val pathToMarbles = s"_test_data/test_route/images/$marblesOriginalFilename"
private val marblesWidth = 1419
private val marblesHeight = 1001
private val pathToMarblesWithWrongExtension = "_test_data/test_route/images/marbles_with_wrong_extension.jpg"
private val trp88OriginalFilename = "Trp88.tiff"
private val pathToTrp88 = s"_test_data/test_route/images/$trp88OriginalFilename"
private val trp88Width = 499
private val trp88Height = 630
private val minimalPdfOriginalFilename = "minimal.pdf"
private val pathToMinimalPdf = s"_test_data/test_route/files/$minimalPdfOriginalFilename"
private val minimalPdfWidth = 1250
private val minimalPdfHeight = 600
private val testPdfOriginalFilename = "test.pdf"
private val pathToTestPdf = s"_test_data/test_route/files/$testPdfOriginalFilename"
private val testPdfWidth = 2480
private val testPdfHeight = 3508
private val csvOriginalFilename = "eggs.csv"
private val pathToCsv = s"_test_data/test_route/files/$csvOriginalFilename"
/**
* Represents a file to be uploaded to Sipi.
*
* @param path the path of the file.
* @param mimeType the MIME type of the file.
*
*/
case class FileToUpload(path: String, mimeType: ContentType)
/**
* Represents an image file to be uploaded to Sipi.
*
* @param fileToUpload the file to be uploaded.
* @param width the image's width in pixels.
* @param height the image's height in pixels.
*/
case class InputFile(fileToUpload: FileToUpload, width: Int, height: Int)
/**
* Represents the information that Sipi returns about each file that has been uploaded.
*
* @param originalFilename the original filename that was submitted to Sipi.
* @param internalFilename Sipi's internal filename for the stored temporary file.
* @param temporaryUrl the URL at which the temporary file can be accessed.
* @param fileType `image`, `text`, or `document`.
*/
case class SipiUploadResponseEntry(originalFilename: String, internalFilename: String, temporaryUrl: String, fileType: String)
/**
* Represents Sipi's response to a file upload request.
*
* @param uploadedFiles the information about each file that was uploaded.
*/
case class SipiUploadResponse(uploadedFiles: Seq[SipiUploadResponseEntry])
object SipiUploadResponseJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
implicit val sipiUploadResponseEntryFormat: RootJsonFormat[SipiUploadResponseEntry] = jsonFormat4(SipiUploadResponseEntry)
implicit val sipiUploadResponseFormat: RootJsonFormat[SipiUploadResponse] = jsonFormat1(SipiUploadResponse)
}
import SipiUploadResponseJsonProtocol._
/**
* Represents the information that Knora returns about an image file value that was created.
*
* @param internalFilename the image's internal filename.
* @param iiifUrl the image's IIIF URL.
* @param width the image's width in pixels.
* @param height the image's height in pixels.
*/
case class SavedImage(internalFilename: String, iiifUrl: String, width: Int, height: Int)
/**
* Represents the information that Knora returns about a document file value that was created.
*
* @param internalFilename the files's internal filename.
* @param url the file's URL.
* @param pageCount the document's page count.
* @param width the document's width in pixels.
* @param height the document's height in pixels.
*/
case class SavedDocument(internalFilename: String, url: String, pageCount: Int, width: Option[Int], height: Option[Int])
/**
* Uploads a file to Sipi and returns the information in Sipi's response.
*
* @param loginToken the login token to be included in the request to Sipi.
* @param filesToUpload the files to be uploaded.
* @return a [[SipiUploadResponse]] representing Sipi's response.
*/
private def uploadToSipi(loginToken: String, filesToUpload: Seq[FileToUpload]): SipiUploadResponse = {
// Make a multipart/form-data request containing the files.
val formDataParts: Seq[Multipart.FormData.BodyPart] = filesToUpload.map {
fileToUpload =>
val fileToSend = new File(fileToUpload.path)
assert(fileToSend.exists(), s"File ${fileToUpload.path} does not exist")
Multipart.FormData.BodyPart(
"file",
HttpEntity.fromPath(fileToUpload.mimeType, fileToSend.toPath),
Map("filename" -> fileToSend.getName)
)
}
val sipiFormData = Multipart.FormData(formDataParts: _*)
// Send Sipi the file in a POST request.
val sipiRequest = Post(s"$baseSipiUrl/upload?token=$loginToken", sipiFormData)
val sipiUploadResponseJson: JsObject = getResponseJson(sipiRequest)
// println(sipiUploadResponseJson.prettyPrint)
val sipiUploadResponse: SipiUploadResponse = sipiUploadResponseJson.convertTo[SipiUploadResponse]
// Request the temporary file from Sipi.
for (responseEntry <- sipiUploadResponse.uploadedFiles) {
val sipiGetTmpFileRequest: HttpRequest = if (responseEntry.fileType == "image") {
Get(responseEntry.temporaryUrl + "/full/full/0/default.jpg")
} else {
Get(responseEntry.temporaryUrl)
}
checkResponseOK(sipiGetTmpFileRequest)
}
sipiUploadResponse
}
/**
* Given a JSON-LD document representing a resource, returns a JSON-LD array containing the values of the specified
* property.
*
* @param resource the JSON-LD document.
* @param propertyIriInResult the property IRI.
* @return a JSON-LD array containing the values of the specified property.
*/
private def getValuesFromResource(resource: JsonLDDocument,
propertyIriInResult: SmartIri): JsonLDArray = {
resource.requireArray(propertyIriInResult.toString)
}
/**
* Given a JSON-LD document representing a resource, returns a JSON-LD object representing the expected single
* value of the specified property.
*
* @param resource the JSON-LD document.
* @param propertyIriInResult the property IRI.
* @param expectedValueIri the IRI of the expected value.
* @return a JSON-LD object representing the expected single value of the specified property.
*/
private def getValueFromResource(resource: JsonLDDocument,
propertyIriInResult: SmartIri,
expectedValueIri: IRI): JsonLDObject = {
val resourceIri: IRI = resource.requireStringWithValidation(JsonLDConstants.ID, stringFormatter.validateAndEscapeIri)
val propertyValues: JsonLDArray = getValuesFromResource(resource = resource, propertyIriInResult = propertyIriInResult)
val matchingValues: Seq[JsonLDObject] = propertyValues.value.collect {
case jsonLDObject: JsonLDObject if jsonLDObject.requireStringWithValidation(JsonLDConstants.ID, stringFormatter.validateAndEscapeIri) == expectedValueIri => jsonLDObject
}
if (matchingValues.isEmpty) {
throw AssertionException(s"Property <$propertyIriInResult> of resource <$resourceIri> does not have value <$expectedValueIri>")
}
if (matchingValues.size > 1) {
throw AssertionException(s"Property <$propertyIriInResult> of resource <$resourceIri> has more than one value with the IRI <$expectedValueIri>")
}
matchingValues.head
}
/**
* Given a JSON-LD object representing a Knora image file value, returns a [[SavedImage]] containing the same information.
*
* @param savedValue a JSON-LD object representing a Knora image file value.
* @return a [[SavedImage]] containing the same information.
*/
private def savedValueToSavedImage(savedValue: JsonLDObject): SavedImage = {
val internalFilename = savedValue.requireString(OntologyConstants.KnoraApiV2Complex.FileValueHasFilename)
val iiifUrl = savedValue.requireDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.FileValueAsUrl,
expectedDatatype = OntologyConstants.Xsd.Uri.toSmartIri,
validationFun = stringFormatter.toSparqlEncodedString
)
val width = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimX)
val height = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimY)
SavedImage(
internalFilename = internalFilename,
iiifUrl = iiifUrl,
width = width,
height = height
)
}
/**
* Given a JSON-LD object representing a Knora document file value, returns a [[SavedImage]] containing the same information.
*
* @param savedValue a JSON-LD object representing a Knora document file value.
* @return a [[SavedDocument]] containing the same information.
*/
private def savedValueToSavedDocument(savedValue: JsonLDObject): SavedDocument = {
val internalFilename = savedValue.requireString(OntologyConstants.KnoraApiV2Complex.FileValueHasFilename)
val url: String = savedValue.requireDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.FileValueAsUrl,
expectedDatatype = OntologyConstants.Xsd.Uri.toSmartIri,
validationFun = stringFormatter.toSparqlEncodedString
)
val pageCount: Int = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasPageCount)
val dimX: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimX)
val dimY: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimY)
SavedDocument(
internalFilename = internalFilename,
url = url,
pageCount = pageCount,
width = dimX,
height = dimY
)
}
"The Knora/Sipi integration" should {
var loginToken: String = ""
"not accept a token in Sipi that hasn't been signed by Knora" in {
val invalidToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJLbm9yYSIsInN1YiI6Imh0dHA6Ly9yZGZoLmNoL3VzZXJzLzlYQkNyRFYzU1JhN2tTMVd3eW5CNFEiLCJhdWQiOlsiS25vcmEiLCJTaXBpIl0sImV4cCI6NDY5NDM1MTEyMiwiaWF0IjoxNTQxNzU5MTIyLCJqdGkiOiJ4bnlYeklFb1QxNmM2dkpDbHhSQllnIn0.P2Aq37G6XMLLBVMdnpDVVhWjenbVw0HTb1BpEuTWGRo"
// The image to be uploaded.
val fileToSend = new File(pathToMarbles)
assert(fileToSend.exists(), s"File $pathToMarbles does not exist")
// A multipart/form-data request containing the image.
val sipiFormData = Multipart.FormData(
Multipart.FormData.BodyPart(
"file",
HttpEntity.fromPath(MediaTypes.`image/tiff`, fileToSend.toPath),
Map("filename" -> fileToSend.getName)
)
)
// Send a POST request to Sipi, asking it to convert the image to JPEG 2000 and store it in a temporary file.
val sipiRequest = Post(s"$baseSipiUrl/upload?token=$invalidToken", sipiFormData)
val sipiResponse = singleAwaitingRequest(sipiRequest)
assert(sipiResponse.status == StatusCodes.Unauthorized)
}
"log in as a Knora user" in {
/* Correct username and correct password */
val params =
s"""
|{
| "email": "$anythingUserEmail",
| "password": "$password"
|}
""".stripMargin
val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params))
val response: HttpResponse = singleAwaitingRequest(request)
assert(response.status == StatusCodes.OK)
val lr: LoginResponse = Await.result(Unmarshal(response.entity).to[LoginResponse], 1.seconds)
loginToken = lr.token
loginToken.nonEmpty should be(true)
logger.debug("token: {}", loginToken)
}
"create a resource with a still image file" in {
// Upload the image to Sipi.
val sipiUploadResponse: SipiUploadResponse =
uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToMarbles, mimeType = MediaTypes.`image/tiff`))
)
val uploadedFile: SipiUploadResponseEntry = sipiUploadResponse.uploadedFiles.head
uploadedFile.originalFilename should ===(marblesOriginalFilename)
// Ask Knora to create the resource.
val jsonLdEntity =
s"""{
| "@type" : "anything:ThingPicture",
| "knora-api:hasStillImageFileValue" : {
| "@type" : "knora-api:StillImageFileValue",
| "knora-api:fileValueHasFilename" : "${uploadedFile.internalFilename}"
| },
| "knora-api:attachedToProject" : {
| "@id" : "http://rdfh.ch/projects/0001"
| },
| "rdfs:label" : "test thing",
| "@context" : {
| "rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "rdfs" : "http://www.w3.org/2000/01/rdf-schema#",
| "xsd" : "http://www.w3.org/2001/XMLSchema#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
val request = Post(s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password))
val responseJsonDoc: JsonLDDocument = getResponseJsonLD(request)
stillImageResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString)
// Get the resource from Knora.
val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(stillImageResourceIri.get, "UTF-8")}")
val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest)
assert(resource.requireTypeAsKnoraTypeIri.toString == "http://0.0.0.0:3333/ontology/0001/anything/v2#ThingPicture")
// Get the new file value from the resource.
val savedValues: JsonLDArray = getValuesFromResource(
resource = resource,
propertyIriInResult = OntologyConstants.KnoraApiV2Complex.HasStillImageFileValue.toSmartIri
)
val savedValue: JsonLDValue = if (savedValues.value.size == 1) {
savedValues.value.head
} else {
throw AssertionException(s"Expected one file value, got ${savedValues.value.size}")
}
val savedValueObj: JsonLDObject = savedValue match {
case jsonLDObject: JsonLDObject => jsonLDObject
case other => throw AssertionException(s"Invalid value object: $other")
}
stillImageFileValueIri.set(savedValueObj.requireIDAsKnoraDataIri.toString)
val savedImage = savedValueToSavedImage(savedValueObj)
assert(savedImage.internalFilename == uploadedFile.internalFilename)
assert(savedImage.width == marblesWidth)
assert(savedImage.height == marblesHeight)
}
"reject an image file with the wrong file extension" in {
val exception = intercept[AssertionException] {
uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToMarblesWithWrongExtension, mimeType = MediaTypes.`image/tiff`))
)
}
assert(exception.getMessage.contains("MIME type and/or file extension are inconsistent"))
}
"change a still image file value" in {
// Upload the image to Sipi.
val sipiUploadResponse: SipiUploadResponse =
uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToTrp88, mimeType = MediaTypes.`image/tiff`))
)
val uploadedFile: SipiUploadResponseEntry = sipiUploadResponse.uploadedFiles.head
uploadedFile.originalFilename should ===(trp88OriginalFilename)
// JSON describing the new image to Knora.
val jsonLdEntity =
s"""{
| "@id" : "${stillImageResourceIri.get}",
| "@type" : "anything:ThingPicture",
| "knora-api:hasStillImageFileValue" : {
| "@id" : "${stillImageFileValueIri.get}",
| "@type" : "knora-api:StillImageFileValue",
| "knora-api:fileValueHasFilename" : "${uploadedFile.internalFilename}"
| },
| "@context" : {
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
// Send the JSON in a PUT request to Knora.
val knoraPostRequest = Put(baseApiUrl + "/v2/values", HttpEntity(ContentTypes.`application/json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password))
val responseJsonDoc = getResponseJsonLD(knoraPostRequest)
stillImageFileValueIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString)
// Get the resource from Knora.
val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(stillImageResourceIri.get, "UTF-8")}")
val resource = getResponseJsonLD(knoraGetRequest)
// Get the new file value from the resource.
val savedValue: JsonLDObject = getValueFromResource(
resource = resource,
propertyIriInResult = OntologyConstants.KnoraApiV2Complex.HasStillImageFileValue.toSmartIri,
expectedValueIri = stillImageFileValueIri.get
)
val savedImage = savedValueToSavedImage(savedValue)
assert(savedImage.internalFilename == uploadedFile.internalFilename)
assert(savedImage.width == trp88Width)
assert(savedImage.height == trp88Height)
// Request the permanently stored image from Sipi.
val sipiGetImageRequest = Get(savedImage.iiifUrl)
checkResponseOK(sipiGetImageRequest)
}
"delete the temporary file if Knora rejects the request to create a file value" in {
// Upload the image to Sipi.
val sipiUploadResponse: SipiUploadResponse = uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToMarbles, mimeType = MediaTypes.`image/tiff`))
)
val internalFilename = sipiUploadResponse.uploadedFiles.head.internalFilename
val temporaryBaseIIIFUrl = sipiUploadResponse.uploadedFiles.head.temporaryUrl
// JSON describing the new image to Knora.
val jsonLdEntity =
s"""{
| "@id" : "${stillImageResourceIri.get}",
| "@type" : "anything:ThingDocument",
| "knora-api:hasStillImageFileValue" : {
| "@type" : "knora-api:StillImageFileValue",
| "knora-api:fileValueHasFilename" : "$internalFilename"
| },
| "@context" : {
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
// Send the JSON in a POST request to Knora.
val knoraPostRequest = Post(baseApiUrl + "/v2/values", HttpEntity(ContentTypes.`application/json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(incunabulaUserEmail, password))
val knoraPostResponse = singleAwaitingRequest(knoraPostRequest)
assert(knoraPostResponse.status == StatusCodes.Forbidden)
// Request the temporary image from Sipi.
val sipiGetTmpFileRequest = Get(temporaryBaseIIIFUrl)
val sipiResponse = singleAwaitingRequest(sipiGetTmpFileRequest)
assert(sipiResponse.status == StatusCodes.NotFound)
}
"create a resource with a PDF file" in {
// Upload the file to Sipi.
val sipiUploadResponse: SipiUploadResponse = uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToMinimalPdf, mimeType = MediaTypes.`application/pdf`))
)
val uploadedFile: SipiUploadResponseEntry = sipiUploadResponse.uploadedFiles.head
uploadedFile.originalFilename should ===(minimalPdfOriginalFilename)
// Ask Knora to create the resource.
val jsonLdEntity =
s"""{
| "@type" : "anything:ThingDocument",
| "knora-api:hasDocumentFileValue" : {
| "@type" : "knora-api:DocumentFileValue",
| "knora-api:fileValueHasFilename" : "${uploadedFile.internalFilename}"
| },
| "knora-api:attachedToProject" : {
| "@id" : "http://rdfh.ch/projects/0001"
| },
| "rdfs:label" : "test thing",
| "@context" : {
| "rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "rdfs" : "http://www.w3.org/2000/01/rdf-schema#",
| "xsd" : "http://www.w3.org/2001/XMLSchema#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
val request = Post(s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password))
val responseJsonDoc: JsonLDDocument = getResponseJsonLD(request)
pdfResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString)
// Get the resource from Knora.
val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(pdfResourceIri.get, "UTF-8")}")
val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest)
assert(resource.requireTypeAsKnoraTypeIri.toString == "http://0.0.0.0:3333/ontology/0001/anything/v2#ThingDocument")
// Get the new file value from the resource.
val savedValues: JsonLDArray = getValuesFromResource(
resource = resource,
propertyIriInResult = OntologyConstants.KnoraApiV2Complex.HasDocumentFileValue.toSmartIri
)
val savedValue: JsonLDValue = if (savedValues.value.size == 1) {
savedValues.value.head
} else {
throw AssertionException(s"Expected one file value, got ${savedValues.value.size}")
}
val savedValueObj: JsonLDObject = savedValue match {
case jsonLDObject: JsonLDObject => jsonLDObject
case other => throw AssertionException(s"Invalid value object: $other")
}
pdfValueIri.set(savedValueObj.requireIDAsKnoraDataIri.toString)
val savedDocument: SavedDocument = savedValueToSavedDocument(savedValueObj)
assert(savedDocument.internalFilename == uploadedFile.internalFilename)
assert(savedDocument.pageCount == 1)
assert(savedDocument.width.contains(minimalPdfWidth))
assert(savedDocument.height.contains(minimalPdfHeight))
}
"change a PDF file value" in {
// Upload the file to Sipi.
val sipiUploadResponse: SipiUploadResponse = uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToTestPdf, mimeType = MediaTypes.`application/pdf`))
)
val uploadedFile: SipiUploadResponseEntry = sipiUploadResponse.uploadedFiles.head
uploadedFile.originalFilename should ===(testPdfOriginalFilename)
// Ask Knora to create the resource.
val jsonLdEntity =
s"""{
| "@id" : "${pdfResourceIri.get}",
| "@type" : "anything:ThingDocument",
| "knora-api:hasDocumentFileValue" : {
| "@id" : "${pdfValueIri.get}",
| "@type" : "knora-api:DocumentFileValue",
| "knora-api:fileValueHasFilename" : "${uploadedFile.internalFilename}"
| },
| "@context" : {
| "rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "rdfs" : "http://www.w3.org/2000/01/rdf-schema#",
| "xsd" : "http://www.w3.org/2001/XMLSchema#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
val request = Put(s"$baseApiUrl/v2/values", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password))
val responseJsonDoc: JsonLDDocument = getResponseJsonLD(request)
pdfValueIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString)
// Get the resource from Knora.
val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(pdfResourceIri.get, "UTF-8")}")
val resource = getResponseJsonLD(knoraGetRequest)
// Get the new file value from the resource.
val savedValue: JsonLDObject = getValueFromResource(
resource = resource,
propertyIriInResult = OntologyConstants.KnoraApiV2Complex.HasDocumentFileValue.toSmartIri,
expectedValueIri = pdfValueIri.get
)
val savedDocument: SavedDocument = savedValueToSavedDocument(savedValue)
assert(savedDocument.internalFilename == uploadedFile.internalFilename)
assert(savedDocument.pageCount == 1)
assert(savedDocument.width.contains(testPdfWidth))
assert(savedDocument.height.contains(testPdfHeight))
}
"create a resource with a CSV file" ignore { // ignored because of https://github.com/dasch-swiss/sipi/issues/309
// Upload the file to Sipi.
val sipiUploadResponse: SipiUploadResponse = uploadToSipi(
loginToken = loginToken,
filesToUpload = Seq(FileToUpload(path = pathToCsv, mimeType = MediaTypes.`text/csv`.toContentType(HttpCharsets.`UTF-8`)))
)
val uploadedFile: SipiUploadResponseEntry = sipiUploadResponse.uploadedFiles.head
uploadedFile.originalFilename should ===(csvOriginalFilename)
// Ask Knora to create the resource.
val jsonLdEntity =
s"""{
| "@type" : "anything:ThingDocument",
| "knora-api:hasDocumentFileValue" : {
| "@type" : "knora-api:DocumentFileValue",
| "knora-api:fileValueHasFilename" : "${uploadedFile.internalFilename}"
| },
| "knora-api:attachedToProject" : {
| "@id" : "http://rdfh.ch/projects/0001"
| },
| "rdfs:label" : "test thing",
| "@context" : {
| "rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
| "knora-api" : "http://api.knora.org/ontology/knora-api/v2#",
| "rdfs" : "http://www.w3.org/2000/01/rdf-schema#",
| "xsd" : "http://www.w3.org/2001/XMLSchema#",
| "anything" : "http://0.0.0.0:3333/ontology/0001/anything/v2#"
| }
|}""".stripMargin
val request = Post(s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLdEntity)) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password))
val responseJsonDoc: JsonLDDocument = getResponseJsonLD(request)
val resourceIri: IRI = responseJsonDoc.body.requireStringWithValidation(JsonLDConstants.ID, stringFormatter.validateAndEscapeIri)
assert(resourceIri.toSmartIri.isKnoraDataIri)
// Get the resource from Knora.
val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}")
val resource = getResponseJsonLD(knoraGetRequest)
// Get the new file value from the resource.
val savedValues: JsonLDArray = getValuesFromResource(
resource = resource,
propertyIriInResult = OntologyConstants.KnoraApiV2Complex.HasDocumentFileValue.toSmartIri
)
val savedValue: JsonLDValue = if (savedValues.value.size == 1) {
savedValues.value.head
} else {
throw AssertionException(s"Expected one file value, got ${savedValues.value.size}")
}
val savedValueObj: JsonLDObject = savedValue match {
case jsonLDObject: JsonLDObject => jsonLDObject
case other => throw AssertionException(s"Invalid value object: $other")
}
val savedDocument: SavedDocument = savedValueToSavedDocument(savedValueObj)
assert(savedDocument.internalFilename == uploadedFile.internalFilename)
assert(savedDocument.pageCount == 1)
assert(savedDocument.width.isEmpty)
assert(savedDocument.height.isEmpty)
}
}
}