11package org .codeoverflow .chatoverflow .connector
22
33import akka .actor .{Actor , ActorRef , ActorSystem , Props }
4+ import akka .pattern .ask
5+ import akka .util .Timeout
46import org .codeoverflow .chatoverflow .WithLogger
57import org .codeoverflow .chatoverflow .configuration .Credentials
68
9+ import scala .concurrent .duration ._
10+ import scala .concurrent .{Await , TimeoutException }
711import scala .reflect .ClassTag
812
913/**
@@ -136,14 +140,31 @@ abstract class Connector(val sourceIdentifier: String) extends WithLogger {
136140 */
137141 def stop (): Boolean
138142
143+ /**
144+ * This method can be used to ask an actor for an result, using the akka system as a black box.
145+ *
146+ * @param actor the specific actor to ask. Use <code>createActor()</code> to create your actor.
147+ * @param timeOutInSeconds the timeout to calculate, request, ... for the actor
148+ * @param message some message to pass to the actor. Can be anything.
149+ * @tparam T result type of the actor answer
150+ * @return the answer of the actor if he answers in time. else: None
151+ */
152+ def askActor [T ](actor : ActorRef , timeOutInSeconds : Int , message : Any ): Option [T ] = {
153+ implicit val timeout : Timeout = Timeout (timeOutInSeconds seconds)
154+ val future = actor ? message
155+ try {
156+ Some (Await .result(future, timeout.duration).asInstanceOf [T ])
157+ } catch {
158+ case _ : TimeoutException => None
159+ }
160+ }
161+
139162 /**
140163 * Creates a new actor of the given type and returns the reference. Uses the connector specific actor system.
141164 *
142165 * @tparam T the type of the desired actor (possible trough scala magic)
143166 * @return a actor reference, ready to be used
144167 */
145- protected def createActor [T <: Actor : ClassTag ](): ActorRef
146-
147- =
168+ protected def createActor [T <: Actor : ClassTag ](): ActorRef =
148169 actorSystem.actorOf(Props (implicitly[ClassTag [T ]].runtimeClass))
149170}
0 commit comments