当前位置: 首页>>代码示例>>Scala>>正文


Scala breakOut类代码示例

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


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

示例1: parse

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

import java.io.{InputStream, InputStreamReader}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths}
import javax.script.ScriptEngineManager

import com.google.common.base.Charsets
import com.google.common.io.CharStreams
import org.luaj.vm2.{LuaTable, LuaValue}

import scala.collection.breakOut
import scala.io.Source

trait FactorioParser[T] {
  import FactorioParser._

  def parse(path: String): Seq[T] = commonParse(readAll(path))
  def parse(path: Path): Seq[T] = commonParse(readAll(path))
  def parse(is: InputStream): Seq[T] = {
    val str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8))
    commonParse(str)
  }

  def transport(table: LuaTable): Option[T]

  private[this] def commonParse(target: String): Seq[T] = {
    val dataLua = Source.fromURL(getClass.getResource("/data.lua")).mkString
    val lua = dataLua + target
    val engine = manager.getEngineByName("luaj")
    engine.eval(lua)
    val array: LuaTable = engine.get("array").asInstanceOf[LuaTable]
    tableToSeq(array)(_.checktable()).flatMap(transport)
  }
}

object FactorioParser {
  private val manager = new ScriptEngineManager()

  def readAll(path: String): String = readAll(Paths.get(path))

  def readAll(path: Path): String =
    new String(Files.readAllBytes(path), StandardCharsets.UTF_8)

  def tableToSeq[T](table: LuaTable)(f: LuaValue => T): Seq[T] = {
    table.keys().map(table.get).map(f)(breakOut)
  }

  def tableToMap[K, V](table: LuaTable)(f: LuaValue => K)(g: LuaValue => V): Map[K, V] = {
    table.keys().map { key =>
      f(key) -> g(table.get(key))
    }(breakOut)
  }


} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:57,代码来源:FactorioParser.scala

示例2: TrainResponse

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

import models._
import scalikejdbc.DBSession
import utils.TrainTime

import scala.collection.breakOut

case class TrainResponse(
  id: Long,
  start: TrainTime,
  diagramId: Long,
  name: String,
  trainType: TrainType,
  subType: String,
  stops: Seq[TrainStopResponse]
)

object TrainResponse {
  def fromTrainId(id: Long)(implicit session: DBSession): Option[TrainResponse] = {
    for {
      train <- Train.findById(id)
      diagram <- Diagram.joins(Diagram.stopStationRef).findById(train.diagramId)
    } yield fromTrainDiagram(train, diagram)
  }

  // diagram??stopStationRef?join???????
  def fromTrainDiagram(train: Train, diagram: Diagram): TrainResponse = {
    val lineStationIds = diagram.stops.map(_.lineStationId)
    val lineStations: Map[Long, LineStation] = LineStation.joins(LineStation.stationRef, LineStation.lineRef)
      .findAllByIds(lineStationIds.distinct: _*)
      .map { ls => ls.id -> ls }(breakOut)
    val trainStops = diagram.stops.flatMap { stop =>
      lineStations.get(stop.lineStationId).map { ls =>
        TrainStopResponse.fromObj(train, stop, ls)
      }
    }
    fromObj(train, diagram, trainStops)
  }

  def fromObj(train: Train, diagram: Diagram, stops: Seq[TrainStopResponse]): TrainResponse =
    TrainResponse(train.id, train.start, diagram.id, diagram.name, diagram.trainType, diagram.subType, stops)

}

case class TrainStopResponse(
  id: Long,
  arrival: Option[TrainTime],
  departure: Option[TrainTime],
  lineStation: LineStation,
  line: Line,
  station: Station
)

object TrainStopResponse {
  def fromObj(train: Train, ss: StopStation, ls: LineStation): TrainStopResponse = {
    val arrival = ss.arrival.map(train.start.addMinutes)
    val departure = ss.departure.map(train.start.addMinutes)
    TrainStopResponse(ss.id, arrival, departure, ls, ls.line.get, ls.station.get)
  }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:62,代码来源:TrainResponse.scala

示例3: StopDetail

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

import scala.xml.NodeSeq
import scala.collection.breakOut

case class StopDetail(
  name: String,
  url: String,
  code: Option[Int],
  no: Option[String],
  departure: TrainRun,
  arrive: TrainRun
)

object StopDetail {
  import utils.ParseHelper._

