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

Scala Success类代码示例

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

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



在下文中一共展示了Success类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
    }
  }
} 
开发者ID:coffius,项目名称:koffio-pagination,代码行数:37,代码来源:TwitterScalaFuture.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: 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
    ))
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:58,代码来源:SeqUpdatesManagerRegion.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: 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"))
  }
} 
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:33,代码来源:MessageParser.scala


示例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
    }
  }

} 
开发者ID:atais,项目名称:Fixed-Length,代码行数:20,代码来源:Util.scala


示例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()
  }
} 
开发者ID:swayvil,项目名称:langton-ant,代码行数:51,代码来源:Game.scala


示例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)
  }
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:42,代码来源:AnimationService.scala


示例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 
开发者ID:mardambey,项目名称:neo4j-scala-dsl,代码行数:36,代码来源:CypherResponseParser.scala


示例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)
    }
  )
} 
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:53,代码来源:package.scala


示例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")
        }
      }
    }
  }
} 
开发者ID:mbryzek,项目名称:apidoc-test,代码行数:28,代码来源:TestUtils.scala


示例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]
  }

} 
开发者ID:ferhtaydn,项目名称:canceRater,代码行数:29,代码来源:CancerRecord.scala


示例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)
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:41,代码来源:PipeToSupport.scala


示例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))
    })
} 
开发者ID:snackCake,项目名称:TweetStreamChallenge,代码行数:33,代码来源:PersistenceService.scala


示例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)
} 
开发者ID:new2scala,项目名称:text-util,代码行数:58,代码来源:TMatcherGen.scala


示例16: TestAtom

//设置package包名称以及导入依赖的类
package org.dele.text.maen.test

import org.dele.text.maen.ErrorHandling.{AtomErrorMultvalueProp, AtomErrorNoProp}
import org.dele.text.maen.ErrorHandling
import org.dele.text.maen.TAtom

import scala.util.{Failure, Success, Try}


object TestAtom {
  object Atom {
    val EmptyPropValueSet = Set[String]()
    import org.dele.text.maen.ErrorHandling._
    private[Atom] class _Atom(val _text:String, val _propMap:Map[String,Set[String]]) extends TAtom {
      def text = _text
      def propValue(propName:String):Try[String] = {
        if (_propMap.contains(propName)) {
          val values = _propMap.get(propName).get
          if (values.size != 1) {
            Failure(AtomErrorMultvalueProp(propName, values))
          }
          else Success(values.toList(0))
        }
        else Failure(AtomErrorNoProp(propName))
      }

      def propValues(propName:String):Try[Set[String]] =
        if (_propMap.contains(propName)) Success(_propMap.get(propName).get) else Failure(AtomErrorNoProp(propName))
    }

    def apply(text:String, propMap:Map[String,Set[String]]):TAtom = new _Atom(text, propMap)

  }

  def entityAtom(text:String, entityTypes:String*):TAtom = Atom(text, Map("entityType" -> entityTypes.toSet))

  val EmptyPropMap = Map[String,Set[String]]()
  def textAtom(text:String):TAtom = Atom(text, EmptyPropMap)

  val FBI = entityAtom("FBI", "Organization", "OrgEntity")
  val CIA = entityAtom("CIA", "Organization", "OrgEntity")
  val Anonymous = //entityAtom("Anonymous", "Organization", "OrgEntity")
    Atom("Anonymous", Map("entityType" -> Set("Organization", "OrgEntity"), "category" -> Set("ThreatActor")))
  val Microsoft = entityAtom("Microsoft", "Company", "OrgEntity")
  val _and = textAtom("and")
  val _comma = textAtom(",")
} 
开发者ID:new2scala,项目名称:text-util,代码行数:48,代码来源:TestAtom.scala


示例17: 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


示例18: 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


示例19: Players

//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.model.player.mockImpl

import de.htwg.se.SevenSteps.model.player.{IPlayer, IPlayers}

import scala.collection.immutable.Map
import scala.util.{Success, Try}
import scala.xml.Elem

case class Players() extends IPlayers {
  def push(name: String): IPlayers = this
  def pop(): IPlayers = this
  def length: Int = 1
  def updateCurPlayer(player: IPlayer): IPlayers = this
  def next(): IPlayers = this
  def nonEmpty: Boolean = true
  def getCurPlayer: IPlayer = Player()
  def setColors(colors: List[Char]): IPlayers = this
  def setAllStonesTo(num: Int): IPlayers = this
  def apply(i: Int): IPlayer = Player()
  def haveNoStones: Boolean = false
  def getAllPossibleColorsFromAllPlayers: List[Char] = List()
  def reset: IPlayers = this
  def toXML: Vector[Elem] = Vector(<el el=""></el>)

}

case class Player() extends IPlayer {
  def getStoneNumber: Int = 2
  def placeStone(color: Char, height: Int): Try[IPlayer] = Success(this)
  def incPoints(delta: Int): IPlayer = this
  def incColor(color: Char, delta: Int): IPlayer = this
  def name: String = "Hans"
  def points: Int = 10
  def map: Option[Map[String, Double]] = None
  def haveNoStones: Boolean = true
  def toXML: Elem = <el el=""></el>

} 
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:39,代码来源:PlayerMock.scala


示例20: DigestState

//设置package包名称以及导入依赖的类
package org.ergoplatform.nodeView.state

import org.ergoplatform.modifiers.{ErgoFullBlock, ErgoPersistentModifier}
import scorex.core.transaction.state.MinimalState.VersionTag
import ErgoState.Digest
import scorex.core.utils.ScorexLogging
import scorex.crypto.hash.Blake2b256Unsafe

import scala.util.{Failure, Success, Try}


class DigestState(override val rootHash: Digest) extends ErgoState[DigestState] with ScorexLogging {

  implicit val hf = new Blake2b256Unsafe

  override def version: VersionTag = ???

  override def validate(mod: ErgoPersistentModifier): Try[Unit] = mod match {
    case fb: ErgoFullBlock =>
      Try {
        assert(hf(fb.aDProofs.get.bytes).sameElements(fb.header.ADProofsRoot))

        val txs = fb.blockTransactions.txs
        val declaredHash = fb.header.stateRoot

        txs.foldLeft(Success(): Try[Unit]) { case (status, tx) =>
          status.flatMap(_ => tx.semanticValidity)
        }.flatMap(_ => fb.aDProofs.map(_.verify(boxChanges(txs), rootHash, declaredHash))
          .getOrElse(Failure(new Error("Proofs are empty"))))
      }.flatten
    case a: Any => log.info(s"Modifier not validated: $a"); Try(this)
  }

  //todo: utxo snapshot could go here
  override def applyModifier(mod: ErgoPersistentModifier): Try[DigestState] = mod match {
    case fb: ErgoFullBlock =>
      validate(fb).map(_ => new DigestState(fb.header.stateRoot))
    case a: Any => log.info(s"Unhandled modifier: $a"); Try(this)
  }

  override def rollbackTo(version: VersionTag): Try[DigestState] = ???
} 
开发者ID:ergoplatform,项目名称:ergo,代码行数:43,代码来源:DigestState.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Failure类代码示例发布时间:2022-05-23
下一篇:
Scala global类代码示例发布时间: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