/
Responder.scala
189 lines (164 loc) · 6.77 KB
/
Responder.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
/*
* Copyright © 2015-2021 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi
package responders
import exceptions.{DuplicateValueException, UnexpectedMessageException}
import messages.store.triplestoremessages.SparqlSelectRequest
import messages.util.ResponderData
import messages.util.rdf.SparqlSelectResult
import messages.{SmartIri, StringFormatter}
import settings.{KnoraDispatchers, KnoraSettings, KnoraSettingsImpl}
import akka.actor.{ActorRef, ActorSystem}
import akka.event.LoggingAdapter
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import akka.util.Timeout
import com.typesafe.scalalogging.{LazyLogging, Logger}
import org.knora.webapi.store.cacheservice.settings.CacheServiceSettings
import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps
/**
* Responder helper methods.
*/
object Responder {
/**
* An responder use this method to handle unexpected request messages in a consistent way.
*
* @param message the message that was received.
* @param log a [[Logger]].
* @param who the responder receiving the message.
*/
def handleUnexpectedMessage(message: Any, log: Logger, who: String): Future[Nothing] = {
val unexpectedMessageException = UnexpectedMessageException(
s"$who received an unexpected message $message of type ${message.getClass.getCanonicalName}")
FastFuture.failed(unexpectedMessageException)
}
}
/**
* An abstract class providing values that are commonly used in Knora responders.
*/
abstract class Responder(responderData: ResponderData) extends LazyLogging {
/**
* The actor system.
*/
protected implicit val system: ActorSystem = responderData.system
/**
* The execution context for futures created in Knora actors.
*/
protected implicit val executionContext: ExecutionContext =
system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher)
/**
* The application settings.
*/
protected val settings: KnoraSettingsImpl = responderData.knoraSettings
/**
* The Cache Service settings.
*/
protected val cacheServiceSettings: CacheServiceSettings = responderData.cacheServiceSettings
/**
* The main application actor.
*/
protected val appActor: ActorRef = responderData.appActor
/**
* The main application actor forwards messages to the responder manager.
*/
protected val responderManager: ActorRef = responderData.appActor
/**
* The main application actor forwards messages to the store manager.
*/
protected val storeManager: ActorRef = responderData.appActor
/**
* A string formatter.
*/
protected implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
/**
* The application's default timeout for `ask` messages.
*/
protected implicit val timeout: Timeout = settings.defaultTimeout
/**
* Provides logging
*/
protected val log: Logger = logger
protected val loggingAdapter: LoggingAdapter = akka.event.Logging(system, this.getClass)
/**
* Checks whether an entity is used in the triplestore.
*
* @param entityIri the IRI of the entity.
* @param ignoreKnoraConstraints if `true`, ignores the use of the entity in Knora subject or object constraints.
* @param ignoreRdfSubjectAndObject if `true`, ignores the use of the entity in `rdf:subject` and `rdf:object`.
*
* @return `true` if the entity is used.
*/
protected def isEntityUsed(entityIri: SmartIri,
ignoreKnoraConstraints: Boolean = false,
ignoreRdfSubjectAndObject: Boolean = false): Future[Boolean] = {
for {
isEntityUsedSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.isEntityUsed(
triplestore = settings.triplestoreType,
entityIri = entityIri,
ignoreKnoraConstraints = ignoreKnoraConstraints,
ignoreRdfSubjectAndObject = ignoreRdfSubjectAndObject
)
.toString())
isEntityUsedResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isEntityUsedSparql))
.mapTo[SparqlSelectResult]
} yield isEntityUsedResponse.results.bindings.nonEmpty
}
/**
* Throws an exception if an entity is used in the triplestore.
*
* @param entityIri the IRI of the entity.
* @param errorFun a function that throws an exception. It will be called if the entity is used.
* @param ignoreKnoraConstraints if `true`, ignores the use of the entity in Knora subject or object constraints.
* @param ignoreRdfSubjectAndObject if `true`, ignores the use of the entity in `rdf:subject` and `rdf:object`.
*/
protected def throwIfEntityIsUsed(entityIri: SmartIri,
errorFun: => Nothing,
ignoreKnoraConstraints: Boolean = false,
ignoreRdfSubjectAndObject: Boolean = false): Future[Unit] = {
for {
entityIsUsed: Boolean <- isEntityUsed(entityIri, ignoreKnoraConstraints, ignoreRdfSubjectAndObject)
_ = if (entityIsUsed) {
errorFun
}
} yield ()
}
/**
* Checks whether an entity with the provided custom IRI exists in the triplestore, if yes, throws an exception.
* If no custom IRI was given, creates a random unused IRI.
*
* @param entityIri the optional custom IRI of the entity.
* @param iriFormatter the stringFormatter method that must be used to create a random Iri.
* @return IRI of the entity.
*/
protected def checkOrCreateEntityIri(entityIri: Option[SmartIri], iriFormatter: => IRI): Future[IRI] = {
entityIri match {
case Some(customResourceIri) =>
for {
result <- stringFormatter.checkIriExists(customResourceIri.toString, storeManager)
_ = if (result) {
throw DuplicateValueException(s"IRI: '${customResourceIri.toString}' already exists, try another one.")
}
} yield customResourceIri.toString
case None => stringFormatter.makeUnusedIri(iriFormatter, storeManager, loggingAdapter)
}
}
}