  val ReCode = """\((\d+)\)""".r

  def fromXML(xml: NodeSeq): Option[StopDetail] = {
    val tds: Seq[String] = (xml \ "td").map { elem => (elem \ "span").text }(breakOut)
    for {
      url <- (xml \\ "a" \ "@href").headOption
      sta <- tds.lift(0)
      stop <- tds.lift(1)
      xs = normList('\n')(sta)
      ys = normList('\n')(stop)
      if 2 <= ys.length && 1 <= xs.length
      name = xs.head
      code = xs.lift(1).flatMap(ReCode.findFirstMatchIn(_)).map(_.group(1).toInt)
      Seq(arr, dep) = ys.map(TrainRun.fromString)
      no = tds.lift(2).map(norm).filter(_.nonEmpty)
    } yield StopDetail(name, normURL(url.text), code, no, dep, arr)
  }

  def normURL(url: String) = url.replace("../../", "/newdata/station/")
}

sealed abstract class TrainRun

object TrainRun {
  val ReTime = """(\d\d)\:(\d\d).*""".r
  case class Time(hour: Int, minutes: Int) extends TrainRun
  case object Pass extends TrainRun
  case object NotService extends TrainRun

  def fromString(str: String): TrainRun =
    str match {
      case "?" => Pass
      case ReTime(hour, minutes) => Time(hour.toInt, minutes.toInt)
      case _ => NotService
    }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:54,代码来源:StopDetail.scala

示例4: SearchMissions

//设置package包名称以及导入依赖的类
package queries
import models.{Mission, Station}
import play.api.data.Form
import play.api.data.Forms._
import scalikejdbc._

import scala.collection.breakOut

case class SearchMissions(
    rank: Option[RankRate],
    score: Boolean,
    stationName: Option[String],
    name: Option[String],
    creator: Option[Long]
) {
  def filter()(implicit session: DBSession) = {
    import models.DefaultAliases.s
    val stations: Option[Set[Long]] = stationName.map { n =>
      Station.findAllBy(sqls.like(s.name, s"%${n}%")).map(_.id)(breakOut)
    }
    MissionFilter(rank, stations)
  }

  def where: SQLSyntax = {
    import models.DefaultAliases.m
    sqls.toAndConditionOpt(
      creator.map { creator => sqls.eq(m.creator, creator) },
      name.map { str => sqls.like(m.name, s"%${str}%") }
    ).getOrElse(sqls"true")
  }
}

case class MissionFilter(rank: Option[RankRate], stations: Option[Set[Long]]) {
  def apply(x: Mission): Boolean = {
    rank.forall(RankRate.findSize(x.stations.size) == _) &&
      stations.forall { sts =>
        sts.contains(x.startStationId) ||
          x.stations.exists { st => sts.contains(st.id) }
      }
  }
}

object SearchMissions {
  val form = Form(
    mapping(
      "rank" -> optional(text(minLength = 1).verifying(RankRate.constraint).transform[RankRate](RankRate.find(_).get, _.toString)),
      "score" -> optional(boolean).transform[Boolean](_.getOrElse(false), Some(_)),
      "station_name" -> optional(text(minLength = 1)),
      "name" -> optional(text(minLength = 1)),
      "creator" -> optional(longNumber(min = 1))
    )(SearchMissions.apply)(SearchMissions.unapply)
  )
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:54,代码来源:SearchMissions.scala

示例5: StationStopValidator

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

import models.{LineStation, StopStation}

import scala.collection.breakOut

class StationStopValidator(allStops: Seq[StopStation]) {
  import StationStopValidator._

  def validate(stations: Seq[LineStation]): Seq[Error] = {
    val stationIds: Set[Long] = allStops.map(_.lineStationId)(breakOut)
    stations.flatMap { st =>
      if (stationIds.contains(st.id)) None
      else {
        Some(new UndefinedTrainError(st))
      }
    }
  }
}

object StationStopValidator {
  class UndefinedTrainError(station: LineStation) extends Error {
    override def message: String = s"Undefined arrived train at ${lineName}:${stationName}"
    override def url: Option[String] = None
    def lineName = station.line.map(_.name).getOrElse(s"(lineId = ${station.lineId})")
    def stationName = station.station.map(_.name).getOrElse(s"(stationId = ${station.stationId})")
  }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:29,代码来源:StationStopValidator.scala

示例6: WithScores

//设置package包名称以及导入依赖的类
package com.twitter.finagle.redis.protocol

import com.twitter.io.Buf
import scala.collection.breakOut

trait CommandArgument extends Command

case object WithScores extends CommandArgument {
  def name: Buf = Command.WITHSCORES
}

case class Limit(offset: Long, count: Long) extends CommandArgument {
  def name: Buf = Command.LIMIT
  override def body: Seq[Buf] = Seq(Buf.Utf8(offset.toString), Buf.Utf8(count.toString))
}

// Represents a list of WEIGHTS
class Weights(underlying: Array[Double]) extends CommandArgument with IndexedSeq[Double] {
  def name: Buf = Command.WEIGHTS

  def apply(idx: Int) = underlying(idx)
  def length = underlying.length

  override def body: Seq[Buf] = underlying.map(w => Buf.Utf8(w.toString))(breakOut)

  override def toString: String = Weights.toString + " " + this.mkString(" ")
}

// Handles parsing and manipulation of WEIGHTS arguments
object Weights {
  def apply(weight: Double) = new Weights(Array(weight))
  def apply(weights: Double*) = new Weights(weights.toArray)
  def apply(weights: Array[Double]) = new Weights(weights)
}

// Handles parsing and manipulation of AGGREGATE arguments
sealed abstract class Aggregate(val sub: String) extends CommandArgument {
  def name: Buf = Command.AGGREGATE
  override def body: Seq[Buf] = Seq(Buf.Utf8(sub.toUpperCase))
  def equals(str: String): Boolean = str.equals(sub)
}

object Aggregate {
  case object Sum extends Aggregate("SUM")
  case object Min extends Aggregate("MIN")
  case object Max extends Aggregate("MAX")
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:48,代码来源:CommandArguments.scala

示例7: Cookie

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

import scala.collection.breakOut

case class Cookie(raw: Map[String, String]) {
  override def toString: String = raw.map { case (k, v) => s"$k=$v" }.mkString(";")
}

object Cookie {
  def fromStr(str: String): Cookie = {
    val raw: Map[String, String] = str.split(';').flatMap { part =>
      part.trim.split('=') match {
        case Array(k) => Some(k -> "")
        case Array(k, v) => Some(k -> v)
        case _ => None
      }
    }(breakOut)
    Cookie(raw)
  }

  def empty = Cookie(Map.empty)
} 
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:23,代码来源:Cookie.scala

示例8: Extractor

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

import java.io.{File, InputStream}
import java.nio.file.Path

import com.drew.imaging.jpeg.JpegMetadataReader
import com.drew.metadata.Tag

import scala.collection.JavaConverters._
import scala.collection.breakOut

class Extractor {
  def read(fName: String): Metadata =
    read(new File(fName))
  def read(path: Path): Metadata =
    read(path.toFile)
  def read(file: File): Metadata =
    new Metadata(JpegMetadataReader.readMetadata(file))
  def read(is: InputStream): Metadata =
    new Metadata(JpegMetadataReader.readMetadata(is))
}

class Metadata(orig: com.drew.metadata.Metadata) {
  def directories: Iterable[Directory] = orig.getDirectories.asScala.map(new Directory(_))
  def tags: Iterable[Tag] = directories.flatMap(_.tags)
  def tagMaps: Map[String, String] = tags.map { tag => tag.getTagName -> tag.getDescription }(breakOut)
}

class Directory(orig: com.drew.metadata.Directory) {
  def tags: Iterable[Tag] = orig.getTags.asScala
  def name: String = orig.getName
} 
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:33,代码来源:Extractor.scala

示例9: convertToJsArray

//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers

import org.bitcoins.rpc.bitcoincore.blockchain.softforks.SoftForks
import org.bitcoins.rpc.bitcoincore.networking.{NetworkConnections, PeerInfo}
import org.bitcoins.rpc.marshallers.networking.NetworkConnectionsMarshaller.NetworkConnectionsFormatter
import org.bitcoins.rpc.marshallers.networking.PeerInfoRPCMarshaller.PeerInfoFormatter
import spray.json.{JsArray, JsValue, JsonWriter}

import scala.collection.breakOut


trait RPCMarshallerUtil {

  def convertToJsArray[T](seq : Seq[T])(implicit formatter : JsonWriter[T]) : JsArray  = {
    JsArray(seq.map(p =>
      formatter.write(p))(breakOut): Vector[JsValue])
  }

  def convertToPeerInfoSeq(value : JsValue) : Seq[PeerInfo] = {
    value match {
      case ja: JsArray => {
        ja.elements.toList.map(
          e => PeerInfoFormatter.read(e))
      }
      case _ => throw new RuntimeException("This Json type is not valid for parsing a list of peer info")
    }
  }

  def convertToNetworkConnectionList(value : JsValue) : Seq[NetworkConnections] = {
    value match {
      case ja: JsArray => {
        ja.elements.toList.map(
          e => NetworkConnectionsFormatter.read(e))
      }
      case _ => throw new RuntimeException("This Json type is not valid for parsing a list of network connections")
    }
  }
} 
开发者ID:bitcoin-s,项目名称:bitcoin-s-rpc-client,代码行数:39,代码来源:RPCMarshallerUtil.scala

示例10: BaseApp

//设置package包名称以及导入依赖的类
package com.typesafe.training.akkacollect

import akka.actor.{ ActorRef, ActorSystem }
import scala.collection.breakOut
import scala.concurrent.Await
import scala.concurrent.duration.Duration

object BaseApp {

  val Opt = """(\S+)=(\S+)""".r

  def argsToOpts(args: Seq[String]): Map[String, String] =
    args.collect { case Opt(key, value) => key -> value }(breakOut)

  def applySystemProperties(options: Map[String, String]): Unit =
    for ((key, value) <- options if key startsWith "-D")
      System.setProperty(key substring 2, value)
}

abstract class BaseApp {

  import BaseApp._

  def main(args: Array[String]): Unit = {
    val opts = argsToOpts(args.toList)
    applySystemProperties(opts)
    val name = opts.getOrElse("name", "akkollect")

    val system = ActorSystem(s"$name-system")
    val settings = Settings(system)
    initialize(system, settings)
    val top = createTop(system, settings)

    system.log.warning(f"{} running%nEnter "
      + Console.BLUE + "commands" + Console.RESET
      + " into the terminal: "
      + Console.BLUE + "[e.g. `s` or `shutdown`]" + Console.RESET, getClass.getSimpleName)
    commandLoop(system, settings, top)
    Await.ready(system.whenTerminated, Duration.Inf)
  }

  def initialize(system: ActorSystem, settings: Settings): Unit =
    ()

  def createTop(system: ActorSystem, settings: Settings): ActorRef =
    system.deadLetters

  protected def commandLoop(system: ActorSystem, settings: Settings, top: ActorRef): Unit
} 
开发者ID:sagunb,项目名称:akka-advanced,代码行数:50,代码来源:BaseApp.scala

示例11: UciCharPair

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

import scala.collection.breakOut

case class UciCharPair(a: Char, b: Char) {

  override def toString = s"$a$b"
}

object UciCharPair {

  import implementation._

  def apply(uci: Uci): UciCharPair = uci match {
    case Uci.Move(orig, dest, None) => UciCharPair(toChar(orig), toChar(dest))
    case Uci.Move(orig, dest, Some(role)) => UciCharPair(toChar(orig), toChar(dest.x, role))
    case Uci.Drop(role, pos) => UciCharPair(
      toChar(pos),
      dropRole2charMap.getOrElse(role, voidChar)
    )
  }

  private[format] object implementation {

    type File = Int

    val charShift = 35 // Start at Char(35) == '#'
    val voidChar = 33.toChar // '!'. We skipped Char(34) == '"'.

    val pos2charMap: Map[Pos, Char] = Pos.all.map { pos =>
      pos -> (pos.hashCode + charShift).toChar
    }(breakOut)

    def toChar(pos: Pos) = pos2charMap.getOrElse(pos, voidChar)

    val promotion2charMap: Map[(File, PromotableRole), Char] = (for {
      (role, index) <- Role.allPromotable.zipWithIndex
      file <- 1 to 8
    } yield (file, role) -> (charShift + pos2charMap.size + index * 8 + (file - 1)).toChar)(breakOut)

    def toChar(file: File, prom: PromotableRole) =
      promotion2charMap.getOrElse(file -> prom, voidChar)

    val dropRole2charMap: Map[Role, Char] =
      Role.all.filterNot(King==).zipWithIndex.map {
        case (role, index) => role -> (charShift + pos2charMap.size + promotion2charMap.size + index).toChar
      }(breakOut)
  }
} 
开发者ID:Thiediev,项目名称:lilyscalachess,代码行数:51,代码来源:UciCharPair.scala

示例12: BSONJodaDateTimeHandler

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

import scala.collection.breakOut
import org.joda.time.DateTime
import reactivemongo.bson._
import scalaz.NonEmptyList

trait Handlers {

  implicit object BSONJodaDateTimeHandler extends BSONHandler[BSONDateTime, DateTime] {
    def read(x: BSONDateTime) = new DateTime(x.value)
    def write(x: DateTime) = BSONDateTime(x.getMillis)
  }

  implicit def nullableHandler[T, B <: BSONValue](implicit reader: BSONReader[B, T], writer: BSONWriter[T, B]): BSONHandler[BSONValue, Option[T]] = new BSONHandler[BSONValue, Option[T]] {
    private val generalizedReader = reader.asInstanceOf[BSONReader[BSONValue, T]]
    def read(bv: BSONValue): Option[T] = generalizedReader.readOpt(bv)
    def write(v: Option[T]): BSONValue = v.fold[BSONValue](BSONNull)(writer.write)
  }

  implicit def bsonArrayToListHandler[T](implicit reader: BSONReader[_ <: BSONValue, T], writer: BSONWriter[T, _ <: BSONValue]): BSONHandler[BSONArray, List[T]] = new BSONHandler[BSONArray, List[T]] {
    def read(array: BSONArray) = readStreamList(array, reader.asInstanceOf[BSONReader[BSONValue, T]])
    def write(repr: List[T]) =
      new BSONArray(repr.map(s => scala.util.Try(writer.write(s))).to[Stream])
  }

  implicit def bsonArrayToVectorHandler[T](implicit reader: BSONReader[_ <: BSONValue, T], writer: BSONWriter[T, _ <: BSONValue]): BSONHandler[BSONArray, Vector[T]] = new BSONHandler[BSONArray, Vector[T]] {
    def read(array: BSONArray) = readStreamVector(array, reader.asInstanceOf[BSONReader[BSONValue, T]])
    def write(repr: Vector[T]) =
      new BSONArray(repr.map(s => scala.util.Try(writer.write(s))).to[Stream])
  }

  private def readStreamList[T](array: BSONArray, reader: BSONReader[BSONValue, T]): List[T] =
    array.stream.filter(_.isSuccess).map { v =>
      reader.read(v.get)
    }(breakOut)

  private def readStreamVector[T](array: BSONArray, reader: BSONReader[BSONValue, T]): Vector[T] =
    array.stream.filter(_.isSuccess).map { v =>
      reader.read(v.get)
    }(breakOut)
} 
开发者ID:ornicar,项目名称:lichess-db,代码行数:43,代码来源:Handlers.scala

示例13: FsmGraph

//设置package包名称以及导入依赖的类
package akkaviz.frontend.components

import akkaviz.frontend.vis
import akkaviz.frontend.vis.{NetworkData, NetworkOptions}
import org.scalajs.dom.html.Element
import org.scalajs.dom.{Element => domElement}

import scala.collection.breakOut
import scala.scalajs.js

class FsmGraph(parent: Element) {

  private[this] val networkNodes = new vis.DataSet[vis.Node]()
  private[this] val networkEdges = new vis.DataSet[vis.Edge]()
  private[this] val data = NetworkData(networkNodes, networkEdges)
  private[this] val network = new vis.Network(parent, data, fsmNetworkOptions)

  network.on("stabilizationProgress", () => network.fit())
  network.on("stabilized", () => network.fit())

  def displayFsm(transitions: Set[(String, String)]): Unit = {
    if (transitions.isEmpty) {
      parent.style.display = "none"
    } else {
      parent.style.display = "box"

      val allStates = transitions.flatMap { case (from, to) => Set(from, to) }
      val nodes: js.Array[vis.Node] = allStates.map(state => vis.Node(state, simplifyStateName(state), state))(breakOut)
      val edges: js.Array[vis.Edge] = transitions.map {
        case (from, to) => vis.Edge(s"${from}>${to}", from, to)
      }(breakOut)
      networkNodes.clear()
      networkNodes.add(nodes)
      networkEdges.clear()
      networkEdges.add(edges)
    }
  }

  @inline
  private[this] def simplifyStateName(state: String): String = {
    state.split('.').last.stripSuffix("$")
  }

  @inline
  private[this] def fsmNetworkOptions: NetworkOptions = {
    val opts = js.Dynamic.literal()

    opts.nodes = js.Dynamic.literal()
    opts.nodes.shape = "dot"
    opts.physics = js.Dynamic.literal()
    opts.physics.solver = "forceAtlas2Based"
    opts.physics.forceAtlas2Based = js.Dynamic.literal()
    opts.physics.forceAtlas2Based.springLength = 100

    opts.asInstanceOf[NetworkOptions]
  }

} 
开发者ID:blstream,项目名称:akka-viz,代码行数:59,代码来源:FsmGraph.scala

示例14: findSerializers

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

import org.clapper.classutil.ClassFinder
import scala.collection.breakOut

trait SerializerFinder {
  private[this] val rm = scala.reflect.runtime.currentMirror

  def findSerializers: List[AkkaVizSerializer] = {
    val finder = ClassFinder()
    val classes = finder.getClasses.filter(_.isConcrete).filter(_.implements(classOf[AkkaVizSerializer].getName))

    classes.flatMap {
      cls =>
        val clazz = Class.forName(cls.name)
        val classSymbol = rm.classSymbol(clazz)
        if (classSymbol.isModule) {
          Some(rm.reflectModule(classSymbol.asModule).instance.asInstanceOf[AkkaVizSerializer])
        } else {
          val constructors = classSymbol.toType.members.filter(_.isConstructor).map(_.asMethod)
          val constructorMaybe = constructors.filter(_.isPublic).filter(_.paramLists.exists(_.size == 0)).headOption
          constructorMaybe.map {
            constructor =>
              rm.reflectClass(classSymbol).reflectConstructor(constructor).apply().asInstanceOf[AkkaVizSerializer]
          }
        }
    }(breakOut)
  }

} 
开发者ID:blstream,项目名称:akka-viz,代码行数:31,代码来源:SerializerFinder.scala

示例15: ActorSystems

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

import akka.actor.{ActorPath, ActorRef, ActorSystem}
import akka.viz.ActorCellInstrumentation

import scala.collection.breakOut
import scala.ref.WeakReference
import scala.util.Try

object ActorSystems {

  private[this] val systemReferences = scala.collection.mutable.Map[String, WeakReference[ActorSystem]]()

  def systems: scala.collection.immutable.Map[String, ActorSystem] = systemReferences.flatMap {
    case (name, ref) => ref.get.map {
      system => name -> system
    }
  }(breakOut)

  def registerSystem(system: ActorSystem): Unit = {
    systemReferences.update(system.name, WeakReference(system))
  }

  def tell(path: String, message: Any): Unit = {
    Try {
      val actorPath = ActorPath.fromString(path)
      systems.get(actorPath.address.system).foreach {
        system =>
          system.actorSelection(actorPath).tell(message, ActorRef.noSender)
      }
    }
  }

  def refreshActorState(path: String): Unit = {
    tell(path, ActorCellInstrumentation.RefreshInternalStateMsg)
  }

} 
开发者ID:blstream,项目名称:akka-viz,代码行数:39,代码来源:ActorSystems.scala


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