summaryrefslogtreecommitdiff
path: root/test/files/jvm/actmig-loop-react.scala
blob: c9a36645264c8f6ef37180bb54b374209b78489e (plain) (blame)
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
/**
 * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change
 * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov.
 */
import scala.actors.Actor._
import scala.actors._
import scala.actors.migration._
import java.util.concurrent.{ TimeUnit, CountDownLatch }
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._
import scala.concurrent.{ Promise, Await }

object Test {
  val finishedLWCR, finishedTNR, finishedEH = Promise[Boolean]
  val finishedLWCR1, finishedTNR1, finishedEH1 = Promise[Boolean]

  def testLoopWithConditionReact() = {
    // Snippet showing composition of receives
    // Loop with Condition Snippet - before
    val myActor = actor {
      var c = true
      loopWhile(c) {
        react {
          case x: Int =>
            // do task
            println("do task")
            if (x == 42) {
              c = false
              finishedLWCR1.success(true)
            }
        }
      }
    }

    myActor.start()
    myActor ! 1
    myActor ! 42

    Await.ready(finishedLWCR1.future, 5 seconds)

    // Loop with Condition Snippet - migrated
    val myAkkaActor = ActorDSL.actor(new StashingActor {

      def receive = {
        case x: Int =>
          // do task
          println("do task")
          if (x == 42) {
            finishedLWCR.success(true)
            context.stop(self)
          }
      }
    })
    myAkkaActor ! 1
    myAkkaActor ! 42
  }

  def testNestedReact() = {
    // Snippet showing composition of receives
    // Loop with Condition Snippet - before
    val myActor = actor {
      var c = true
      loopWhile(c) {
        react {
          case x: Int =>
            // do task
            println("do task " + x)
            if (x == 42) {
              c = false
            } else {
              react {
                case y: String =>
                  println("do string " + y)
              }
            }
            println("after react")
            finishedTNR1.success(true)
        }
      }
    }
    myActor.start()

    myActor ! 1
    myActor ! "I am a String"
    myActor ! 42

    Await.ready(finishedTNR1.future, 5 seconds)

    // Loop with Condition Snippet - migrated
    val myAkkaActor = ActorDSL.actor(new StashingActor {

      def receive = {
        case x: Int =>
          // do task
          println("do task " + x)
          if (x == 42) {
            println("after react")
            finishedTNR.success(true)
            context.stop(self)
          } else
            context.become(({
              case y: String =>
                println("do string " + y)
            }: Receive).andThen(x => {
              unstashAll()
              context.unbecome()
            }).orElse { case x => stash() })
      }
    })

    myAkkaActor ! 1
    myAkkaActor ! "I am a String"
    myAkkaActor ! 42

  }

  def exceptionHandling() = {
    // Stashing actor with act and exception handler
    val myActor = ActorDSL.actor(new StashingActor {

      def receive = { case _ => println("Dummy method.") }
      override def act() = {
        loop {
          react {
            case "fail" =>
              throw new Exception("failed")
            case "work" =>
              println("working")
            case "die" =>
              finishedEH1.success(true)
              exit()
          }
        }
      }

      override def exceptionHandler = {
        case x: Exception => println("scala got exception")
      }

    })

    myActor ! "work"
    myActor ! "fail"
    myActor ! "die"

    Await.ready(finishedEH1.future, 5 seconds)
    // Stashing actor in Akka style
    val myAkkaActor = ActorDSL.actor(new StashingActor {
      def receive = PFCatch({
        case "fail" =>
          throw new Exception("failed")
        case "work" =>
          println("working")
        case "die" =>
          finishedEH.success(true)
          context.stop(self)
      }, { case x: Exception => println("akka got exception") })
    })

    myAkkaActor ! "work"
    myAkkaActor ! "fail"
    myAkkaActor ! "die"
  }

  def main(args: Array[String]): Unit = {
    testLoopWithConditionReact()
    Await.ready(finishedLWCR.future, 5 seconds)
    exceptionHandling()
    Await.ready(finishedEH.future, 5 seconds)
    testNestedReact()
    Await.ready(finishedTNR.future, 5 seconds)
  }

}

// As per Jim Mcbeath's blog (http://jim-mcbeath.blogspot.com/2008/07/actor-exceptions.html)
class PFCatch(f: PartialFunction[Any, Unit],
  handler: PartialFunction[Exception, Unit])
  extends PartialFunction[Any, Unit] {

  def apply(x: Any) = {
    try {
      f(x)
    } catch {
      case e: Exception if handler.isDefinedAt(e) => handler(e)
    }
  }

  def isDefinedAt(x: Any) = f.isDefinedAt(x)
}

object PFCatch {
  def apply(f: PartialFunction[Any, Unit],
    handler: PartialFunction[Exception, Unit]) = new PFCatch(f, handler)
}