scala.util.control.ControlThrowable Scala Examples

The following examples show how to use scala.util.control.ControlThrowable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: TryLoad.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.utils

import scala.util.control.ControlThrowable

object NonFatal {
  def apply(t: Throwable): Boolean = t match {
    case _: LinkageError => true
    case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: ControlThrowable => false
    case _ => true
  }

  def unapply(t: Throwable): Option[Throwable] = if (apply(t)) Some(t) else None
}

sealed trait TryLoad[+A] { self =>

  def map[B](f: A => B): TryLoad[B] =
    self match {
      case Succ(a) => TryLoad(f(a))
      case err: Err[_] => err.asInstanceOf[Err[B]]
    }

  def flatMap[B](f: A => TryLoad[B]): TryLoad[B] =
    self match {
      case Succ(a) => TryLoad(f(a)).flatten
      case err: Err[_] => err.asInstanceOf[Err[B]]
    }

  def flatten[B](implicit ev: A <:< TryLoad[B]): TryLoad[B]

  def orElse[B >: A](f: => TryLoad[B]): TryLoad[B] =
    self match {
      case succ: Succ[_] => succ.asInstanceOf[Succ[B]]
      case err: Err[_] => TryLoad(f).flatten
    }

  def isSuccess: Boolean
  def isFailure: Boolean = !isSuccess

  def get: A
}

object TryLoad {

  def apply[A](f: => A): TryLoad[A] =
    try { Succ(f) } catch {
      case NonFatal(e) => Err(e)
    }

  def fromEither[A](ei: Either[Throwable, A]): TryLoad[A] = ei match {
    case Right(v) => Succ(v)
    case Left(err) => Err(err)
  }

}

final case class Succ[+A](value: A) extends TryLoad[A] {
  def flatten[B](implicit ev: <:<[A, TryLoad[B]]): TryLoad[B] = value
  def isSuccess: Boolean = true
  def get: A = value
}
final case class Err[+A](err: Throwable) extends TryLoad[A] {
  def flatten[B](implicit ev: <:<[A, TryLoad[B]]): TryLoad[B] = this.asInstanceOf[TryLoad[B]]
  def isSuccess: Boolean = false
  def get: A = throw err
} 
Example 2
Source File: ControlThrowable.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.neg

import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.junit.Test

import lacasa.util._

@RunWith(classOf[JUnit4])
class ControlThrowableSpec {
  @Test
  def test1() {
    println(s"ControlThrowableSpec.test1")
    expectError("propagated") {
      """
        class C {
          import scala.util.control.ControlThrowable
          import lacasa.Box._
          def m(): Unit = {
            try {
              val x = 0
              val y = x + 10
              println(s"res: ${x + y}")
            } catch {
              case t: ControlThrowable =>
                println("hello")
                uncheckedCatchControl
            }
          }
        }
      """
    }
  }

  @Test
  def test2() {
    println(s"ControlThrowableSpec.test2")
    expectError("propagated") {
      """
        class C {
          import scala.util.control.ControlThrowable
          def m(): Unit = {
            try {
              throw new ControlThrowable {}
            } catch {
              case t: Throwable =>
                println("hello")
            }
          }
        }
      """
    }
  }

  @Test
  def test3() {
    println(s"ControlThrowableSpec.test3")
    expectError("propagated") {
      """
        class SpecialException(msg: String) extends RuntimeException
        class C {
          import scala.util.control.ControlThrowable
          def m(): Unit = {
            val res = try { 5 } catch {
              case s: SpecialException => println("a")
              case c: ControlThrowable => println("b")
              case t: Throwable => println("c")
            }
          }
        }
      """
    }
  }
} 
Example 3
Source File: Stack1.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.run

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.util.control.ControlThrowable

class Message {
  var arr: Array[Int] = _
}

@RunWith(classOf[JUnit4])
class Stack1Spec {

  import lacasa.Box._

