• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala NonFatal类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.util.control.NonFatal的典型用法代码示例。如果您正苦于以下问题:Scala NonFatal类的具体用法?Scala NonFatal怎么用?Scala NonFatal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了NonFatal类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: ProcessorHierarchySpec

//设置package包名称以及导入依赖的类
package akka.stream

import akka.stream.testkit.AkkaSpec
import akka.stream.scaladsl.Flow
import akka.actor.ActorContext
import scala.concurrent.Await
import scala.concurrent.duration._
import akka.actor.ActorRef
import scala.collection.immutable.TreeSet
import scala.util.control.NonFatal
import akka.stream.impl.ActorBasedFlowMaterializer

class ProcessorHierarchySpec extends AkkaSpec("akka.actor.debug.lifecycle=off\nakka.loglevel=INFO") {

  val materializer = FlowMaterializer(MaterializerSettings())

  def self = ActorBasedFlowMaterializer.currentActorContext().self

  "An ActorBasedFlowMaterializer" must {

    "generate the right level of descendants" in {
      val f = Flow(() ? {
        testActor ! self
        Flow(List(1)).map(x ? { testActor ! self; x }).toProducer(materializer)
      }).take(3).foreach(x ? {
        testActor ! self
        Flow(x).foreach(_ ? testActor ! self).consume(materializer)
      }).toFuture(materializer)
      Await.result(f, 3.seconds)
      val refs = receiveWhile(idle = 250.millis) {
        case r: ActorRef ? r
      }
      try {
        refs.toSet.size should be(8)
        refs.distinct.map(_.path.elements.size).groupBy(x ? x).mapValues(x ? x.size) should be(Map(2 -> 2, 3 -> 6))
      } catch {
        case NonFatal(e) ?
          println(refs.map(_.toString).to[TreeSet].mkString("\n"))
          throw e
      }
    }

  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:46,代码来源:ProcessorHierarchySpec.scala


示例2: interpret

//设置package包名称以及导入依赖的类
package org.atnos.eff

import cats._
import cats.implicits._

import scala.util.control.NonFatal


  def interpret[U](n: Eff[R, Unit] => Eff[U, Unit]): Last[U] =
    Last[U](value.map(v => v.map(n)))

  def interpretEff[U](n: Last[R] => Eff[U, Unit]): Last[U] =
    Last.eff(n(this))

  def <*(last: Last[R]): Last[R] =
    (value, last.value) match {
      case (None, None)       => this
      case (Some(r), None)    => this
      case (None, Some(l))    => last
      case (Some(r), Some(l)) => Last(Option(r *> l))
    }

  def *>(last: Last[R]): Last[R] =
    (value, last.value) match {
      case (None, None)       => this
      case (Some(r), None)    => this
      case (None, Some(l))    => last
      case (Some(r), Some(l)) => Last(Option(r *> l))
    }
}

object Last {

  def none[R]: Last[R] =
    Last(None)

  def eff[R](e: =>Eff[R, Unit]): Last[R] =
    Last(Option(Eval.later(evaluate(e))))

  def evaluate[R](e: =>Eff[R, Unit]): Eff[R, Unit] =
    try e
    catch { case NonFatal(t) =>
       if (sys.props.isDefinedAt("eff.debuglast"))
         println("executing one last eff action failed\n"+t.getStackTrace.mkString("\n"))
        Eff.pure[R, Unit](())
    }

} 
开发者ID:atnos-org,项目名称:eff,代码行数:49,代码来源:Last.scala


示例3: main

//设置package包名称以及导入依赖的类
package akka

import akka.actor.ActorSystem
import akka.actor.ExtendedActorSystem
import akka.actor.Actor
import akka.actor.Terminated
import akka.actor.ActorLogging
import akka.actor.Props
import akka.actor.ActorRef
import scala.util.control.NonFatal


