本文整理汇总了Scala中scala.concurrent.TimeoutException类的典型用法代码示例。如果您正苦于以下问题:Scala TimeoutException类的具体用法?Scala TimeoutException怎么用?Scala TimeoutException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TimeoutException类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: HTTP_METHOD
//设置package包名称以及导入依赖的类
package net.cimadai.chatwork
import com.ning.http.client.Response
import dispatch.Defaults._
import dispatch._
import org.json4s._
import org.json4s.jackson.JsonMethods
import scala.concurrent.duration._
import scala.concurrent.{Await, TimeoutException}
trait HttpClient extends JsonMethods {
object HTTP_METHOD extends Enumeration {
val GET, POST, PUT, DELETE = Value
}
private val absoluteTimeout = 30.seconds
protected val StatusCodeUndefined = -1
implicit val formats = DefaultFormats
private val http = new Http
private def executeRequestAndAwait(uri: String, method: HTTP_METHOD.Value, params: Params): Option[Response] = {
try {
val req = url(uri).setMethod(method.toString).setParameters(params)
if (method != HTTP_METHOD.GET) {
req.addHeader("Content-Type", "application/x-www-form-urlencoded")
}
val res = Await.result(http(decorateRequest(req)), absoluteTimeout)
Option(res)
} catch {
case e: TimeoutException =>
None
}
}
}
示例2: ErrorTest
//设置package包名称以及导入依赖的类
package com.github.tkqubo.akka_open_graph_fetcher
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.StatusCodes.ClientError
import org.specs2.mutable.Specification
import spray.json.DefaultJsonProtocol._
import spray.json._
import scala.concurrent.TimeoutException
// scalastyle:off magic.number
class ErrorTest extends Specification {
"Error" should {
val errorMessage: Option[String] = Some("error")
"maybeFromStatusCode" should {
"return None" in {
Error.maybeFromStatusCode(StatusCodes.OK, errorMessage) === None
}
"return Error instance" in {
val requestTimeout: ClientError = StatusCodes.RequestTimeout
Error.maybeFromStatusCode(requestTimeout, errorMessage) === Some(Error(requestTimeout.intValue, errorMessage))
Error.maybeFromStatusCode(requestTimeout) === Some(Error(requestTimeout.intValue))
}
}
"fromThrowable" should {
"return Error with 408 status code" in {
Error.fromThrowable(new TimeoutException(), errorMessage) === Error(StatusCodes.RequestTimeout.intValue, errorMessage)
Error.fromThrowable(new TimeoutException()) === Error(StatusCodes.RequestTimeout.intValue)
}
"return Error with 503 status code" in {
Seq(new IllegalArgumentException, new RuntimeException, new OutOfMemoryError())
.forall(Error.fromThrowable(_) == Error(StatusCodes.ServiceUnavailable.intValue))
}
}
"rootJsonFormat" should {
"pass" in {
val error = Error(StatusCodes.BadRequest.intValue, errorMessage)
val json =
s"""
|{
| "status_code": ${StatusCodes.BadRequest.intValue},
| "message": ${error.message.get.toJson}
|}
""".stripMargin.parseJson
Error.rootJsonFormat.write(error).prettyPrint === json.prettyPrint
Error.rootJsonFormat.read(json) === error
}
}
}
}
示例3: Main
//设置package包名称以及导入依赖的类
package name.denyago.yasc
import akka.actor.{ActorSystem, Props}
import akka.stream.ActorMaterializer
import name.denyago.yasc.log.{Helper => LogHelper}
import scala.concurrent.duration._
import scala.concurrent.{Await, TimeoutException}
import scala.util.Try
class Main(args: Array[String]) extends LogHelper {
implicit val system = ActorSystem("yasc-server")
implicit val materializer = ActorMaterializer()
def run(): Unit = {
log.info(s"Statring the App: Starting the Chat Server...")
system.actorOf(Props(classOf[Server]), "main-server")
}
def stop(): Unit = {
val timeout = (20 seconds)
log.info(s"Stopping the App: Asking Akka System to terminate. Waiting for $timeout")
Try(Await.result(system.terminate(), timeout)).
map(_ => log.info("Stopping the App: Stopped gracefully.")).
recover {
case _: TimeoutException => log.error("Stopping the App: it took too long. The app is killed :(")
case throwable: Throwable => log.error(s"Stopping the App: Exception happened - ${throwable.getMessage}")
}
}
}
object Main extends App {
val app = new Main(args)
app.run()
sys.addShutdownHook({
app.stop()
})
}
示例4: TimeoutScheduler
//设置package包名称以及导入依赖的类
package com.gilazaria.subsearch.utils
import java.util.concurrent.TimeUnit
import org.jboss.netty.util.{Timeout, TimerTask, HashedWheelTimer}
import scala.concurrent.{TimeoutException, Promise, Future}
import scala.concurrent.duration.Duration
object TimeoutScheduler {
val timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS)
def scheduleTimeout(promise:Promise[_], after:Duration) = {
timer.newTimeout(new TimerTask {
def run(timeout:Timeout){
promise.failure(new TimeoutException("Operation timed out after " + after.toMillis + " millis"))
}
}, after.toNanos, TimeUnit.NANOSECONDS)
}
}
object TimeoutFuture {
implicit class FutureWithTimeout[T](f: Future[T]) {
import scala.concurrent.ExecutionContext
def withTimeout(after: Duration)(implicit ec: ExecutionContext) = {
val prom = Promise[T]()
val timeout = TimeoutScheduler.scheduleTimeout(prom, after)
val combinedFut = Future.firstCompletedOf(List(f, prom.future))
f onComplete { case result => timeout.cancel() }
combinedFut
}
}
}
示例5: BackoffTest
//设置package包名称以及导入依赖的类
package caustic.runtime
import Backoff._
import org.junit.runner.RunWith
import org.mockito.Mockito._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FunSuite, Matchers}
import org.scalatest.mockito.MockitoSugar
import scala.concurrent.{Await, Future, TimeoutException}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.language.postfixOps
@RunWith(classOf[JUnitRunner])
class BackoffTest extends FunSuite
with ScalaFutures
with Matchers
with MockitoSugar {
test("Backoff properly retries failures.") {
val fake = mock[Database]
when(fake.execute(literal(""))(global))
.thenReturn(Future.failed(new Exception("Retryable.")))
.thenReturn(Future("Success"))
.thenReturn(Future.failed(FatalException("Non-Retryable")))
.thenReturn(Future.failed(new Exception("Retryable")))
.thenReturn(Future("Success"))
// Verify that retries succeed on retryable failures.
whenReady(retry(Seq(100 millis))(fake.execute(literal(""))))(_ shouldEqual "Success")
// Verify that retries fail on fatal errors.
whenReady(retry(Seq(100 millis))(fake.execute(literal(""))).failed)(_ shouldBe an [FatalException])
// Verify that retry respects backoff durations.
assertThrows[TimeoutException] {
Await.result(retry(Seq(1 second))(fake.execute(literal(""))).failed, 500 millis)
}
verify(fake, times(4)).execute(literal(""))(global)
}
}
示例6: fetchingConfig
//设置package包名称以及导入依赖的类
package io.scalac.newspaper.crawler.fetching
import akka.NotUsed
import akka.stream.scaladsl.Flow
import io.scalac.newspaper.crawler.fetching.FetchingFlow._
import io.scalac.newspaper.crawler.fetching.HttpFetchingFlow.FetchingConfig
import play.api.libs.ws.{StandaloneWSClient, StandaloneWSResponse}
import scala.concurrent.duration.Duration
import scala.concurrent.{ExecutionContext, Future, TimeoutException}
trait HttpFetchingFlow extends FetchingFlow {
def fetchingConfig: FetchingConfig
def fetchURLs: Flow[String, URLFetchingResult, NotUsed] =
Flow[String].mapAsyncUnordered(fetchingConfig.maxParallelism)(fetchURL)
implicit def ec: ExecutionContext
def wsClient: StandaloneWSClient
protected def get(url: String): Future[URLFetchingResult] =
wsClient
.url(url)
.withRequestTimeout(fetchingConfig.requestTimeout)
.get()
.map(response => if (responseFetchedCorrectly(response)) URLFetched(url, response.body)
else URLNotFetched(url, response.status, response.body)
)
private def fetchURL(url: String): Future[URLFetchingResult] =
get(url)
.recover {
case _: TimeoutException => URLFetchingTimeout(url)
case ex: Throwable => URLFetchingException(url, ex)
}
private def responseFetchedCorrectly(response: StandaloneWSResponse): Boolean =
response.status == 200
}
object HttpFetchingFlow {
case class FetchingConfig(maxParallelism: Int, requestTimeout: Duration)
}
示例7: timeoutHandler
//设置package包名称以及导入依赖的类
package teleporter.integration.utils
import java.util.concurrent.atomic.AtomicLong
import akka.actor.ActorSystem
import akka.util.Timeout
import scala.collection.concurrent.TrieMap
import scala.concurrent.duration._
import scala.concurrent.{Future, Promise, TimeoutException}
import scala.util.{Failure, Try}
trait EventListener[T] {
val system: ActorSystem
type ErrorHandler = Long ? Try[T]
def timeoutHandler(seqNr: Long): Try[T] = Failure(new TimeoutException(s"Event handler timeout, seqNr: $seqNr"))
def timeoutMessageHandler(message: String)(seqNr: Long): Try[T] = Failure(new TimeoutException(s"Event handler timeout: seqNr: $seqNr, $message"))
import system.dispatcher
private val events = TrieMap[Long, Promise[T]]()
private val _seqNr = new AtomicLong()
private def getSeqNr: Long = _seqNr.incrementAndGet()
private def registerEvents(default: ErrorHandler = timeoutHandler)(implicit timeout: Timeout): (Long, Future[T]) = {
val idx = getSeqNr
val promise = Promise[T]()
events += idx ? promise
system.scheduler.scheduleOnce(timeout.duration) {
resolve(idx, default(idx))
}
(idx, promise.future)
}
def asyncEvent(handler: Long ? Unit, default: ErrorHandler = timeoutHandler)(implicit timeout: Timeout = Timeout(10.seconds)): (Long, Future[T]) = {
val [email protected](seqNr, _) = registerEvents()
handler(seqNr)
result
}
def resolve(seqNr: Long, result: T): Unit = events.remove(seqNr).foreach(_.success(result))
def resolve(seqNr: Long, result: Try[T]): Unit = events.remove(seqNr).foreach(_.tryComplete(result))
def clear(): Unit = {
events.values.foreach(_.failure(new RuntimeException("Event will clear, So some unComplete event will interrupt")))
events.clear()
}
}
class EventListenerImpl[T]()(implicit val system: ActorSystem) extends EventListener[T]
object EventListener {
def apply[T]()(implicit system: ActorSystem): EventListener[T] = new EventListenerImpl[T]()
}
示例8: NodesUnreachableException
//设置package包名称以及导入依赖的类
package com.evolutiongaming.cluster
import akka.actor.{ActorSystem, Address}
import com.evolutiongaming.util.Nel
import scala.concurrent.TimeoutException
class NodesUnreachableException(addresses: Nel[Address], cause: Throwable) extends TimeoutException {
override def getCause = cause
override def getMessage = {
addresses map { _.hostPort } match {
case Nel(node, Nil) => s"node $node is unreachable"
case nodes => s"nodes ${ nodes mkString ", " } are unreachable"
}
}
}
object NodesUnreachableException {
def opt(timeoutException: TimeoutException, system: ActorSystem): Option[NodesUnreachableException] = {
for {
cluster <- ClusterOpt(system)
members <- Nel.opt(cluster.state.unreachable)
} yield {
val addresses = for {member <- members} yield member.address
new NodesUnreachableException(addresses, timeoutException)
}
}
}