  @Test
  def test1(): Unit = {
    println(s"run.Stack1Spec.test1")
    try {
      mkBox[Message] { packed =>
        implicit val access = packed.access
        packed.box open { msg =>
          msg.arr = Array(1, 2, 3, 4)
        }
      }
    } catch {
      case ct: ControlThrowable =>
        uncheckedCatchControl
        assert(true, "this should not fail!")
    }
  }

} 
Example 4
Source File: Control.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.run

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

@RunWith(classOf[JUnit4])
class ControlSpec {
  import scala.util.control.ControlThrowable
  import lacasa.Box._

  @Test
  def test1(): Unit = {
    println("run.ControlSpec.test1")
    val res = try { 5 } catch {
      case c: ControlThrowable =>
        throw c
      case t: Throwable =>
        println("hello")
    }
    assert(res == 5, "this should not fail")
  }

} 
Example 5
Source File: Transfer.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.samples

import scala.concurrent.ExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global

import scala.util.control.ControlThrowable

import lacasa.{System, Box, CanAccess, Actor, ActorRef, doNothing}
import Box._

import scala.spores._


class Sneaky { // not ocap!
  def process(a: Array[Int]): Unit = {
    SomeObject.fld = a
  }
}

class NonSneaky {
  def process(a: Array[Int]): Unit = {
    for (i <- 0 until a.length)
      a(i) = a(i) + 1
  }
}

class ActorA extends Actor[Any] {
  override def receive(box: Box[Any])
      (implicit acc: CanAccess { type C = box.C }) {
    box open {
      case s: Start =>
        mkBox[Message] { packed =>
          implicit val access = packed.access
          packed.box open { msg =>
            msg.arr = Array(1, 2, 3, 4)
          }
          s.next.send(packed.box) {
            doNothing.consume(packed.box)
          }
        }
      case other => // ...
    }
  }
}

class ActorB extends Actor[Message] {
  override def receive(box: Box[Message])
      (implicit acc: CanAccess { type C = box.C }) {
    box open { msg =>
      println(msg.arr.mkString(","))
    }
  }
}

class Message {
  var arr: Array[Int] = _
  def leak(): Unit = {
    //SomeObject.fld = arr
  }
}

object SomeObject {
  var fld: Array[Int] = _
}

class Start {
  var next: ActorRef[Message] = _
}

// expected output:
// 1,2,3,4
object Transfer {

  def main(args: Array[String]): Unit = try {
    val sys = System()
    val a = sys.actor[ActorA, Any]

    // LaCasa plugin checks that `Start` is an ocap class
    mkBox[Start] { packed =>
      import packed.access
      val box: packed.box.type = packed.box

      // initialize object in box
      box.open(spore { obj =>
        val innerSys = System()
        obj.next = innerSys.actor[ActorB, Message]
      })

      a.send(box) { doNothing.consume(box) }
    }
  } catch {
    case t: ControlThrowable =>
      uncheckedCatchControl
      Thread.sleep(1000)
  }

} 
Example 6
Source File: ActorWithField.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.samples.actorwithfield

import scala.concurrent.ExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global

import scala.util.control.ControlThrowable

import lacasa.{System, Box, CanAccess, Actor, ActorRef, doNothing, Packed}
import Box._

import scala.spores._
import SporeConv._


class Start {
  var next: ActorRef[Message] = _
}

class Message {
  var l: List[Int] = List()
}


class ActorA extends Actor[Start] {

  override def receive(box: Box[Start])(implicit acc: CanAccess { type C = box.C }) {
    box open { s =>
      mkBox[Message] { packed =>
        implicit val access = packed.access

        packed.box open { msg =>
          msg.l = List(2, 4, 6)
        }

        s.next.send(packed.box) {
          doNothing.consume(packed.box)
        }
      }
    }
  }

}

class Data {
  var l: List[Int] = List(1)
  var tmp: Message = _
}

