本文整理汇总了Scala中akka.actor.Status.Failure类的典型用法代码示例。如果您正苦于以下问题:Scala Failure类的具体用法?Scala Failure怎么用?Scala Failure使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Failure类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ResolveArtifactsActor
//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade
import java.net.URL
import akka.actor.Status.Failure
import akka.actor.{ Actor, Props }
import akka.pattern.pipe
import mesosphere.marathon.ResolveArtifactsCanceledException
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.io.{ CancelableDownload, PathFun }
import mesosphere.util.Logging
import scala.concurrent.Promise
private[this] class ResolveArtifactsActor(
url2Path: Map[URL, String],
promise: Promise[Boolean],
storage: StorageProvider)
extends Actor
with PathFun
with Logging {
import mesosphere.marathon.upgrade.ResolveArtifactsActor.DownloadFinished
// all downloads that have to be performed by this actor
var downloads = url2Path.map { case (url, path) => new CancelableDownload(url, storage, path) }
override def preStart(): Unit = {
import context.dispatcher
downloads.map(_.get.map(DownloadFinished) pipeTo self)
if (url2Path.isEmpty) promise.success(true) // handle empty list
}
override def postStop(): Unit = {
downloads.foreach(_.cancel()) // clean up not finished artifacts
}
override def receive: Receive = {
case DownloadFinished(download) =>
downloads = downloads.filter(_ != download)
if (downloads.isEmpty) promise.success(true)
case Failure(ex) =>
log.warn("Can not resolve artifact", ex) // do not fail the promise!
case DeploymentActor.Shutdown =>
if (!promise.isCompleted)
promise.tryFailure(new ResolveArtifactsCanceledException("Artifact Resolving has been cancelled"))
context.stop(self)
}
}
object ResolveArtifactsActor {
def props(
url2Path: Map[URL, String],
promise: Promise[Boolean],
storage: StorageProvider): Props = Props(new ResolveArtifactsActor(url2Path, promise, storage))
case class DownloadFinished(download: CancelableDownload)
}
示例2: CustomRoute
//设置package包名称以及导入依赖的类
package docs.camel
import akka.camel.CamelMessage
import akka.actor.Status.Failure
import language.existentials
object CustomRoute {
object Sample1 {
//#CustomRoute
import akka.actor.{ Props, ActorSystem, Actor, ActorRef }
import akka.camel.{ CamelMessage, CamelExtension }
import org.apache.camel.builder.RouteBuilder
import akka.camel._
class Responder extends Actor {
def receive = {
case msg: CamelMessage =>
sender() ! (msg.mapBody {
body: String => "received %s" format body
})
}
}
class CustomRouteBuilder(system: ActorSystem, responder: ActorRef)
extends RouteBuilder {
def configure {
from("jetty:http://localhost:8877/camel/custom").to(responder)
}
}
val system = ActorSystem("some-system")
val camel = CamelExtension(system)
val responder = system.actorOf(Props[Responder], name = "TestResponder")
camel.context.addRoutes(new CustomRouteBuilder(system, responder))
//#CustomRoute
}
object Sample2 {
//#ErrorThrowingConsumer
import akka.camel.Consumer
import org.apache.camel.builder.Builder
import org.apache.camel.model.RouteDefinition
class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer {
def receive = {
case msg: CamelMessage => throw new Exception("error: %s" format msg.body)
}
override def onRouteDefinition = (rd) => rd.onException(classOf[Exception]).
handled(true).transform(Builder.exceptionMessage).end
final override def preRestart(reason: Throwable, message: Option[Any]) {
sender() ! Failure(reason)
}
}
//#ErrorThrowingConsumer
}
}
示例3: WriteEventExample
//设置package包名称以及导入依赖的类
package eventstore_client
import akka.actor.Status.Failure
import akka.actor.{ ActorLogging, Actor, Props, ActorSystem }
import eventstore._
import eventstore.tcp.ConnectionActor
object WriteEventExample extends App {
val system = ActorSystem()
val connection = system.actorOf(ConnectionActor.props())
implicit val writeResult = system.actorOf(Props[WriteResult])
val event = EventData("my-event", data = Content("my event data"), metadata = Content("my first event"))
connection ! WriteEvents(EventStream.Id("my-stream"), List(event))
class WriteResult extends Actor with ActorLogging {
def receive = {
case WriteEventsCompleted(range, position) =>
log.info("range: {}, position: {}", range, position)
context.system.terminate()
case Failure(e: EsException) =>
log.error(e.toString)
context.system.terminate()
}
}
}
示例4: ReadEventExample
//设置package包名称以及导入依赖的类
package eventstore_client
import akka.actor.Status.Failure
import akka.actor._
import eventstore._
import eventstore.tcp.ConnectionActor
import java.net.InetSocketAddress
object ReadEventExample extends App {
val system = ActorSystem()
val settings = Settings(
address = new InetSocketAddress("127.0.0.1", 1113),
defaultCredentials = Some(UserCredentials("admin", "changeit")))
val connection = system.actorOf(ConnectionActor.props(settings))
implicit val readResult = system.actorOf(Props[ReadResult])
connection ! ReadEvent(EventStream.Id("my-stream"), EventNumber.First)
class ReadResult extends Actor with ActorLogging {
def receive = {
case ReadEventCompleted(event) =>
log.info("event: {}", event)
context.system.terminate()
case Failure(e: EsException) =>
log.error(e.toString)
context.system.terminate()
}
}
}
示例5: Collector
//设置package包名称以及导入依赖的类
package com.darienmt.keepers
import akka.Done
import akka.actor.Status.Failure
import akka.actor.{ Actor, ActorLogging, ActorRef, Props }
import com.darienmt.keepers.Collector.{ StreamFinished }
object Collector {
sealed trait CollectorMessage
case object StreamFinished extends CollectorMessage
def props(
manager: ActorRef,
collectorGenerator: Generator
): Props = Props(new Collector(manager, collectorGenerator))
}
class Collector(
manager: ActorRef,
collectorGenerator: Generator
) extends Actor with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
override def receive: Receive = {
case Failure(ex) => {
log.error("Stream stopped with an error")
throw ex
}
case Done => {
manager ! StreamFinished
}
case msg => throw new Exception("Unknown message: " + msg.toString)
}
override def preStart(): Unit = collectorGenerator() pipeTo self
override def postRestart(reason: Throwable): Unit = {}
}
示例6: TellDemoArticleParser
//设置package包名称以及导入依赖的类
package com.dbaktor.actors
import java.util.concurrent.TimeoutException
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorRef, Props}
import akka.util.Timeout
import com.dbaktor.{ArticleBody, HttpResponse, ParseArticle, ParseHtmlArticle}
import com.dbaktor.messages.{GetRequest, SetRequest}
class TellDemoArticleParser(cacheActorPath: String,
httpClientActorPath: String,
acticleParserActorPath: String,
implicit val timeout: Timeout
) extends Actor {
val cacheActor = context.actorSelection(cacheActorPath)
val httpClientActor = context.actorSelection(httpClientActorPath)
val articleParserActor = context.actorSelection(acticleParserActorPath)
implicit val ec = context.dispatcher
private def buildExtraActor(senderRef: ActorRef, uri: String): ActorRef = {
return context.actorOf(Props(new Actor{
override def receive = {
case "timeout" => //if we get timeout, then fail
senderRef ! Failure(new TimeoutException("timeout!"))
context.stop(self)
case HttpResponse(body) => //If we get the http response first, we pass it to be parsed.
articleParserActor ! ParseHtmlArticle(uri, body)
case body: String => //If we get the cache response first, then we handle it and shut down.
//The cache response will come back before the HTTP response so we never parse in this case.
senderRef ! body
context.stop(self)
case ArticleBody(uri, body) => //If we get the parsed article back, then we've just parsed it
cacheActor ! SetRequest(uri, body) //Cache it as we just parsed it
senderRef ! body
context.stop(self)
case t => //We can get a cache miss
println("ignoring msg: " + t.getClass)
}
}))
}
}
示例7: TellDemoArticleParser
//设置package包名称以及导入依赖的类
package com.dbaktor
import java.util.concurrent.TimeoutException
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorRef, Props}
import akka.util.Timeout
import com.dbaktor.messages._
class TellDemoArticleParser(cacheActorPath: String,
httpClientActorPath: String,
acticleParserActorPath: String,
implicit val timeout: Timeout
) extends Actor {
val cacheActor = context.actorSelection(cacheActorPath)
val httpClientActor = context.actorSelection(httpClientActorPath)
val articleParserActor = context.actorSelection(acticleParserActorPath)
implicit val ec = context.dispatcher
private def buildExtraActor(senderRef: ActorRef, uri: String): ActorRef = {
return context.actorOf(Props(new Actor{
override def receive = {
case "timeout" => //if we get timeout, then fail
senderRef ! Failure(new TimeoutException("timeout!"))
context.stop(self)
case HttpResponse(body) => //If we get the http response first, we pass it to be parsed.
articleParserActor ! ParseHtmlArticle(uri, body)
case body: String => //If we get the cache response first, then we handle it and shut down.
//The cache response will come back before the HTTP response so we never parse in this case.
senderRef ! body
context.stop(self)
case ArticleBody(uri, body) => //If we get the parsed article back, then we've just parsed it
cacheActor ! SetRequest(uri, body) //Cache it as we just parsed it
senderRef ! body
context.stop(self)
case t => //We can get a cache miss
println("ignoring msg: " + t.getClass)
}
}))
}
}
示例8: MetricsShipper
//设置package包名称以及导入依赖的类
package com.timeout.kamon.cloudwatch
import java.util.concurrent.{ExecutorService, Executors}
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.pattern.pipe
import com.amazonaws.client.builder.ExecutorFactory
import com.amazonaws.regions.Regions
import com.amazonaws.services.cloudwatch.model.PutMetricDataResult
import com.amazonaws.services.cloudwatch.{AmazonCloudWatchAsync, AmazonCloudWatchAsyncClientBuilder}
import com.timeout.kamon.cloudwatch.KamonSettings.region
import com.timeout.kamon.cloudwatch.AmazonAsync.{MetricDatumBatch, MetricsAsyncOps}
import scala.concurrent.ExecutionContext
class MetricsShipper(implicit ec: ExecutionContext) extends Actor with ActorLogging {
// async aws client uses a thread pool that reuses a fixed number of threads
// operating off a shared unbounded queue.
implicit val client: AmazonCloudWatchAsync = AmazonCloudWatchAsyncClientBuilder
.standard()
.withRegion(
Option(Regions.getCurrentRegion).map(r => Regions.fromName(r.getName))
.getOrElse(Regions.fromName(region))
)
.withExecutorFactory(
new ExecutorFactory {
// don't use the default thread pool which configures 50 number of threads
override def newExecutor(): ExecutorService = Executors.newFixedThreadPool(KamonSettings.numThreads)
}
).build()
override def receive: Receive = LoggingReceive {
case ShipMetrics(metrics) => metrics.put.pipeTo(self)
case msg: PutMetricDataResult => log.debug(s"Succeeded to push metrics to Cloudwatch: $msg")
case Failure(t) => log.warning(s"Failed to send metrics to Cloudwatch ${t.getMessage}")
case msg => log.warning(s"Unsupported message $msg received in MetricsShipper")
}
}
object MetricsShipper {
def props(implicit ec: ExecutionContext): Props = Props(new MetricsShipper)
}
final case class ShipMetrics(datums: MetricDatumBatch)
示例9: PaymentHandlerSpec
//设置package包名称以及导入依赖的类
package fr.acinq.eclair.payment
import akka.actor.ActorSystem
import akka.actor.Status.Failure
import akka.testkit.{TestKit, TestProbe}
import fr.acinq.bitcoin.MilliSatoshi
import fr.acinq.eclair.TestConstants.Alice
import fr.acinq.eclair.channel.CMD_FULFILL_HTLC
import fr.acinq.eclair.wire.UpdateAddHtlc
import org.junit.runner.RunWith
import org.scalatest.FunSuiteLike
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class PaymentHandlerSpec extends TestKit(ActorSystem("test")) with FunSuiteLike {
test("LocalPaymentHandler should send an event when receiving a payment") {
val handler = system.actorOf(LocalPaymentHandler.props(Alice.nodeParams))
val sender = TestProbe()
val eventListener = TestProbe()
system.eventStream.subscribe(eventListener.ref, classOf[PaymentReceived])
val amountMsat = MilliSatoshi(42000)
sender.send(handler, ReceivePayment(amountMsat))
val pr = sender.expectMsgType[PaymentRequest]
val add = UpdateAddHtlc("11" * 32, 0, amountMsat.amount, 0, pr.paymentHash, "")
sender.send(handler, add)
sender.expectMsgType[CMD_FULFILL_HTLC]
eventListener.expectMsg(PaymentReceived(amountMsat, add.paymentHash))
}
test("Payment request generation should fail when the amount asked in not valid") {
val handler = system.actorOf(LocalPaymentHandler.props(Alice.nodeParams))
val sender = TestProbe()
val eventListener = TestProbe()
system.eventStream.subscribe(eventListener.ref, classOf[PaymentReceived])
// negative amount should fail
sender.send(handler, ReceivePayment(MilliSatoshi(-50)))
val negativeError = sender.expectMsgType[Failure]
assert(negativeError.cause.getMessage.contains("amount is not valid"))
// amount = 0 should fail
sender.send(handler, ReceivePayment(MilliSatoshi(0)))
val zeroError = sender.expectMsgType[Failure]
assert(zeroError.cause.getMessage.contains("amount is not valid"))
// large amount should fail (> 42.95 mBTC)
sender.send(handler, ReceivePayment(MilliSatoshi(PaymentRequest.maxAmountMsat + 10)))
val largeAmountError = sender.expectMsgType[Failure]
assert(largeAmountError.cause.getMessage.contains("amount is not valid"))
// success with 1 mBTC
sender.send(handler, ReceivePayment(MilliSatoshi(100000000L)))
val pr = sender.expectMsgType[PaymentRequest]
assert(pr.amount.amount == 100000000L
&& pr.nodeId.toString == Alice.nodeParams.privateKey.publicKey.toString)
}
}
示例10: TellDemoArticleParser
//设置package包名称以及导入依赖的类
package com.akkademy
import java.util.concurrent.TimeoutException
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorRef, Props}
import akka.util.Timeout
import com.akkademy.messages.{GetRequest, SetRequest}
class TellDemoArticleParser(cacheActorPath: String,
httpClientActorPath: String,
articleParserActorPath: String,
implicit val timeout: Timeout) extends Actor {
val cacheActor = context.actorSelection(cacheActorPath)
val httpClientActor = context.actorSelection(httpClientActorPath)
val articleParserActor = context.actorSelection(articleParserActorPath)
implicit val ec = context.dispatcher
private def buildExtraActor(senderRef: ActorRef, uri: String): ActorRef = {
context.actorOf(Props(new Actor{
override def receive: Receive = {
case body: String => // This executes when a cached result is found.
senderRef ! body
context.stop(self)
// the articleParserActor will reply with an ArticleBody which is the parsing results.
case HttpResponse(body) => articleParserActor ! ParseHtmlArticle(uri, body)
case ArticleBody(uri, body) => // This executes when a raw parse of the html is done.
cacheActor ! SetRequest(uri, body)
senderRef ! body
context.stop(self)
case "timeout" =>
senderRef ! Failure(new TimeoutException("timeout!"))
context.stop(self)
case t => println("ignoring msg: " + t.getClass)
}
}))
}
}
示例11: TellDemoArticleParser
//设置package包名称以及导入依赖的类
package com.akkademy
import java.util.concurrent.TimeoutException
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorRef, Props}
import akka.util.Timeout
import com.akkademy.messages.{GetRequest, SetRequest}
class TellDemoArticleParser(cacheActorPath: String,
httpClientActorPath: String,
articleParserActorPath: String,
implicit val timeout: Timeout
) extends Actor {
val cacheActor = context.actorSelection(cacheActorPath)
val httpClientActor = context.actorSelection(httpClientActorPath)
val articleParserActor = context.actorSelection(articleParserActorPath)
implicit val ec = context.dispatcher
override def receive: Receive = {
case [email protected](uri) =>
val extraActor = buildExtraActor(sender(), uri)
cacheActor.tell(GetRequest(uri), extraActor)
httpClientActor.tell("test", extraActor)
context.system.scheduler.scheduleOnce(timeout.duration, extraActor, "timeout")
}
private def buildExtraActor(senderRef: ActorRef, uri: String): ActorRef = {
return context.actorOf(Props(new Actor {
override def receive = {
case "timeout" =>
senderRef ! Failure(new TimeoutException("timeout!"))
context.stop(self)
case HttpResponse(body) =>
articleParserActor ! ParseHtmlArticle(uri, body)
case body: String =>
senderRef ! body
context.stop(self)
case ArticleBody(uri, body) =>
cacheActor ! SetRequest(uri, body)
senderRef ! body
context.stop(self)
case t =>
println("ignoring msg: " + t.getClass)
}
}))
}
}