alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (TypedActorDocSpec.scala)

This example Akka source code file (TypedActorDocSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, akka, bar, concurrent, exception, foo, future, int, option, squarer, squarerimpl, test, testing, time, typedactor, unit

The TypedActorDocSpec.scala Akka example source code

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */
package docs.actor

import language.postfixOps
import scala.concurrent.{ Promise, Future, Await }
import scala.concurrent.duration._
import akka.actor.{ ActorContext, TypedActor, TypedProps }
import org.scalatest.{ BeforeAndAfterAll, WordSpec }
import org.scalatest.Matchers
import akka.testkit._

//Mr funny man avoids printing to stdout AND keeping docs alright
import java.lang.String.{ valueOf => println }
import akka.actor.ActorRef

//#typed-actor-iface
trait Squarer {
  //#typed-actor-iface-methods
  def squareDontCare(i: Int): Unit //fire-forget

  def square(i: Int): Future[Int] //non-blocking send-request-reply

  def squareNowPlease(i: Int): Option[Int] //blocking send-request-reply

  def squareNow(i: Int): Int //blocking send-request-reply

  @throws(classOf[Exception]) //declare it or you will get an UndeclaredThrowableException
  def squareTry(i: Int): Int //blocking send-request-reply with possible exception
  //#typed-actor-iface-methods
}
//#typed-actor-iface

//#typed-actor-impl
class SquarerImpl(val name: String) extends Squarer {

  def this() = this("default")
  //#typed-actor-impl-methods
  def squareDontCare(i: Int): Unit = i * i //Nobody cares :(

  def square(i: Int): Future[Int] = Future.successful(i * i)

  def squareNowPlease(i: Int): Option[Int] = Some(i * i)

  def squareNow(i: Int): Int = i * i

  def squareTry(i: Int): Int = throw new Exception("Catch me!")
  //#typed-actor-impl-methods
}
//#typed-actor-impl
//#typed-actor-supercharge
trait Foo {
  def doFoo(times: Int): Unit = println("doFoo(" + times + ")")
}

trait Bar {
  def doBar(str: String): Future[String] =
    Future.successful(str.toUpperCase)
}

class FooBar extends Foo with Bar
//#typed-actor-supercharge

class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {

  "get the TypedActor extension" in {
    val someReference: AnyRef = null

    try {
      //#typed-actor-extension-tools

      import akka.actor.TypedActor

      //Returns the Typed Actor Extension
      val extension = TypedActor(system) //system is an instance of ActorSystem

      //Returns whether the reference is a Typed Actor Proxy or not
      TypedActor(system).isTypedActor(someReference)

      //Returns the backing Akka Actor behind an external Typed Actor Proxy
      TypedActor(system).getActorRefFor(someReference)

      //Returns the current ActorContext,
      // method only valid within methods of a TypedActor implementation
      val c: ActorContext = TypedActor.context

      //Returns the external proxy of the current Typed Actor,
      // method only valid within methods of a TypedActor implementation
      val s: Squarer = TypedActor.self[Squarer]

      //Returns a contextual instance of the Typed Actor Extension
      //this means that if you create other Typed Actors with this,
      //they will become children to the current Typed Actor.
      TypedActor(TypedActor.context)

      //#typed-actor-extension-tools
    } catch {
      case e: Exception => //dun care
    }
  }

  "create a typed actor" in {
    //#typed-actor-create1
    val mySquarer: Squarer =
      TypedActor(system).typedActorOf(TypedProps[SquarerImpl]())
    //#typed-actor-create1
    //#typed-actor-create2
    val otherSquarer: Squarer =
      TypedActor(system).typedActorOf(TypedProps(classOf[Squarer],
        new SquarerImpl("foo")), "name")
    //#typed-actor-create2

    //#typed-actor-calls
    //#typed-actor-call-oneway
    mySquarer.squareDontCare(10)
    //#typed-actor-call-oneway

    //#typed-actor-call-future
    val fSquare = mySquarer.square(10) //A Future[Int]
    //#typed-actor-call-future

    //#typed-actor-call-option
    val oSquare = mySquarer.squareNowPlease(10) //Option[Int]
    //#typed-actor-call-option

    //#typed-actor-call-strict
    val iSquare = mySquarer.squareNow(10) //Int
    //#typed-actor-call-strict
    //#typed-actor-calls

    Await.result(fSquare, 3 seconds) should be(100)

    oSquare should be(Some(100))

    iSquare should be(100)

    //#typed-actor-stop
    TypedActor(system).stop(mySquarer)
    //#typed-actor-stop

    //#typed-actor-poisonpill
    TypedActor(system).poisonPill(otherSquarer)
    //#typed-actor-poisonpill
  }

  "proxy any ActorRef" in {
    val actorRefToRemoteActor: ActorRef = system.deadLetters
    //#typed-actor-remote
    val typedActor: Foo with Bar =
      TypedActor(system).
        typedActorOf(
          TypedProps[FooBar],
          actorRefToRemoteActor)
    //Use "typedActor" as a FooBar
    //#typed-actor-remote
  }

  "create hierarchies" in {
    try {
      //#typed-actor-hierarchy
      //Inside your Typed Actor
      val childSquarer: Squarer =
        TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
      //Use "childSquarer" as a Squarer
      //#typed-actor-hierarchy
    } catch {
      case e: Exception => //ignore
    }
  }

  "supercharge" in {
    //#typed-actor-supercharge-usage
    val awesomeFooBar: Foo with Bar =
      TypedActor(system).typedActorOf(TypedProps[FooBar]())

    awesomeFooBar.doFoo(10)
    val f = awesomeFooBar.doBar("yes")

    TypedActor(system).poisonPill(awesomeFooBar)
    //#typed-actor-supercharge-usage
    Await.result(f, 3 seconds) should be("YES")
  }
}

Other Akka source code examples

Here is a short list of links related to this Akka TypedActorDocSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.