本文整理汇总了Scala中scala.util.Failure类的典型用法代码示例。如果您正苦于以下问题:Scala Failure类的具体用法?Scala Failure怎么用?Scala Failure使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Failure类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: WithCalcLogging
//设置package包名称以及导入依赖的类
package biz.meetmatch.decorators
import biz.meetmatch.logging.BusinessLogger
import org.apache.spark.sql.SparkSession
import org.rogach.scallop.Scallop
import scala.util.{Failure, Success, Try}
object WithCalcLogging {
def apply[B](f: => B)(implicit module: Class[_]): B = apply(module.getName)(f)
def apply[B](scallopts: Scallop, sparkSession: SparkSession)(f: => B)(implicit module: Class[_] = this.getClass): B = apply(module.getName, Some(scallopts), Some(sparkSession))(f)
def apply[B](module: String)(f: => B): B = apply(module, None, None)(f)
def apply[B](module: String, scallopts: Scallop)(f: => B)(): B = apply(module, Some(scallopts), None)(f)
def apply[B](module: String, scallopts: Scallop, sparkSession: SparkSession)(f: => B): B = apply(module, Some(scallopts), Some(sparkSession))(f)
def apply[B](module: String, scalloptsO: Option[Scallop], sparkSessionO: Option[SparkSession])(f: => B): B = {
val businessLogger = new BusinessLogger(module)
val optsString = scalloptsO
.map { scallopts =>
scallopts.opts
.map { opt => opt.name + " = " + scallopts.get(opt.name)(opt.converter.tag).getOrElse("(empty)") }
.mkString(",")
}
.getOrElse("")
val sparkAppId = sparkSessionO.map(_.sparkContext.applicationId).getOrElse("")
businessLogger.calcStarted(optsString, sparkAppId)
val attempt = Try(WithStopwatch(f))
attempt match {
case Success(result) =>
businessLogger.calcStopped("SUCCESS")
result
case Failure(exception) =>
businessLogger.calcStopped("FAILURE")
throw exception
}
}
}
开发者ID:tolomaus,项目名称:languagedetector,代码行数:46,代码来源:WithCalcLogging.scala
示例2: ActivationProviders
//设置package包名称以及导入依赖的类
package im.actor.server.activation.common
import akka.actor.ActorSystem
import im.actor.config.ActorConfig
import scala.collection.JavaConversions._
import scala.util.{ Failure, Success, Try }
object ActivationProviders {
val Sms = "sms"
val Smtp = "smtp"
val Call = "call"
val Internal = "internal"
/**
* Instantiates activation providers based on configuration.
* Makes sure to instantiate only one instance of provider,
* if it is present for several activation types
* @param system actor system
* @return map from activation type to activation provider instance
*/
def getProviders()(implicit system: ActorSystem): Map[String, ActivationProvider] = {
val providersConfig = ActorConfig.load().getConfig("services.activation.providers")
val configMap = providersConfig.root.unwrapped.toMap
val reverseAcc = Map.empty[String, List[String]].withDefaultValue(List.empty[String])
// this is made to avoid duplicate instantiation of same providers
val reverseMap = (configMap foldLeft reverseAcc) {
case (acc, (activationType, value)) ?
val className = value.toString
acc.updated(className, activationType :: acc(className))
}
reverseMap flatMap {
case (className, activationTypes) ?
providerOf(className, system) match {
case Success(instance) ?
system.log.debug("Successfully instantiated code provider: {}, for activation types: [{}]", className, activationTypes mkString ", ")
(activationTypes map { _ ? instance }).toMap
case Failure(e) ?
system.log.warning("Failed to instantiate code provider: {}, exception: {}", className, e)
Map.empty[String, ActivationProvider]
}
}
}
private def providerOf(fqcn: String, system: ActorSystem): Try[ActivationProvider] = {
for {
constructor ? Try(Class.forName(fqcn).asSubclass(classOf[ActivationProvider]).getConstructor(classOf[ActorSystem]))
} yield constructor.newInstance(system)
}
}
开发者ID:wex5,项目名称:dangchat-server,代码行数:53,代码来源:ActivationProviders.scala
示例3: Stages
//设置package包名称以及导入依赖的类
package eu.svez.akka.stream
import akka.NotUsed
import akka.stream.FanOutShape2
import akka.stream.scaladsl.{Flow, GraphDSL, Partition}
import scala.util.{Failure, Success, Try}
object Stages {
object PartitionEither {
def apply[A, B]() = GraphDSL.create[FanOutShape2[Either[A, B], A, B]]() { implicit builder: GraphDSL.Builder[NotUsed] =>
import GraphDSL.Implicits._
val left = builder.add(Flow[Either[A, B]].map (_.left.get))
val right = builder.add(Flow[Either[A, B]].map (_.right.get))
val partition = builder.add(Partition[Either[A, B]](2, _.fold(_ ? 0, _ ? 1)))
partition ~> left
partition ~> right
new FanOutShape2[Either[A, B], A, B](partition.in, left.out, right.out)
}
}
implicit class EitherShape[A, B](val shape: FanOutShape2[Either[A, B], A, B]) extends AnyVal {
def left = shape.out0
def right = shape.out1
}
object PartitionTry {
def apply[T]() = GraphDSL.create[FanOutShape2[Try[T], Throwable, T]]() { implicit builder ?
import GraphDSL.Implicits._
val success = builder.add(Flow[Try[T]].collect { case Success(a) ? a })
val failure = builder.add(Flow[Try[T]].collect { case Failure(t) ? t })
val partition = builder.add(Partition[Try[T]](2, _.map(_ ? 1).getOrElse(0)))
partition ~> failure
partition ~> success
new FanOutShape2[Try[T], Throwable, T](partition.in, failure.out, success.out)
}
}
implicit class TryShape[T](val shape: FanOutShape2[Try[T], Throwable, T]) extends AnyVal {
def failure = shape.out0
def success = shape.out1
}
}
开发者ID:svezfaz,项目名称:akka-stream-fp,代码行数:52,代码来源:Stages.scala
示例4: BigfootService
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.services
import com.flipkart.concord.publisher.{RequestType, TPublishRequest, TPublishRequestMetadata, TPublisher}
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.metrics.Instrumented
import com.flipkart.connekt.commons.utils._
import com.flipkart.metrics.Timed
import scala.util.{Failure, Success, Try}
object BigfootService extends Instrumented {
private lazy val phantomSocketPath: String = ConnektConfig.getString("connections.specter.socket").get
private lazy val ingestionEnabled = ConnektConfig.getBoolean("flags.bf.enabled").getOrElse(false)
private lazy val jUnixSocketLibPath = ConnektConfig.getString("connections.specter.lib.path").get
lazy val phantomPublisher: TPublisher[String] = {
if(ingestionEnabled) {
try {
val configLoaderClass = Class.forName("com.flipkart.connekt.util.publisher.PhantomSocketPublisher")
configLoaderClass.getConstructor(classOf[String], classOf[String], classOf[String]).newInstance(jUnixSocketLibPath, phantomSocketPath, "publishToBigFoot").asInstanceOf[TPublisher[String]]
} catch {
case e: Exception =>
ConnektLogger(LogFile.SERVICE).error("Unable to initialize PhantomPublisher", e)
null
}
} else null
}
private def ingest(request: TPublishRequest, requestMetadata: TPublishRequestMetadata): Try[Boolean] = Try {
if(ingestionEnabled) {
phantomPublisher.publish(request, requestMetadata).response match {
case Success(m) if m.equalsIgnoreCase("SUCCESS") => Success(true)
case Success(m) =>
ConnektLogger(LogFile.SERVICE).error(s"Phantom ingestion failed. CommandResponse: $m")
Failure(new Throwable(s"Phantom ingestion failed. CommandResponse: $m"))
case Failure(t) => Failure(t)
}
} else {
Success(true)
}
}.flatten
@Timed("ingestEntity")
def ingestEntity(entityId: String, request: TPublishRequest, entityNamespace: String) = ingest(request, new TPublishRequestMetadata {
override def requestType: RequestType.Value = RequestType.Entity
override def id: String = entityId
override def namespace(): Option[String] = Some(entityNamespace)
})
@Timed("ingestEvent")
def ingestEvent(request: TPublishRequest, eventNamespace: String) = ingest(request, new TPublishRequestMetadata {
override def requestType: RequestType.Value = RequestType.Event
override def id: String = StringUtils.generateRandomStr(25)
override def namespace(): Option[String] = Some(eventNamespace)
})
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:62,代码来源:BigfootService.scala
示例5: ProxyController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.Logger
import play.api.libs.ws._
import play.api.mvc._
import services.ProxyRequestCreator.mapToForwardingRequest
import services.ResultTransformer.transformResult
import services.{DocsterDB, ServerBaseUriNotConfigured, ServerGateway}
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
class ProxyController @Inject()(ws: WSClient)(configStore: DocsterDB, serverGateway: ServerGateway) extends Controller {
implicit val context = play.api.libs.concurrent.Execution.Implicits.defaultContext
def proxy(requestPath: String) = Action.async(parse.tolerantText) { originalRequest =>
val result: Try[Future[Result]] = for {
forwardingRequest <- mapToForwardingRequest(originalRequest, requestPath, configStore)
serverResponse <- Try(serverGateway.forwardRequestToServer(forwardingRequest, ws))
transformedResult <- Try(transformResult(serverResponse, forwardingRequest))
} yield transformedResult
result match {
case Failure(ex) =>
ex match {
case ex: ServerBaseUriNotConfigured =>
Future.successful(Redirect(controllers.routes.AdminController.adminConsole()))
case default =>
Logger.error(ex.getMessage, ex)
Future(InternalServerError(ex.getMessage))
}
case Success(finalResult) => finalResult
}
}
}
开发者ID:innoq,项目名称:docster,代码行数:39,代码来源:ProxyController.scala
示例6: CancerRecord
//设置package包名称以及导入依赖的类
package com.ferhtaydn.models
import java.io.File
import scala.util.{ Failure, Success, Try }
case class CancerRecord(label: Double, gender: Double, age: Double, weight: Double, height: Double, job: String)
object CancerRecord {
private val commaRegex: String = "\\,"
def from(s: String): Option[CancerRecord] = s.split(commaRegex) match {
case Array(result, gender, age, weight, height, job) ?
Some(CancerRecord(result.toDouble, Gender.id(gender).toDouble, age.toDouble, weight.toDouble, height.toDouble, job))
case _ ? None
}
def read(file: String): Seq[CancerRecord] = Try(scala.io.Source.fromFile(file)) match {
case Success(bufferedSource) ?
for {
a ? bufferedSource.getLines().toSeq.map(CancerRecord.from)
b ? a
} yield b
case Failure(exception) ? Seq.empty[CancerRecord]
}
}
开发者ID:ferhtaydn,项目名称:canceRater,代码行数:29,代码来源:CancerRecord.scala
示例7: FlowToFutureSpec
//设置package包名称以及导入依赖的类
package akka.stream
import akka.stream.testkit.AkkaSpec
import akka.stream.testkit.ScriptedTest
import scala.concurrent.forkjoin.ThreadLocalRandom.{ current ? random }
import akka.stream.testkit.StreamTestKit
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.Failure
import akka.stream.scaladsl.Flow
class FlowToFutureSpec extends AkkaSpec with ScriptedTest {
val materializer = FlowMaterializer(MaterializerSettings(
initialInputBufferSize = 2,
maximumInputBufferSize = 16,
initialFanOutBufferSize = 1,
maxFanOutBufferSize = 16))
"A Flow with toFuture" must {
"yield the first value" in {
val p = StreamTestKit.producerProbe[Int]
val f = Flow(p).toFuture(materializer)
val proc = p.expectSubscription
proc.expectRequestMore()
proc.sendNext(42)
Await.result(f, 100.millis) should be(42)
proc.expectCancellation()
}
"yield the first error" in {
val p = StreamTestKit.producerProbe[Int]
val f = Flow(p).toFuture(materializer)
val proc = p.expectSubscription
proc.expectRequestMore()
val ex = new RuntimeException("ex")
proc.sendError(ex)
Await.ready(f, 100.millis)
f.value.get should be(Failure(ex))
}
"yield NoSuchElementExcption for empty stream" in {
val p = StreamTestKit.producerProbe[Int]
val f = Flow(p).toFuture(materializer)
val proc = p.expectSubscription
proc.expectRequestMore()
proc.sendComplete()
Await.ready(f, 100.millis)
f.value.get match {
case Failure(e: NoSuchElementException) ? e.getMessage() should be("empty stream")
case x ? fail("expected NoSuchElementException, got " + x)
}
}
}
}
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:59,代码来源:FlowToFutureSpec.scala
示例8: InventoryLogController
//设置package包名称以及导入依赖的类
package controllers
import java.io.File
import play.api.http.ContentTypes
import play.api.mvc.{Action, Controller}
import service.InventoryLogService
import util.JsonUtil
import scala.util.{Failure, Success, Try}
object InventoryLogController extends Controller {
def create = Action {
InventoryLogService.createSchema
Ok("Schema Created")
}
def truncate = Action {
InventoryLogService.truncateData
Ok("Schema Truncated")
}
def upload = Action(parse.multipartFormData) { implicit request =>
val files = request.body.files
Try(files.map { file =>
val tmpFile = file.ref.moveTo(new File(s"/tmp/${file.filename}"))
InventoryLogService.populateSchema(tmpFile)
tmpFile.delete
}) match {
case Success(_) => if(files.size <= 0) BadRequest("File Not uploaded!!") else Ok("File Uploaded")
case Failure(x) => BadRequest(s"Upload Error!! ${x.getMessage}")
}
}
def track = Action { request =>
val trackRequest = request.body.asJson
Try(trackRequest.map { json =>
val objectId = (json \ "object_id").as[Int]
val objectType = (json \ "object_type").as[String]
val timestamp = (json \ "timestamp").as[Long]
InventoryLogService.trackStatus(objectId, objectType, timestamp)
}.getOrElse {
BadRequest("Expecting application/json request body")
}) match {
case Success(x: Some[Any]) => Ok(JsonUtil.toJson(x.getOrElse(Map.empty))).as(ContentTypes.JSON)
case Success(_) => Ok("No updates available")
case Failure(_) => BadRequest("Expecting all input parameters")
}
}
def details = Action {
Ok(JsonUtil.toJson(InventoryLogService.trackDetails)).as(ContentTypes.JSON)
}
}
开发者ID:SarathChandran,项目名称:InventoryTracker,代码行数:58,代码来源:InventoryLogController.scala
示例9: LeakyBucket
//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter
import scala.util.{Success, Failure, Try}
import com.twitter.logging.Logger
import com.lookout.ratelimitingfilter.models._
import com.redis._
object LeakyBucket {
val LOG = Logger.get(getClass)
def processRule(rule: RateLimitRule, leakAndIncFn: (RateLimitRule) => Try[Int]): Boolean = {
leakAndIncFn(rule) match {
case Success(tokenCount) => {
if (tokenCount < rule.threshold) {
true
} else {
LOG.info(s"Request is rate limited with rule id: ${rule.id} and threshold: ${rule.threshold}")
false
}
}
case Failure(error) => throw error
}
}
}
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:26,代码来源:LeakyBucket.scala
示例10: Server
//设置package包名称以及导入依赖的类
package org.goingok.httpServer
import akka.http.scaladsl.Http
import org.goingok.BuildInfo
import org.goingok.data.persistence.db.DatabaseOps
import scala.util.{Failure, Success}
object Server extends GoingOkAPI {
import org.goingok.GoingOkContext._
var dbOk = false
def startServer(address:String, port:Int) = {
log.info("->> STARTING {} - version {} <<-",BuildInfo.name,BuildInfo.version)
log.info("Connecting to DB server")
connectDb
log.info("Starting http server at {}:{}",address,port)
Http().bindAndHandle(routes,address,port)
}
def connectDb: Unit = {
DatabaseOps.version.onComplete {
case Success(result:String) => {
dbOk = true
log.info("Current version is: "+result)
// Create tables that don't exist
DatabaseOps.checkAndCreateTables()
// Get the number of rows for all tables
val tableRows = DatabaseOps.tableSizes()
if(tableRows.isLeft) tableRows.left.map(i => log.info("Database tables exist: {}",i))
else log.error("There was a problem with accessing the database tables")
}
case Failure(e:Exception) => log.error("Could not get version from db: "+e.getMessage)
case _ => log.error("There was a problem getting the version from the database")
}
}
}
开发者ID:GoingOK,项目名称:goingok-server,代码行数:42,代码来源:Server.scala
示例11: spawn
//设置package包名称以及导入依赖的类
package org.dele.text.lapa.patterns
import org.dele.text.lapa.ErrorHandling.{MatcherGenErrorFailed, MatcherGenErrorUndefinedTemplate}
import DomainStructure.LangDomainManager
import org.dele.text.maen.ConfValueStringParser.Parsed
import org.dele.text.maen.matchers.MatcherTmpl.{DomainIdFinder, MatcherTmplLib}
import org.dele.text.maen.matchers.SubMatchCheckerLib._
import org.dele.text.maen.matchers.{MatcherTmpl, MatcherManager, SubMatchCheckerLib, TMatcher}
import org.dele.text.maen.{ConfValueStringParser, AtomPropMatcherLib}
import org.dele.text.maen.matchers.TMatcher.MId
import scala.util.{Failure, Success, Try}
trait TMatcherGen {
def spawn(parsedDefi: Parsed, id:Option[MId], regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib, domain:Option[String]):Try[TMatcher]
}
object TMatcherGen {
private[TMatcherGen] class AtomLibMatcherGen extends TMatcherGen {
import TMatcher._
def spawn(parsedDefi: Parsed, id:Option[MId], regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib, domain:Option[String]):Try[TMatcher] = {
//val parsed = ConfValueStringParser.parse(defi)
if (AtomPropMatcherLib.contains(parsedDefi.id)) Success(fromAtomMatcher(AtomPropMatcherLib.spawn(parsedDefi.id, parsedDefi.paras, regexDict), EmptyCheckerIds, id))
else Failure(MatcherGenErrorUndefinedTemplate(parsedDefi.id))
}
}
val NoMatcherTemplateLibGen:TMatcherGen = new AtomLibMatcherGen
private[TMatcherGen] class MatcherTemplateGen(val tmplLib:MatcherTmplLib) extends TMatcherGen {
def spawn(parsedDefi: Parsed, id:Option[MId], regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib, domain:Option[String]):Try[TMatcher] = {
if (tmplLib.contains(parsedDefi.id)) {
val domainIdFinder:DomainIdFinder = id => if (domain.nonEmpty) domainManager.getFullId(domain.get, id) else domainManager.getGlobalDomainFullId(id)
Success(tmplLib.spawn(parsedDefi.id, parsedDefi.paras, regexDict, id, Option(domainIdFinder)))
}
else Failure(MatcherGenErrorUndefinedTemplate(parsedDefi.id))
}
}
private[TMatcherGen] class ChainedGen(val matcherGens:TMatcherGen*) extends TMatcherGen {
def spawn(parsedDefi: Parsed, id:Option[MId], regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib, domain:Option[String]):Try[TMatcher] = {
val gened = matcherGens.map(_.spawn(parsedDefi, id, regexDict))
val filtered = gened.filter(_.isSuccess)
if (filtered.nonEmpty) filtered(0)
else Failure(MatcherGenErrorFailed(parsedDefi))
}
}
private def TemplateGen(tmplLib:MatcherTmplLib)(implicit subMatchCheckerLib: SubMatchCheckerLib):TMatcherGen = {
new MatcherTemplateGen(tmplLib)
}
def All(tmplLib:MatcherTmplLib)(implicit subMatchCheckerLib: SubMatchCheckerLib):TMatcherGen =
new ChainedGen(TemplateGen(tmplLib), NoMatcherTemplateLibGen)
}
开发者ID:new2scala,项目名称:text-util,代码行数:58,代码来源:TMatcherGen.scala
示例12: MonitoringServer
//设置package包名称以及导入依赖的类
package com.scalaio.http.monitoring
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}
import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._
object MonitoringServer {
lazy val logger = LoggerFactory.getLogger(getClass)
def handleHealthchecks(registry: HealthCheckRegistry): Route = {
path("health") {
get {
complete {
val checks = registry.runHealthChecks
val payload = JsArray(checks.map {
case (name, result) =>
Json.obj(
"name" -> name,
"healthy" -> result.isHealthy,
"message" -> result.getMessage
)
}.toSeq)
val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
}
}
}
}
def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
(implicit system: ActorSystem, materializer: Materializer): Unit = {
val host = serverConfig.getString("host")
val port = serverConfig.getInt("port")
logger.info(s"Starting monitoring server at: $host:$port")
val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
import system.dispatcher
Http()
.bindAndHandle(routes, host, port).onComplete {
case Success(Http.ServerBinding(address)) =>
logger.info(s"Monitoring server started at :$address")
case Failure(t) =>
logger.error("Error while trying to start monitoring server", t)
}
}
}
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala
示例13: AsyncTest
//设置package包名称以及导入依赖的类
package com.bob.scalatour.futures
import org.scalatest.FunSuite
import scala.async.Async._
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}
class AsyncTest extends FunSuite {
implicit val ec = ExecutionContext.global
test("sequential") {
val future = async {
val futureOne = async {
1
}
val futureTwo = async {
2
}
await(futureOne) + await(futureTwo)
}
future onComplete {
case Success(result) => assert(result == 3)
case Failure(failure) => throw failure
}
}
test("parallel") {
val futureOne = async {
1
}
val futureTwo = async {
2
}
val futureThree = async {
await(futureOne) + await(futureTwo)
}
futureThree onComplete {
case Success(result) => assert(result == 3)
case Failure(failure) => throw failure
}
}
}
开发者ID:bobxwang,项目名称:scalatour,代码行数:46,代码来源:AsyncTest.scala
示例14: cx
//设置package包名称以及导入依赖的类
package org.blinkmob
import java.sql.Connection
import javax.sql.DataSource
import resource._
import scala.util.control.ControlThrowable
import scala.util.{Failure, Success, Try}
trait CxProvider{ this:hasDataSource =>
def cx[A](block: Connection => A): A = managed(ds.getConnection()).acquireAndGet(block(_))
def tx[A](block: Connection => A): A ={
cx { c =>
c.setAutoCommit(false)
Try({
val r = block(c)
c.commit()
r
}) match{
case Success(r) => r
case Failure(f) => {
f match{
case e: ControlThrowable => c.commit(); throw e
case e => c.rollback(); throw e
}
}
}
}
}
def rbtx[A](block: Connection => A): A ={
cx { c =>
c.setAutoCommit(false)
Try(block(c)) match{
case Success(r) => c.rollback(); r
case Failure(f) => c.rollback(); throw f
}
}
}
}
开发者ID:gnomff,项目名称:scala-tx-provider,代码行数:49,代码来源:CxProvider.scala
示例15: PipeableFuture
//设置package包名称以及导入依赖的类
package akka.pattern
import language.implicitConversions
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Failure, Success }
import akka.actor.{ Status, ActorRef, Actor }
import akka.actor.ActorSelection
trait PipeToSupport {
final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) {
def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
future onComplete {
case Success(r) ? recipient ! r
case Failure(f) ? recipient ! Status.Failure(f)
}
future
}
def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
future onComplete {
case Success(r) ? recipient ! r
case Failure(f) ? recipient ! Status.Failure(f)
}
future
}
def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender)
def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = {
pipeTo(recipient)(sender)
this
}
def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender)
def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = {
pipeToSelection(recipient)(sender)
this
}
}
implicit def pipe[T](future: Future[T])(implicit executionContext: ExecutionContext): PipeableFuture[T] = new PipeableFuture(future)
}
开发者ID:Starofall,项目名称:Chakka,代码行数:41,代码来源:PipeToSupport.scala
示例16: ConfigHandler
//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender.config
import org.hpi.esb.commons.config.Configs
import org.hpi.esb.commons.util.Logging
import pureconfig.loadConfigFromFiles
import scopt.OptionParser
import scala.util.{Failure, Success}
import scalax.file.Path
object ConfigHandler extends Logging {
val projectPath = System.getProperty("user.dir")
val dataSenderPath = s"$projectPath/tools/datasender"
val configName = "datasender.conf"
val userConfigPath = s"$dataSenderPath/$configName"
val resultsPath = s"$dataSenderPath/results"
val config: Config = getConfig()
def resultFileName(currentTime: String): String = s"${Configs.benchmarkConfig.topicPrefix}_" +
s"${Configs.benchmarkConfig.benchmarkRun}_$currentTime.csv"
def resultFileNamePrefix(): String = s"${Configs.benchmarkConfig.topicPrefix}"
private def getConfig(): Config = {
if (!Path.fromString(userConfigPath).exists && Path.fromString(userConfigPath).isFile) {
logger.error(s"The config file '$userConfigPath' does not exist.")
sys.exit(1)
}
val config = loadConfigFromFiles[Config](Seq[java.io.File](new java.io.File(userConfigPath))) match {
case Failure(f) => {
logger.error(s"Invalid configuration for file $userConfigPath")
logger.error(f.getMessage())
sys.exit(1)
}
case Success(conf) => conf
}
if (!config.isValid) {
logger.error(s"Invalid configuration:\n${config.toString}")
sys.exit(1)
}
config
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:46,代码来源:ConfigHandler.scala
示例17: UndoManager
//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.util
import scala.collection.mutable
import scala.util.{Failure, Try}
case class UndoManager(
var undoStack: mutable.Stack[Command] = mutable.Stack(),
var redoStack: mutable.Stack[Command] = mutable.Stack()
) {
def clearUndoStack(): Unit = undoStack.clear()
def doIt(com: Command): Try[_] = {
val result = com.doIt()
if (result.isSuccess) {
undoStack.push(com)
redoStack.clear()
}
result
}
def undo(): Try[_] = {
if (undoStack.nonEmpty) {
val temp = undoStack.pop()
val result = temp.undo()
if (result.isSuccess) {
redoStack.push(temp)
}
result
} else {
Failure(new Exception("Can't undo now!"))
}
}
def redo(): Try[_] = {
if (redoStack.nonEmpty) {
val temp = redoStack.pop()
val result = temp.doIt()
if (result.isSuccess) {
undoStack.push(temp)
}
result
} else {
Failure(new Exception("Can't redo now!"))
}
}
}
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:46,代码来源:UndoManager.scala
示例18: Prepare
//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.controller.basicImpl
import de.htwg.se.SevenSteps.controller.{IController, IFinish, IPlay, IPrepare}
import de.htwg.se.SevenSteps.util.Command
import scala.util.{Failure, Try}
case class Prepare() extends IPrepare {
override def exploreCommand(com: Command, c: IController): Try[_] = {
com match {
case _: AddPlayer => c.undoManager.doIt(com)
case _: NewGrid => c.undoManager.doIt(com)
case _: StartGame => c.undoManager.doIt(com)
case _: SetColor => c.undoManager.doIt(com)
case _ => Failure(new Exception("ILLEGAL COMMAND"))
}
}
}
case class Play() extends IPlay {
override def exploreCommand(com: Command, c: IController): Try[_] = {
com match {
case _: NextPlayer => c.undoManager.doIt(com)
case _: SetStone => c.undoManager.doIt(com)
case _: NewGame => c.undoManager.doIt(com)
case _ => Failure(new Exception("ILLEGAL COMMAND Play"))
}
}
}
case class Finish() extends IFinish {
override def exploreCommand(com: Command, c: IController): Try[_] = {
com match {
case _: NewGame => c.undoManager.doIt(com)
case _ => Failure(new Exception("ILLEGAL COMMAND"))
}
}
}
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:39,代码来源:GameState.scala
示例19: query
//设置package包名称以及导入依赖的类
package cz.alenkacz.db.postgresscala
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Failure
trait Connection extends AutoCloseable {
def query[T](query: String, deserializer: Row => T): Future[Seq[T]]
def queryValue[T](query: String): Future[Option[T]]
def execute[T](query: String, values: Seq[Any] = Seq.empty): Future[Unit]
def count(query: String): Future[Long]
def sendPreparedStatementForValue[T](query: String, values: Seq[Any] = Seq.empty): Future[Option[T]]
def sendPreparedStatement[T](query: String, values: Seq[Any], deserializer: Row => T): Future[Seq[T]]
def sendPreparedStatement[T](query: String, deserializer: Row => T): Future[Seq[T]]
def inTransaction[A](f : Connection => Future[A])(implicit ec : ExecutionContext) : Future[A] = {
execute("BEGIN").flatMap { _ =>
val p = Promise[A]()
f(this).onComplete { r =>
execute(if (r.isFailure) "ROLLBACK" else "COMMIT").onComplete {
case Failure(e) if r.isSuccess => p.failure(e)
case _ => p.complete(r)
}
}
p.future
}
}
}
开发者ID:alenkacz,项目名称:postgres-scala,代码行数:28,代码来源:Connection.scala
示例20: validate
//设置package包名称以及导入依赖的类
package org.ergoplatform.nodeView.history.storage.modifierprocessors.popow
import com.google.common.primitives.Ints
import io.iohk.iodb.ByteArrayWrapper
import org.ergoplatform.modifiers.ErgoPersistentModifier
import org.ergoplatform.modifiers.history.{HistoryModifierSerializer, PoPoWProof}
import org.ergoplatform.nodeView.history.storage.modifierprocessors.HeadersProcessor
import org.ergoplatform.settings.Constants
import scorex.core.consensus.History.ProgressInfo
import scala.util.{Failure, Success, Try}
trait FullPoPoWProofsProcessor extends PoPoWProofsProcessor with HeadersProcessor {
def validate(m: PoPoWProof): Try[Unit] = m.validate.map { _ =>
//TODO what if we trying to apply better popow proof?
//TODO validate difficulty for suffix
if (height > 1) Failure(new Error("Trying to apply PoPoW proof to nonempty history"))
else Success()
}
def process(m: PoPoWProof): ProgressInfo[ErgoPersistentModifier] = {
val headers = m.innerchain ++ m.suffix
val bestHeader = m.suffix.last
val headersRows: Seq[(ByteArrayWrapper, ByteArrayWrapper)] = headers.zipWithIndex.flatMap { case (h, i) =>
//TODO howto?
val requiredDifficulty: BigInt = Constants.InitialDifficulty
Seq((ByteArrayWrapper(h.id), ByteArrayWrapper(HistoryModifierSerializer.toBytes(h))),
//TODO howto?
(headerHeightKey(h.id), ByteArrayWrapper(Ints.toByteArray(2 + i))),
//TODO howto?
(headerScoreKey(h.id), ByteArrayWrapper((requiredDifficulty * (1 + i)).toByteArray)),
(headerDiffKey(h.id), ByteArrayWrapper(requiredDifficulty.toByteArray)))
}
val bestHeaderRow = (BestHeaderKey, ByteArrayWrapper(bestHeader.id))
historyStorage.insert(bestHeader.id, bestHeaderRow +: headersRows)
ProgressInfo(None, Seq(), Seq(m.suffix.last))
}
}
开发者ID:ergoplatform,项目名称:ergo,代码行数:41,代码来源:FullPoPoWProofsProcessor.scala
注:本文中的scala.util.Failure类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论