  def main(args: Array[String]): Unit = {
    if (args.length != 1) {
      println("you need to provide exactly one argument: the class of the application supervisor actor")
    } else {
      val system = ActorSystem("Main")
      try {
        val appClass = system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](args(0)).get
        val app = system.actorOf(Props(appClass), "app")
        val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
      } catch {
        case NonFatal(e) ? system.shutdown(); throw e
      }
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app
    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:38,代码来源:Main.scala


示例4: JsonSchema

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation

import org.coursera.autoschema.{AutoSchema, TypeMappings}
import play.api.libs.json.{JsObject, Json}

import scala.reflect.runtime.{universe => ru}
import scala.util.control.NonFatal

object JsonSchema {

  def resolveSchema[T](implicit t: ru.TypeTag[T], as: AutoSchema): JsObject = {
    try as.createSchema[T] catch {
      case NonFatal(err) =>
        def errPath(ex: Throwable): String = ex.getCause match {
          case null => ex.getMessage
          case x    => "[" + ex.getClass.getSimpleName + "]" + ex.getMessage + ". Caused by: " + errPath(x)
        }
        Json.obj("error" -> s"$t: ${errPath(err)}")
    }
  }

  val string: JsObject    = Json.obj("type" -> "string")
  val numeric: JsObject   = Json.obj("type" -> "number", "format" -> "number")
  val boolean: JsObject   = Json.obj("type" -> "boolean")
}

trait DocumentedTypeMappings extends TypeMappings {
  import JsonSchema._

  override def schemaTypeForScala(typeName: String): Option[JsObject] = {
    schemaTypes.get(typeName)
  }

  private val schemaTypes = Map(
    "scala.Nothing"           -> Json.obj(),
    "scala.Unit"              -> Json.obj(),
    "org.joda.time.DateTime"  -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.ZonedDateTime" -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.LocalDate"     -> Json.obj("type" -> "string", "format" -> "date", "pattern" -> localDatePattern),
    "java.util.Date"          -> Json.obj("type" -> "string", "format" -> "date"),
    "java.lang.String"        -> string,
    "scala.Boolean"           -> boolean,
    "scala.Int"               -> numeric,
    "scala.Long"              -> numeric,
    "scala.Double"            -> numeric,
    "scala.math.BigInt"       -> numeric,
    "scala.math.BigDecimal"   -> numeric,
    "java.util.UUID"          -> Json.obj("type" -> "string", "pattern" -> "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$")
  )

  lazy val localDatePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
}

object DocumentedTypeMappings extends DocumentedTypeMappings 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:55,代码来源:JsonSchema.scala


示例5: ExecutionContextBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {

  import ExecutionContextBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    Future {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }(executionContext)
  }

}

object ExecutionContextBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:37,代码来源:ExecutionContextBackboneCoordinator.scala


示例6: ExecutorServiceBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import java.util.concurrent.{ Callable, Future, ExecutorService }

import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
  import ExecutorServiceBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
    override def call(): Xor[TransformationPipelineFailure, DA] = {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }
  }

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    executor.submit(new BackboneCallable(datum))
  }

}

object ExecutorServiceBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:41,代码来源:ExecutorServiceBackboneCoordinator.scala


示例7: RobotsTxtLookUp

//设置package包名称以及导入依赖的类
package bridgeapp.crawler

import java.net.URI

import akka.actor.{ActorRef, ActorSystem, Cancellable}
import bridgeapp.crawler.execution._
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration._
import scala.util.control.NonFatal


class RobotsTxtLookUp(throttling: ActorRef) extends Runnable with LazyLogging {
  override def run(): Unit = {
    logger.warn(s" Lookup robots.txt")
    val uri = new URI("https://rutracker.org/robots.txt")

    val parser = new ResponseParser {
      override def ->(response: Response): Unit = {
        val body = new String(response.body)
        Robots.parse(body) match {
          case Left(error) =>
            logger.error(s"Error parse robots txt file, $error ")
          case Right(robots) =>
            robots.nonGroupFields.map(s => (s.key, s.value)).toMap[String, String].get("Crawl-delay").fold() { delay =>
              try {
                val rate = Rate(1, delay.toFloat.second)
                throttling ! SetRate(rate)
              } catch {
                case NonFatal(e) => logger.error("Error parse crawl delay directive in robots.txt. ", e)
              }
            }
        }
      }
    }
    val request = Request(uri, parser)

    //throttling !! request
  }
}