class ActorB extends Actor[Message] {

  var data: Box[Data] = _

  override def receive(box: Box[Message])(implicit acc: CanAccess { type C = box.C }) {
    mkBox[Data] { packed =>
      implicit val access = packed.access

      // capture received message
      packed.box.capture(box)(_.tmp = _)(spore { packedData =>
        implicit val accessData = packedData.access

        packedData.box.open { d =>
          d.l = d.l ::: d.tmp.l
          d.tmp = null
          println(s"list inside: ${d.l}")
        }

        swap(this.data)(x => this.data = x, packedData.box)(spore { (packedOld: Packed[Data]) =>
          // packedOld is uninteresting (it's null)
        })
      })

    }
  }

}

object ActorWithField {

  def main(args: Array[String]): Unit = try {
    val sys = System()
    val a = sys.actor[ActorA, Start]

    mkBox[Start] { packed =>
      implicit val acc = packed.access
      val box: packed.box.type = packed.box

      box.open(spore { obj =>
        val innerSys = System()
        obj.next = innerSys.actor[ActorB, Message]
      })

      a.send(box) { doNothing.consume(box) }
    }
  } catch {
    case t: ControlThrowable =>
      uncheckedCatchControl
      Thread.sleep(1000)
  }

} 
Example 7
Source File: Unique.scala    From lacasa   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lacasa.samples.unique

import scala.concurrent.ExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global

import scala.util.control.ControlThrowable

import lacasa.{LaCasaApp, System, Box, Packed, CanAccess, Actor, ActorRef, doNothing, sleep}
import Box._

import scala.spores._
import SporeConv._


// this time C is ocap!
class C {
  var arr: Array[Int] = _
}

// Container is ocap!
class Container {
  var part1: Box[C] = _
  var part2: Box[C] = _
}

class ActorA(next: ActorRef[C]) extends Actor[Container] {
  def receive(msg: Box[Container])(implicit access: CanAccess { type C = msg.C }): Unit = {
    println("ActorA received container")

    // create box that can be swapped with `part1` of container
    mkBox[C] { packed =>
      implicit val acc = packed.access
      val b: packed.box.type = packed.box

      b.open(spore { obj =>
        obj.arr = Array(100, 200, 300)
      })

      msg.swap(_.part1)((cont, newBox) => cont.part1 = newBox, b)(
        spore { (packed: Packed[C]) =>
          implicit val acc = packed.access
          val part1: packed.box.type = packed.box

          part1.open { part1Obj =>
            println(part1Obj.arr.mkString(","))
            part1Obj.arr(0) = 1000
          }

          next.send(part1) { doNothing.consume(part1) }
        })
    }
  }
}

class ActorB extends Actor[C] {
  def receive(msg: Box[C])(implicit access: CanAccess { type C = msg.C }): Unit = {
    println("ActorB received object with array")
    println(msg.extract(_.arr.mkString(",")))
  }
}


object Transfer extends LaCasaApp {

  def lcMain(args: Array[String]): Unit = {
    val sys = System()
    val b = sys.actor[ActorB, C]
    val a = sys.actor[Container](new ActorA(b))

    mkBox[Container] { packed =>
      import packed.access
      val containerBox: packed.box.type = packed.box

      mkBox[C] { packed2 =>
        import packed2.access
        val box2: packed2.box.type = packed2.box

        // initialize object in box2 with new array
        box2.open(spore { obj =>
          obj.arr = Array(1, 2, 3, 4)
        })

        // assign `box2` to `part1` of container
        containerBox.swap(_.part1)((cont, newBox) => cont.part1 = newBox, box2)(
          spore {
            implicit val localAcc = packed.access
            val localContainerBox = containerBox
            val localA = a
              (packed: Packed[C]) =>
                import packed.access
                val ignore = packed.box

                localA.send(localContainerBox) { sleep.consume(localContainerBox)(500) }
          }
        )
      }
    }
  }

}