本文整理汇总了Scala中scala.util.Success类的典型用法代码示例。如果您正苦于以下问题:Scala Success类的具体用法?Scala Success怎么用?Scala Success使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Success类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: TwitterScalaFuture
//设置package包名称以及导入依赖的类
package io.koff.pagination.utils
import com.twitter.util.{Future => TwitterFut, Promise => TwitterProm}
import scala.concurrent.{ExecutionContext, Future => ScalaFut, Promise => ScalaProm}
import scala.util.{Failure, Success, Try}
import com.twitter.{util => twitter}
object TwitterScalaFuture {
implicit def scalaToTwitterTry[T](t: Try[T]): twitter.Try[T] = t match {
case Success(r) => twitter.Return(r)
case Failure(ex) => twitter.Throw(ex)
}
implicit def twitterToScalaTry[T](t: twitter.Try[T]): Try[T] = t match {
case twitter.Return(r) => Success(r)
case twitter.Throw(ex) => Failure(ex)
}
// Twitter -> Scala
implicit class TwitterToScala[T](val twitterFut: TwitterFut[T]) extends AnyVal {
def toScala: ScalaFut[T] = {
val promise = ScalaProm[T]()
twitterFut.respond(promise complete _)
promise.future
}
}
implicit class ScalaToTwitter[T](val scalaFut: ScalaFut[T]) extends AnyVal {
def toTwitter(implicit execCtx: ExecutionContext): TwitterFut[T] = {
val promise = TwitterProm[T]()
scalaFut.onComplete { result => promise.update(result) }
promise
}
}
}
示例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)
}
}
示例3: SeqUpdatesManagerRegion
//设置package包名称以及导入依赖的类
package im.actor.server.sequence
import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.cluster.sharding.{ ClusterSharding, ClusterShardingSettings, ShardRegion }
import akka.event.Logging
import scala.util.{ Success, Try }
final case class SeqUpdatesManagerRegion(ref: ActorRef)
object SeqUpdatesManagerRegion {
import UserSequenceCommands._
private def extractEntityId(system: ActorSystem): ShardRegion.ExtractEntityId = {
val log = Logging(system, getClass)
{
case e @ Envelope(userId, payload) ? (userId.toString, Try(e.getField(Envelope.descriptor.findFieldByNumber(payload.number))) match {
case Success(any) ? any
case _ ?
val error = new RuntimeException(s"Payload not found for $e")
log.error(error, error.getMessage)
throw error
})
}
}
private val extractShardId: ShardRegion.ExtractShardId = {
case Envelope(userId, _) ? (userId % 10).toString // TODO: configurable
}
private val typeName = "SeqUpdatesManager"
private def start(props: Props)(implicit system: ActorSystem): SeqUpdatesManagerRegion =
SeqUpdatesManagerRegion(ClusterSharding(system).start(
typeName = typeName,
entityProps = props,
settings = ClusterShardingSettings(system),
extractEntityId = extractEntityId(system),
extractShardId = extractShardId
))
def start()(
implicit
system: ActorSystem
): SeqUpdatesManagerRegion =
start(UserSequence.props)
def startProxy()(implicit system: ActorSystem): SeqUpdatesManagerRegion =
SeqUpdatesManagerRegion(ClusterSharding(system).startProxy(
typeName = typeName,
role = None,
extractEntityId = extractEntityId(system),
extractShardId = extractShardId
))
}
示例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)
})
}
示例5: MessageParser
//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.collector.parsing
import java.time.ZonedDateTime
import FromCSVtoCaseClass.rowParserFor
import com.darienmt.airplaneadventures.basestation.data.BaseStation._
import scala.util.{ Failure, Success, Try }
object MessageParser {
def apply(l: String): Message = parse(l.split(",").toList) match {
case Success(m) => m
case Failure(ex) => ErrorMessage(l, ex.toString, ZonedDateTime.now())
}
protected val parse: List[String] => Try[Message] = {
case "SEL" :: "" :: rest => rowParserFor[SelectionChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "ID" :: "" :: rest => rowParserFor[IdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "AIR" :: "" :: rest => rowParserFor[NewAircraftMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10))
case "STA" :: "" :: rest => rowParserFor[StatusChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "CLK" :: "" :: rest => rowParserFor[ClickMessage](rest, List(3, 7, 8, 9, 10))
case "MSG" :: "1" :: rest => rowParserFor[ESIdentificationAncCategoryMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "MSG" :: "2" :: rest => rowParserFor[ESSurfacePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 22))
case "MSG" :: "3" :: rest => rowParserFor[ESAirbornePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 19, 20, 21, 22))
case "MSG" :: "4" :: rest => rowParserFor[ESAirborneVelocityMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 17))
case "MSG" :: "5" :: rest => rowParserFor[SurveillanceAltMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 19, 21, 22))
case "MSG" :: "6" :: rest => rowParserFor[SurveillanceIdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 19, 20, 21, 22))
case "MSG" :: "7" :: rest => rowParserFor[AirToAirMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 22))
case "MSG" :: "8" :: rest => rowParserFor[AllCallReplyMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 22))
case x => Failure(new Exception(s"Unknown message => $x"))
}
}
示例6: Util
//设置package包名称以及导入依赖的类
package com.github.atais.util
import scala.util.{Success, Try}
object Util {
// https://stackoverflow.com/a/22533154/1549135
implicit class RichTry[T](t: Try[T]) {
def toEither: Either[Throwable, T] = t.transform(s => Success(Right(s)), f => Success(Left(f))).get
}
implicit class RichEither[A, B](t: Either[A, B]) {
def toOption: Option[B] = t match {
case Right(v) => Some(v)
case Left(_) => None
}
}
}
示例7: Game
//设置package包名称以及导入依赖的类
package main.scala.swayvil.langtonant
import swayvil.langtonant.Matrix
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure
import scala.concurrent.duration.Duration
import swayvil.langtonant.gui.CompositeGUI
class Game() {
var turn: Int = 0
private val turnTime: Long = 2 // ms
var gui: CompositeGUI = null
private var isRunning: Boolean = true
val matrixSize: Int = 80
var m: Matrix = new Matrix(matrixSize)
private var ant: Ant = new Ant(m)
def nextTurn() {
if (!isRunning)
return
turn += 1
if (!ant.move()) {
isRunning = false
} else {
val f: Future[Int] = Future {
Thread.sleep(turnTime)
0
}
f onComplete {
case Success(v) => {
if (isRunning) {
nextTurn()
gui.repaint()
}
}
case Failure(v) => { println("FAILURE") }
}
}
}
def pauseOrResume() {
isRunning = !isRunning
if (isRunning)
nextTurn()
}
}
示例8: AnimationService
//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.services
import org.scalajs.dom.html
import org.danielnixon.saferdom.implicits._
import scala.concurrent.{ Future, Promise }
import scala.scalajs.js.timers._
import scala.util.Success
class AnimationService {
private def transition(element: html.Element, show: Boolean, preserveHeight: Boolean, durationOpt: Option[Int]): Future[Unit] = {
val initialMinHeight = element.getAttributeOpt("data-initial-min-height") getOrElse {
val m = element.style.minHeight
element.setAttribute("data-initial-min-height", m)
m
}
val minHeight = if (preserveHeight) s"${element.getBoundingClientRect.height}px" else initialMinHeight
val duration = {
val defaultDuration = 400
durationOpt.getOrElse(defaultDuration)
}
element.style.minHeight = minHeight
element.style.transition = s"opacity ${duration}ms ease"
element.style.opacity = if (show) "1" else "0"
val promise = Promise[Unit]()
setTimeout(duration.toDouble)(promise.complete(Success(())))
promise.future
}
def transitionOut(element: html.Element, duration: Option[Int]): Future[Unit] = {
transition(element, false, true, duration)
}
def transitionIn(element: html.Element, preserveHeight: Boolean = false): Future[Unit] = {
transition(element, true, preserveHeight, None)
}
}
示例9: parseResult
//设置package包名称以及导入依赖的类
package neo4j.client
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.util.{ Success, Failure, Try }
trait CypherResultParser extends CypherResponseParser {
override def parseResult[R](result: JsValue)(implicit parser: Reads[R]): Try[Seq[R]] = {
val rows = (result \ "data").as[JsArray].value.map(row ? {
// TODO: there should be a cleaner way of doing this; perhaps by looking at the returned "columns" field.
val r = row \ "row"
if (r.apply(1).toOption.isDefined) {
r
} else {
r(0)
}
})
val parsed = rows.map(row ? row.validate[R])
if (parsed.forall(res ? res.isSuccess)) {
Success(parsed.map(_.get))
} else {
val e = buildErrorMessage(parsed.filter(_.isError).asInstanceOf[Seq[JsError]])
Failure(new JsonValidationException(e.mkString("\n"), Some(result)))
}
}
}
object CypherResultAndErrorParser extends CypherResultParser with CypherErrorParser
object CypherErrorOnlyParser extends CypherNoopResultParser with CypherErrorParser
示例10: LocalDateTimeCoercionViolation
//设置package包名称以及导入依赖的类
package io.soheila.cms.api
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import sangria.ast.StringValue
import sangria.schema.ScalarType
import sangria.validation.ValueCoercionViolation
import scala.util.{ Failure, Success, Try }
package object graphql {
case object LocalDateTimeCoercionViolation extends ValueCoercionViolation("Date value expected")
case object LocaleCoercionViolation extends ValueCoercionViolation("Locale value expected")
private[graphql] def parseLocalDateTime(s: String) = Try(LocalDateTime.parse(s)) match {
case Success(date) => Right(date)
case Failure(_) => Left(LocalDateTimeCoercionViolation)
}
private[graphql] def parseLocale(s: String) = Try(Locale.forLanguageTag(s)) match {
case Success(locale) => Right(locale)
case Failure(_) => Left(LocaleCoercionViolation)
}
val LocalDateTimeType = ScalarType[LocalDateTime](
"LocalDateTime",
coerceOutput = (value, caps) => value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
coerceUserInput = {
case s: String => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
}
)
val LocaleType = ScalarType[Locale](
"Locale",
coerceOutput = (value, caps) => value.toLanguageTag,
coerceUserInput = {
case s: String => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
}
)
}
示例11: TestUtils
//设置package包名称以及导入依赖的类
package utils
import com.bryzek.apidoc.test.light.v0.errors.UnitResponse
import scala.util.{Failure, Success, Try}
object TestUtils {
def expectStatus(code: Int)(f: => Unit) {
Try(
f
) match {
case Success(response) => {
org.specs2.execute.Failure(s"Expected HTTP[$code] but got HTTP 2xx")
}
case Failure(ex) => ex match {
case UnitResponse(code) => {
org.specs2.execute.Success()
}
case e => {
org.specs2.execute.Failure(s"Unexpected error: $e")
}
}
}
}
}
示例12: 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]
}
}
示例13: 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)
}
示例14: stringPersister
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import akka.NotUsed
import akka.stream._
import akka.stream.scaladsl.{Broadcast, Flow, GraphDSL, Sink}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.Future
import scala.util.{Failure, Success}
def stringPersister(pf: String => Future[Unit]): Flow[String, String, NotUsed] =
Flow.fromGraph(GraphDSL.create() { implicit builder =>
import GraphDSL.Implicits._
val persistenceSink = Sink.foreach[String] { content =>
val f = pf(content)
f.onComplete {
case Success(u) => Logger.debug(s"Persisted content: '$content'")
case Failure(t) => Logger.error(s"Failed to persist content: '$content", t)
}
}
val bcast = builder.add(Broadcast[String](2))
bcast.out(1) ~> persistenceSink
FlowShape(bcast.in, bcast.out(0))
})
}
示例15: 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)
}