class RobotsTXTScheduleExecutor(robotsTxtLookUp: RobotsTxtLookUp)(implicit val actorSystem: ActorSystem) {

  private implicit val prep = actorSystem.dispatcher.prepare()

  private var instance: Cancellable = _

  def execute(duration: FiniteDuration) = {
    instance = actorSystem.scheduler.schedule(duration, duration, robotsTxtLookUp)
  }

  def cancel(): Unit = {
    instance.cancel()
  }
} 
开发者ID:bridge-app,项目名称:crawler,代码行数:56,代码来源:RobotsTxtLookUp.scala


示例8: CustomExceptionHandling

//设置package包名称以及导入依赖的类
package com.queirozf.utils

import java.time.format.DateTimeParseException

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import com.queirozf.utils.ResponseUtils._
import org.slf4j.LoggerFactory

import scala.util.control.NonFatal


object CustomExceptionHandling {
  private val logger = LoggerFactory.getLogger("balance-tracker.errors")

  def handler = ExceptionHandler {

    case dpe: DateTimeParseException => complete(JsonError(dpe))
    case NonFatal(nf) => {
      logger.error("Non-fatal error thrown: ", nf)
      // avoid leaking information
      complete(JsonError(new Exception("An unexpected error occurred.")))
    }
    case t: Throwable => {
      logger.error("Fatal error thrown: ", t)

      complete(JsonError(new Exception("An unexpected error occurred.")))
    }
  }
} 
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:31,代码来源:CustomExceptionHandling.scala


示例9: futuristicErrors

//设置package包名称以及导入依赖的类
package akka_in_action.future

import akka.actor.ActorSystem

import scala.concurrent._
import scala.util.{Success, Failure}
import scala.util.control.NonFatal

object futuristicErrors extends App {
  implicit val system = ActorSystem()
  import system.dispatcher

  val futureFail = future {
    throw new Exception("Error!")
  }

  futureFail onComplete {
    case Failure(NonFatal(e)) => println(e)
    case Success(value) => println(value)
  }

  futureFail andThen {
    case _ => system.shutdown
  }
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:26,代码来源:futuristicErrors.scala


示例10: tryOnNextAndRequest

//设置package包名称以及导入依赖的类
package knot.core.emitters

import knot.core.Downstream
import knot.core.Signals.Request

import scala.util.control.NonFatal

trait RequestEimitter[T] {
  self: PartContext with RequestContext =>

  protected def tryOnNextAndRequest(part: Downstream[T], element: T, length: Long): Unit = {
    _requested -= 1
    try {
      part.onNext(element)
    } catch {
      case NonFatal(e) => error(e)
    }
    try part.request() catch {
      case NonFatal(e) => error(e)
    }
  }

  protected def emittRequest(length: Long): Unit = {
    if (input != null && _requested <= 0) {
      input.send(Request(length))
      _requested += length
      if (_requested < 0L)
        _requested = Long.MaxValue
    }
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:32,代码来源:RequestEimitter.scala


示例11: DecryptConfig

//设置package包名称以及导入依赖的类
package com.evolutiongaming.crypto

import com.typesafe.config.{Config, ConfigFactory}
import scala.util.control.NonFatal

object DecryptConfig {
  def apply(password: String, config: Config = ConfigFactory.load()): String = try {
    if (config getBoolean "encryptedPasswords") {
      val secret = config getString "application.secret"
      Crypto.decryptAES(password, secret.substring(0, 16))
    } else {
      password
    }
  } catch {
    case NonFatal(e) => password
  }
} 
开发者ID:evolution-gaming,项目名称:crypto,代码行数:18,代码来源:DecryptConfig.scala


示例12: ClientMain

//设置package包名称以及导入依赖的类
package nl.dykam.hangman.client

import akka.actor._
import com.typesafe.config.{Config, ConfigFactory}
import nl.dykam.hangman.client.actors.Client

import scala.collection.JavaConverters._
import scala.util.control.NonFatal

object ClientMain {
  def main(args: Array[String]): Unit = {
    val baseConfig: Config = ConfigFactory.load()
    val config = ConfigFactory.parseMap(Map(
      "akka" -> Map(
        "cluster.roles" -> Map("0" -> "client").asJava
      ).asJava
    ).asJava).withFallback(baseConfig)

    val system = ActorSystem("NetTag", config)
    try {
      val app = system.actorOf(Props[Client], name = "client")

      val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
    } catch {
      case NonFatal(e) ? system.shutdown(); throw e
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app

    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:Dykam,项目名称:scala-akka-cluster-hangman,代码行数:40,代码来源:ClientMain.scala


示例13: SeedMain

//设置package包名称以及导入依赖的类
package nl.dykam.hangman.seed

import java.net.URI

import akka.actor._
import com.typesafe.config.{Config, ConfigFactory}
import nl.dykam.hangman.seed.actors.Seed

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.util.control.NonFatal

object SeedMain {
  def main(args: Array[String]): Unit = {
    val baseConfig: Config = ConfigFactory.load()
    val seedRawUrl: String = baseConfig.getStringList("akka.cluster.seed-nodes")(0)
    val seedUrl = new URI(seedRawUrl)

    val config = ConfigFactory.parseMap(Map(
      "akka" -> Map(
        "remote.netty.tcp.port" -> seedUrl.getPort,
        "cluster.roles" -> Map("0" -> "backend").asJava
      ).asJava
    ).asJava).withFallback(baseConfig)

    val system = ActorSystem("NetTag", config)
    try {
      val app = system.actorOf(Props[Seed], name = "seed")

      val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
    } catch {
      case NonFatal(e) ? system.shutdown(); throw e
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app

    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:Dykam,项目名称:scala-akka-cluster-hangman,代码行数:47,代码来源:SeedMain.scala


示例14: PagerDutyAlerter

//设置package包名称以及导入依赖的类
package pagerduty

import io.circe.generic.auto._
import io.circe.syntax._
import okhttp3.{MediaType, OkHttpClient, Request, RequestBody}
import play.api.Logger

import scala.util.control.NonFatal

object PagerDutyAlerter {

  case class Context(url: String, serviceKey: String, enableAlerts: Boolean)

  case class AlertBody(service_key: String, event_type: String, description: String)

  val httpClient = new OkHttpClient()
  def apply(message: String, context: Context): Unit = {
    if (context.enableAlerts) {
      val alertBody = AlertBody(context.serviceKey, "trigger", message).asJson.toString()
      try {
        val request = new Request.Builder()
          .url(context.url)
          .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), alertBody))
          .build()

        val response = httpClient
          .newCall(request)
          .execute()

        response.code match {
          case 200 => Logger.info(s"Raised alert to pagerduty for : $message}")
          case _   => Logger.warn(s"Failed to raise pagerduty alert for: $message")

        }
        response.close()
      } catch {
        case NonFatal(e) =>
          Logger.warn(s"Unable to create PagerDuty incident for message $message")
      }
    } else ()
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:43,代码来源:PagerDutyAlerter.scala


示例15: onShutdown

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.base

import java.util.concurrent.atomic.AtomicBoolean

import org.slf4j.LoggerFactory

import scala.util.control.NonFatal

trait ShutdownHooks {
  def onShutdown(block: => Unit): Unit

  def shutdown(): Unit

  def isShuttingDown: Boolean
}

object ShutdownHooks {
  def apply(): ShutdownHooks = new DefaultShutdownHooks
}

private[base] class BaseShutdownHooks extends ShutdownHooks {
  private[this] val log = LoggerFactory.getLogger(getClass)
  private[this] var shutdownHooks = List.empty[() => Unit]
  private[this] val shuttingDown = new AtomicBoolean(false)

  override def onShutdown(block: => Unit): Unit = {
    shutdownHooks +:= { () => block }
  }

  override def shutdown(): Unit = {
    shuttingDown.set(true)
    shutdownHooks.foreach { hook =>
      try hook()
      catch {
        case NonFatal(e) => log.error("while executing shutdown hook", e)
      }
    }
    shutdownHooks = Nil
  }

  override def isShuttingDown: Boolean = shuttingDown.get
}


private class DefaultShutdownHooks extends BaseShutdownHooks {
  Runtime.getRuntime.addShutdownHook(new Thread() {
    override def run(): Unit = {
      shutdown()
    }
  })
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:ShutdownHooks.scala


示例16: FullStream

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.indexing_logic

import akka.NotUsed
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import com.yannick_cw.elastic_indexer4s.Index_results.{IndexError, StageSucceeded, StageSuccess}
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal

object FullStream extends LazyLogging {

  private def countAntLogSink[A](logPer: FiniteDuration): Sink[A, Future[Int]] = Flow[A]
    .groupedWithin(Int.MaxValue, logPer)
    .map(_.length)
    .map { elementsPerTime =>
      logger.info(s"Indexed $elementsPerTime elements last $logPer")
      elementsPerTime
    }.toMat(Sink.reduce[Int](_ + _))(Keep.right)

  def run[A](source: Source[A, NotUsed], sink: Sink[A, Future[Unit]], logSpeedInterval: FiniteDuration)
    (implicit materializer: ActorMaterializer, ex: ExecutionContext): Future[Either[IndexError, StageSucceeded]] =
    (for {
      count <- source
        .alsoToMat(countAntLogSink(logSpeedInterval))(Keep.right)
        .toMat(sink)(Keep.both)
        .mapMaterializedValue{ case(fCount, fDone) => fDone.flatMap(_ => fCount) }
        .run()
    } yield Right(StageSuccess(s"Indexed $count documents successfully")))
      .recover { case NonFatal(t) =>
        Left(IndexError("Writing documents failed.", Some(t)))
      }
} 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:36,代码来源:FullStream.scala


示例17: AliasSwitching

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.elasticsearch.index_ops

import scala.concurrent.{ExecutionContext, Future}
import cats.implicits._
import com.yannick_cw.elastic_indexer4s.Index_results.{IndexError, StageSucceeded}

import scala.util.Right
import scala.util.control.NonFatal

class AliasSwitching(esClient: EsOpsClientApi, waitForElastic: Long, minThreshold: Double, maxThreshold: Double)
  (implicit ec: ExecutionContext) {

  import esClient._

  def switchAlias(alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] = trySwitching(alias, newIndexName)
    .recover { case NonFatal(ex) =>
        Left(IndexError("Could not switch alias.", Some(ex)))
    }

  private def trySwitching(alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] = for {
    _ <- Future(Thread.sleep(waitForElastic))
    oldSize <- latestIndexWithAliasSize(alias)
    newSize <- sizeFor(newIndexName)
    optSwitchRes <- oldSize.traverse(size => switchAliasBetweenIndices(newSize / size.toDouble, alias, newIndexName))
    switchRes <- optSwitchRes match {
      case None => addAliasToIndex(newIndexName, alias)
        .map(_ => Right(NewAliasCreated(s"Added alias $alias to index $newIndexName")))
      case Some(x) => Future.successful(x)
    }
  } yield switchRes

  private def switchAliasBetweenIndices(percentage: Double, alias: String, newIndexName: String): Future[Either[IndexError, StageSucceeded]] =
    if (checkThreshold(percentage)) switchAliasToIndex(alias, newIndexName)
      .map(_ => Right(AliasSwitched(s"Switched alias, new index size is ${(percentage * 100).toInt}% of old index")))
    else Future.successful(Left(IndexError(s"Switching failed, new index size is ${(percentage * 100).toInt}% of old index")))

  private def checkThreshold(percentage: Double): Boolean = minThreshold < percentage && percentage <= maxThreshold
}

object AliasSwitching {
  def apply(esClient: EsOpsClientApi,  minThreshold: Double, maxThreshold: Double, waitForElastic: Long)
    (implicit ec: ExecutionContext): AliasSwitching = new AliasSwitching(esClient, waitForElastic, minThreshold, maxThreshold)
}

case class AliasSwitched(override val msg: String) extends StageSucceeded
case class NewAliasCreated(override val msg: String) extends StageSucceeded 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:47,代码来源:AliasSwitching.scala


示例18: respondWith

//设置package包名称以及导入依赖的类
package com.pacbio.common

import akka.actor.{Status, Actor}
import akka.pattern.pipe

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
import scala.util.control.NonFatal

package object actors {
  trait PacBioActor extends Actor {
    def respondWith(x: => Any): Unit = {
      sender ! Try(x).recover{ case NonFatal(e) => Status.Failure(e) }.get
    }

    def pipeWith(x: => Future[Any])(implicit ec: ExecutionContext): Unit = {
      pipe(x.recover{ case NonFatal(e) => Status.Failure(e) }) to sender
    }
  }
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:21,代码来源:package.scala


示例19: CanarySMSAsserter

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.monitor.canary.sms.asserter

import java.time.LocalDateTime

import com.ovoenergy.comms.monitor.canary.sms.client.Twilio.Message
import com.ovoenergy.comms.monitor.logging.LoggingWithMDC

import scala.util.control.NonFatal

object CanarySMSAsserter extends LoggingWithMDC {

  def apply(canaryMobileNumber: String, smsClient: (String, LocalDateTime) => Option[Either[String, Message]])(
      generatedTime: LocalDateTime,
      traceToken: String): Either[Seq[String], Boolean] = {

    try {
      smsClient(traceToken, generatedTime) match {
        case None => Right(false)
        case Some(result) =>
          result match {
            case Left(error) => Left(Seq(error))
            case Right(message) =>
              val errors = Seq(
                checkBodyForErrors(traceToken, message),
                checkSenderForErrors(message)
              ).flatten
              if (errors.isEmpty) Right(true)
              else Left(errors)
          }
      }
    } catch {
      case NonFatal(ex) =>
        logError(traceToken, "Error retrieving canary sms from client", ex)
        Right(false)
    }
  }

  private def checkBodyForErrors(traceToken: String, sms: Message): Option[String] = {
    val expContent = s"This is a canary comm with trace token $traceToken"
    if (sms.body == expContent) None
    else Some(s"SMS content not as expected, expected '$expContent' but was '${sms.body}'")
  }

  private def checkSenderForErrors(sms: Message): Option[String] = {
    val expSender = "OVO Energy"
    if (sms.from == expSender) None
    else Some(s"SMS sender not as expected, expected '$expSender' but was '${sms.from}'")
  }

  override def loggerName: String = "CanarySMSAsserter"
} 
开发者ID:ovotech,项目名称:comms-monitor-service,代码行数:52,代码来源:CanarySMSAsserter.scala


示例20: TryCatch

//设置package包名称以及导入依赖的类
// src/main/scala/progscala2/rounding/TryCatch.scala
package progscala2.rounding

object TryCatch {
  
  def main(args: Array[String]) = {
    args foreach (arg => countLines(arg))                            // <1>
  }

  import scala.io.Source                                             // <2>
  import scala.util.control.NonFatal

  def countLines(fileName: String) = {                               // <3>
    println()  // ?? ?? ?? ?? ? ?? ???.
    var source: Option[Source] = None                                // <4>
    try {                                                            // <5>
      source = Some(Source.fromFile(fileName))                       // <6>
      val size = source.get.getLines.size
      println(s"file $fileName has $size lines")
    } catch {
      case NonFatal(ex) => println(s"Non fatal exception! $ex")      // <7>
    } finally {
      for (s <- source) {                                            // <8>
        println(s"Closing $fileName...")
        s.close
      }
    }
  }
} 
开发者ID:oops,项目名称:scala_test,代码行数:30,代码来源:TryCatch.scala



注:本文中的scala.util.control.NonFatal类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ScalaFutures类代码示例发布时间:2022-05-23
下一篇:
Scala PrintWriter类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap