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

Scala Set类代码示例

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

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



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

示例1: MedicineProcess

//设置package包名称以及导入依赖的类
package cn.com.warlock.practice.ml

import java.io.BufferedReader
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.{ArrayType, DataType, StringType}

import scala.collection.mutable.Set

class MedicineProcess(override val uid: String, private val dict: String)
  extends UnaryTransformer[Seq[String], Seq[String], MedicineProcess] {

  def this(dict: String) = this(Identifiable.randomUID("med"), dict)

  // ?????????
  private val wordsSet = loadDict

  // ????
  private def loadDict: Set[String] = {
    val br: BufferedReader = Files.newBufferedReader(Paths.get(dict), StandardCharsets.UTF_8)
    val words = Set[String]()

    var count = 0

    while (br.ready()) {
      words += br.readLine()
      count += 1
    }

    println(s"load med words: $count")

    words
  }

  override protected def createTransformFunc: Seq[String] => Seq[String] = (words: Seq[String]) => {
    // ?? "???", arr ?????????, c ??????? word
    words.foldLeft(List[String]())((arr, c) => {
      val newC = wordsSet.contains(c) match {
        case true => List(c, "_MED_")
        case false => List(c)
      }
      arr ++ newC
    })
  }

  override protected def validateInputType(inputType: DataType): Unit = {
    require(inputType.isInstanceOf[ArrayType],
      s"The input column must be ArrayType, but got $inputType.")
  }

  override protected def outputDataType: DataType = new ArrayType(StringType, true)

  override def copy(extra: ParamMap): MedicineProcess = defaultCopy(extra)
} 
开发者ID:warlock-china,项目名称:spark-meepo,代码行数:59,代码来源:MedicineProcess.scala


示例2: Problem

//设置package包名称以及导入依赖的类
object Problem {

  def main(args: Array[String]) {

    import scala.collection.mutable.Set

    // ????? ????
    def isAbundant(num: Int): Boolean = {
      val ls: Set[Int] = Set()
      for { a <- 1 to num; if (num % a == 0) }
        ls += (a, num / a)
      (ls - num).sum > num
    }

    // ????? ?? ??? ???
    def getAbundantsComb(ab: List[Int], numbers: Array[Boolean]): Array[Boolean] = {
      if (ab.length < 1)
        numbers
      else {
        ab.foreach((x) => numbers(x + ab.head) = true)
        getAbundantsComb(ab.tail, numbers) // ??
      }
    }

    val abundants = (for { i <- 1 until 28123; if (isAbundant(i)) } yield i).toList
    val numbers = getAbundantsComb(abundants, new Array[Boolean](28123 * 2))

    val result = (for { i <- 1 until numbers.length; if (!numbers(i) && i <= 28123) }
      yield i).toList.sum
    println(result)
  }
} 
开发者ID:johngrib,项目名称:project_euler,代码行数:33,代码来源:Problem023.scala


示例3: KthMultiple

//设置package包名称以及导入依赖的类
package org.pfcoperez.cci.hard

object KthMultiple extends App {

  def kthMultiple(k: Int, primes: Set[Long]): Long = {
    import scala.collection.mutable.Set

    val multiples = Set.empty[Long]
    var scout: Long = 1
    var lastMultiple: Long = scout

    multiples.add(scout)
    multiples.add(1)

    while(multiples.size < k) {
      if(primes.exists(p => scout % p == 0 && multiples.contains(scout/p))) {
        multiples.add(scout)
        lastMultiple = scout
      }
      scout += 1
    }

    lastMultiple

  }

  (1 to 10) foreach { i =>
    println(kthMultiple(i, Set(3,5,7)))
  }

} 
开发者ID:pfcoperez,项目名称:cci,代码行数:32,代码来源:KthMultiple.scala


示例4: StreetActor

//设置package包名称以及导入依赖的类
package ch.becompany.akka.demo.actor

import scala.collection.mutable.Set
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import ch.becompany.akka.demo.actor.StreetActor.{Initialize, LeaveQueue}

class StreetActor(val maximum: Int = 15, val barsNumber: Int = 1) extends Actor with ActorLogging {
  var bars = scala.collection.mutable.ArrayBuffer.empty[ActorRef]
  var queue = Set[ActorRef]()
  var counter = 0

  override def receive = {
    case Initialize => {
      log.info("Street is being created.")
      for (i <- 0 until barsNumber ) {
        bars += context.actorOf(BarActor.props, "bar" + i)
        log.info(s"Created 'bar$i'.")
      }
      bars map (actor => actor ! Initialize)
    }
    case LeaveQueue => {
      queue.remove(sender())
    }
    case customerName: String =>  {
      if (queue.size < maximum) {
        counter += 1
        val customerActor = context.actorOf(CustomerActor.props(customerName), "customer" + counter)
        queue += customerActor
        log.info(s"The customer '$customerName' is in the queue. Queue size: ${queue.size}")

        customerActor ! Initialize
      } else {
        log.warning(s"Customer '$customerName' has to leave because queue is full.")
      }
    }
    case unknown => log.error(s"Actor name '$unknown' not recognized.")
  }
}

object StreetActor {
  def props(maximum: Int) = Props(new StreetActor(maximum))
  case object Initialize
  case object LeaveQueue
} 
开发者ID:becompany,项目名称:cooking-with-akka,代码行数:45,代码来源:StreetActor.scala


示例5: PageTracker

//设置package包名称以及导入依赖的类
import akka.actor.Actor
import scala.collection.mutable.{HashSet, Set}

class PageTracker extends Actor {
  var pages: Set[Page] = new HashSet[Page]()

  def receive = {

    case PageCheck(page, replyTo) => {
      if (pages.contains(page)) {
        replyTo ! DoNotCrawl(page)
      } else {
        pages.add(page)
        replyTo ! DoCrawl(page)
      }
    }
    case RemovePage(page) => {
       pages.remove(page)
    }
  }
} 
开发者ID:rzrelyea,项目名称:scala-akka-web-crawler,代码行数:22,代码来源:PageTracker.scala


示例6: LinkQueueActor

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

import scala.collection.mutable.Queue
import scala.collection.mutable.Set
import akka.actor.{Actor, ActorRef, ActorLogging}


class LinkQueueActor(parseQueue: ActorRef) extends Actor with ActorLogging {
  // We have provided some definitions below which will help you with
  // you implementation. You are welcome to modify these, however, this
  // is what we used for our implementation.
  log.info("LinkQueueActor created")
  val queue        = Queue[String]()
  val fetchers     = Set[ActorRef]()
  var limit        = 500

  def receive = {

    case NeedLink =>     if(limit == 0)
                             context.system.shutdown()
                         else {
                               if(queue.isEmpty)
                                  sender ! NoLinks
                                  else
                                  {
                                   println(limit + " more links to do")
                                    limit = limit -1
                                    sender ! FetchLink(queue.dequeue)
                                  }
                                }


    case Page(url,html)    =>  parseQueue ! Page(url,html)

    case QueueLink(url)    => queue.enqueue(url)
  }

} 
开发者ID:juconghe,项目名称:web-crawler,代码行数:39,代码来源:LinkQueueActor.scala


示例7: ChatRoom

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

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import scala.collection.mutable.Set
import play.Logger

class ChatRoom(name: String, var available: Set[ActorRef]) extends Actor with ActorLogging {

  override def receive = {
    case joined: Join => {
      available = available + sender
      val broadcast = Notification(s"${joined.member} joined the chat room")
      (available - sender).foreach { actor => actor ! broadcast }
      Logger.info("Joined 1 member. # of Available members " + available.size)
    }
    case leave: Leave => {
      val broadcast = Notification(s"<i>@${leave.member}</i> left the chat room")
      available = available - sender
      available.foreach { actor => actor ! broadcast }
      
    }
    case msg: BroadCastMessage => {
      available.foreach { actor => actor ! msg }
    }
  }
}

trait Message
case class Join(member: String) extends Message
case class Leave(member: String) extends Message
case class BroadCastMessage(author : String, msg: String,color : String) extends Message
case class Notification(message : String) extends Message 
开发者ID:amezng,项目名称:akka-chat,代码行数:35,代码来源:ChatRoom.scala


示例8: ChatManager

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

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import scala.collection.mutable.Set
import play.Logger

case class ChatManager(val chatRooms: List[ActorRef]) {
  //Work in progress
  // Add feature to initialize list of chat rooms

}

object ChatManager {

  def getChatRoom(roomName: String)(implicit system: ActorSystem) = {
    Logger.info("Creating the chat room")
    system.actorOf(Props(classOf[ChatRoom], roomName, Set()), name = roomName)
  }

}

case class ClientActor(color : String, member: String, out: ActorRef, chat: ActorRef) extends Actor with ActorLogging {

  chat ! Join(member)
  Logger.info("Joined the chat")
  
  override def postStop() = {
    Logger.info("leaving the chat room ")
    chat ! Leave(member)
  }

  def receive = {
    case message: String           => chat ! BroadCastMessage(member,message,color)
    case BroadCastMessage(author, message,color) => out ! s"$color:$author : $message"
    case Notification(message) => out ! s"#fff:Admin : $message"
  }

} 
开发者ID:amezng,项目名称:akka-chat,代码行数:43,代码来源:ChatManager.scala


示例9: GossipingBestEffortBroadcastComponent

//设置package包名称以及导入依赖的类
package se.kth.app.broadcast

import com.typesafe.scalalogging.StrictLogging
import se.kth.app.events.{HistoryRequest, _}
import se.kth.app.ports.{GossipingBestEffortBroadcast, PerfectLink}
import se.sics.kompics.{KompicsEvent, Start}
import se.sics.kompics.sl._
import se.sics.ktoolbox.croupier.CroupierPort
import se.sics.ktoolbox.croupier.event.CroupierSample
import se.sics.ktoolbox.util.network.KAddress

import scala.collection.JavaConversions._
import scala.collection.mutable.Set


class GossipingBestEffortBroadcastComponent(init: Init[GossipingBestEffortBroadcastComponent]) extends ComponentDefinition with StrictLogging{
  val gbeb: NegativePort[GossipingBestEffortBroadcast] = provides[GossipingBestEffortBroadcast]
  val pLink: PositivePort[PerfectLink] = requires[PerfectLink]
  val croupier: PositivePort[CroupierPort] = requires[CroupierPort]

  var self: KAddress = init match {case Init(self:KAddress) => self}
  var past: Set[(KAddress, KompicsEvent)] = Set.empty[(KAddress, KompicsEvent)]

  ctrl uponEvent {
    case _:Start => handle {
      logger.info("Starting...")
      past = Set.empty[(KAddress, KompicsEvent)]
    }
  }

  gbeb uponEvent {
    case GBEB_Broadcast(payload: KompicsEvent) => handle {
      past += ((self, payload))
    }
  }

  croupier uponEvent {
    case  sample:CroupierSample[_] => handle {
      logger.info("Croupier sample received")
      if(!sample.publicSample.isEmpty){
        val nodes = sample.publicSample.values().map{ x => x.getSource}
        for (p <- nodes) trigger(PL_Send(p, new HistoryRequest) -> pLink)

      }
    }
  }

  pLink uponEvent {
    case  PL_Deliver(src: KAddress, _:HistoryRequest) => handle {
      trigger(PL_Send(src, HistoryResponse(past)) -> pLink)
    }
    case PL_Deliver(_:KAddress, HistoryResponse(history)) => handle {
      val unseen = history.diff(past)

      for ((pp, m) <- unseen) trigger(GBEB_Deliver(pp, m) -> gbeb)
      past ++= unseen
    }
  }

} 
开发者ID:reginbald,项目名称:p2p-crdt,代码行数:61,代码来源:GossipingBestEffortBroadcastComponent.scala


示例10: Function

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

import scala.collection.mutable.{Set, Queue}

sealed class Function(funName: String) extends Iterable[BasicBlock] {
  private val _name: String = funName
  private var _first: BasicBlock = null

  def name: String = _name

  def first: BasicBlock = _first

  def first_=(bb: BasicBlock): Unit = _first = bb

  override def iterator: Iterator[BasicBlock] = new Iterator[BasicBlock] {
    private val visited = Set[BasicBlock]()
    private val queue = new Queue[BasicBlock]() += first

    def hasNext = ! queue.isEmpty

    def next = {
      val res = queue.dequeue
      visited += res
      res foreach {
        case B(cond, ifBB, elseBB) => {
          if (! (visited contains ifBB) && ! (queue contains ifBB)) {
            queue += ifBB
          }
          if (! (visited contains elseBB) && ! (queue contains elseBB)) {
            queue += elseBB
          }
        }
        case _ =>
      }
      res
    }
  }

  
  def traverseInstructions(action: Instruction => Unit): Unit =
    traverseBB(bb => bb foreach action)

  override def toString(): String = {
    var res = "fun " + name + " {\n"
    this foreach (bb => res += "" + bb + "\n")
    res += "}\n"
    res
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:51,代码来源:Function.scala


示例11: getMapping

//设置package包名称以及导入依赖的类
package scanalyzer
package analysis
package dominance

import cfg._
import util._

import scala.collection.mutable.{Set, Map, Queue}


  def getMapping(): Map[BasicBlock, Set[BasicBlock]] = {
    blocktab.clone
  }

  override def getResult(): String = {
    var res = ""
    for ((k, v) <- blocktab)
      res += k.Name + " -> " + Util.strItBB(v) + "\n"
    res
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:22,代码来源:DominanceAnalysis.scala


示例12:

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

import cfg._
import util._

import scala.collection.mutable.{Set, Queue, Map}


    val depMap = Map[Named, Set[Named]]()

    setUpDependencyMap(depMap)

    Util.dbgmsg("Dependencies:")
    if (Util.dbg) {
      depMap foreach {
        case (Named(n), s) => Util.dbgmsg("  " + n + " ->" + Util.strIt(s))
        case _ =>
      }
    }

    val queue = new Queue[Named]

    queue ++= depMap.keys

    while (! queue.isEmpty) {
      Util.dbgmsg("Queue: " + Util.strIt(queue))

      val current = queue.dequeue
      val before = symtab(current.Name)
      eval(current)
      val after = symtab(current.Name)

      Util.dbgmsg("Transform `" + current.Name + "` from `" + before +
        "` to `" + after)

      if (after != before) {
        val add = (depMap(current) filterNot (queue contains _))
        Util.dbgmsg("  ~> Adding `" + Util.strIt(add) + "` to queue")
        queue ++= add
      }
    }
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:45,代码来源:SimpleValueIterationAnalysis.scala


示例13: Auth

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

import scala.collection.mutable.Set
import twitter4j.auth.AccessToken
import twitter4j.conf.PropertyConfiguration

class Auth private(val token: AccessToken) {
	def id = token.getUserId
	def remove {
		Auth.accounts -= id
		Auth.pref.remove(Auth.ATOKEN.format(id))
		Auth.pref.remove(Auth.SECRET.format(id))
		Auth.put("ids", Auth.accounts.toSeq)
	}
}

object Auth extends Conf("authentication") {
	val keys = Mbed.stream("rabbit.key")
	val conf = new PropertyConfiguration(keys)
	keys.close
	private val accounts = Set[Long]()
	val ATOKEN = "atoken.%d"
	val SECRET = "secret.%d"
	accounts ++= seq("ids").map(_.toLong)
	def apply(id: Long): Auth = {
		val a = pref.get(ATOKEN.format(id), "")
		val s = pref.get(SECRET.format(id), "")
		new Auth(new AccessToken(a, s))
	}
	def add(token: AccessToken): Auth = {
		val a = token.getToken
		val s = token.getTokenSecret
		val id = token.getUserId
		pref.put(ATOKEN.format(id), a)
		pref.put(SECRET.format(id), s)
		accounts += id
		put("ids", accounts.toSeq)
		new Auth(token)
	}
	def ids = accounts.toSeq
	def all = accounts.map(Auth(_)).toSeq
	def selfs = all.map(new Self(_)(Auth.conf))
} 
开发者ID:nextzlog,项目名称:nabe,代码行数:44,代码来源:Auth.scala


示例14: LinkQueueActor

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

import scala.collection.mutable.Queue
import scala.collection.mutable.Set
import akka.actor.{Actor, ActorRef, ActorLogging}


class LinkQueueActor(parseQueue: ActorRef) extends Actor with ActorLogging {
  // We have provided some definitions below which will help you with
  // you implementation. You are welcome to modify these, however, this
  // is what we used for our implementation.
  log.info("LinkQueueActor created")
  val queue        = Queue[String]()
  val fetchers     = Set[ActorRef]()
  var limit        = 500

  def receive = {
    case NeedLink =>   {   println("LinkQueueActor receive NeedLink Message\n" + sender)
                            if(limit == 0){
                             context.system.shutdown() }
                             else {
                               limit = limit -1;
                               if(queue.isEmpty)
                                  sender ! NoLinks
                                  else{
                                  sender ! FetchLink(queue.dequeue)
                                }
                             }
                           }

    case Page(url,html)    =>    { println("LinkQueueActor receive Page Message\n" + sender)
                                  parseQueue ! Page(url,html)
                                }

    case QueueLink(url) =>      {
      println("LinkQueueActor receive QueueLink Message\n" + sender)
      queue.enqueue(url)
      println(queue.size)
    }
  }

} 
开发者ID:amherst-takeout,项目名称:asn-inverted-index-student-master,代码行数:43,代码来源:LinkQueueActor.scala


示例15: UntypedTaskEventBus

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

import scala.collection.mutable.HashMap
import scala.collection.mutable.MultiMap
import scala.collection.mutable.Set
import scala.reflect.ClassTag


class UntypedTaskEventBus(task: UntypedTaskEventBus => Unit) {
  val listeners = new HashMap[Class[_], Set[EventListener[_]]] with MultiMap[Class[_], EventListener[_]]

  def onEvent[EventType](listener: EventType => Unit)(implicit ct: ClassTag[EventType]) {
    listeners.addBinding(ct.runtimeClass, new EventListener[EventType](listener))
  }

  def sendEvent(event: AnyRef) {
    val eventClass = event.getClass
    if (listeners.contains(eventClass)) {
      for (listener <- listeners.get(eventClass).get) {
        listener(event)
      }
    }
  }

  def startTask = task(this)
}

class EventListener[EventType: ClassTag](listener: EventType => Unit) {
  def apply(event: AnyRef) {
    listener(event.asInstanceOf[EventType])
  }
} 
开发者ID:Kneelawk,项目名称:SimpleCurseModpackDownloader,代码行数:33,代码来源:UntypedTaskEventBus.scala


示例16: MutableSet

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


object MutableSet {
  def main(args: Array[String]):Unit= {
    //??
    import scala.collection.mutable.Set
    val movieSet = Set("Hitch", "Poltergeist")
    movieSet += "Shrek"
    println(movieSet)
    //???
    import scala.collection.immutable.HashSet
    val hashSet = HashSet("Tomatoes", "Chilies")
    println(hashSet + "Coriander")
  }

} 
开发者ID:tophua,项目名称:spark1.52,代码行数:18,代码来源:MutableSet.scala


示例17: SetMaker

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

import scala.collection.JavaConverters._
import scala.collection.mutable.{Map, Set}

import com.google.common.collect.{MapMaker => GoogleMapMaker}


object SetMaker {
  def apply[A](f: Config[A] => Any): Set[A] = {
    val config = new Config[A]
    f(config)
    config()
  }

  class Config[A] {
    private val mapMaker = new GoogleMapMaker

    def weakValues = { mapMaker.weakKeys; mapMaker.weakValues; this }
    def concurrencyLevel(level: Int) = { mapMaker.concurrencyLevel(level); this }
    def initialCapacity(capacity: Int) = { mapMaker.initialCapacity(capacity); this }

    def apply() = new MapToSetAdapter[A](
      mapMaker.makeMap[A, A]().asScala)
  }
}

class MapToSetAdapter[A](map: Map[A, A]) extends Set[A] {
  def +=(elem: A) = {
    map(elem) = elem
    this
  }
  def -=(elem: A) = {
    map -= elem
    this
  }
  override def size = map.size
  def iterator = map.keysIterator
  def contains(elem: A) = map.contains(elem)
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:41,代码来源:SetMaker.scala


示例18: UpdatesActor

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

import actors.UpdatesActor.{Subscribe, Unsubscribe}
import actors.WebSocketActor.ReloadMessage
import akka.actor.{Actor, ActorRef, Props}
import play.api.Logger

import scala.collection.mutable
import scala.collection.mutable.{HashMap, Set}


class UpdatesActor extends Actor {

  val listeners = new HashMap[String, Set[ActorRef]] with mutable.MultiMap[String, ActorRef]

  override def receive: Receive = {
    case Subscribe(ref, category) => listeners.addBinding(category, ref)
    case Unsubscribe(ref, category) => listeners.removeBinding(category, ref)
    case ReloadMessage(reload) => {
      Logger.info("Received reload message from Mongo to updater")
      for(set <- listeners.values){
        for(listener <- set) {
          listener ! ReloadMessage(reload)
        }
      }
    }
  }
}

object UpdatesActor {
  case class ReloadMessage(reload: Boolean)
  case class Subscribe(ws: ActorRef, category: String)
  case class Unsubscribe(ws: ActorRef, category: String)

  def props() = Props(new UpdatesActor())
} 
开发者ID:barthorre,项目名称:kassa,代码行数:37,代码来源:UpdatesActor.scala


示例19: toString

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

import java.io.File
import scala.collection.mutable.{HashSet, Set}

trait Format[T] extends NotNull
{
	def toString(t: T): String
	def fromString(s: String): T
}
abstract class SimpleFormat[T] extends Format[T]
{
	def toString(t: T) = t.toString
}
object Format
{
	def path(basePath: Path): Format[Path] = new Format[Path]
	{
		def toString(path: Path) = Path.relativize(basePath.asFile, path.asFile).getOrElse(error("Path " + path + " not in " + basePath))
		def fromString(s: String) = Path.fromString(basePath, s)
	}
	implicit val file: Format[File] = new Format[File]
	{
		def toString(file: File) = file.getAbsolutePath
		def fromString(s: String) = (new File(s)).getAbsoluteFile
	}
	implicit val hash: Format[Array[Byte]] = new Format[Array[Byte]]
	{
		def toString(hash: Array[Byte]) = Hash.toHex(hash)
		def fromString(hash: String) = Hash.fromHex(hash)
	}
	def set[T](implicit format: Format[T]): Format[Set[T]] = new Format[Set[T]]
	{
		def toString(set: Set[T]) = set.toList.map(format.toString).mkString(File.pathSeparator)
		def fromString(s: String) = (new HashSet[T]) ++ FileUtilities.pathSplit(s).map(_.trim).filter(!_.isEmpty).map(format.fromString)
	}
	implicit val string: Format[String] = new SimpleFormat[String] { def fromString(s: String) = s }
	implicit val test: Format[TestDefinition] = new SimpleFormat[TestDefinition]
	{
		def fromString(s: String) = TestParser.parse(s).fold(error, x => x)
	}
} 
开发者ID:TomasPleml,项目名称:simple-build-tool,代码行数:43,代码来源:Format.scala


示例20: ValidationDirective

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

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{Directive1, ValidationRejection}
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.server.Directives._

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


object ValidationDirective extends SprayJsonSupport with DefaultJsonProtocol {

  import akka.http.scaladsl.server.Rejection

  final case class FieldRule[-M](fieldName: String, isInvalid: M => Boolean, errorMsg: String)
  final case class FieldErrorInfo(name: String, error: String)
  final case class ModelValidationRejection(invalidFields: Set[FieldErrorInfo]) extends Rejection

  implicit val validatedFieldFormat = jsonFormat2(FieldErrorInfo)

  private def caseClassFields[M <: Any](obj: AnyRef): Seq[(String, M)] = {
    val metaClass = obj.getClass
    metaClass.getDeclaredFields.map {
      field => {
        field.setAccessible(true)
        (field.getName, field.get(obj).asInstanceOf[M])
      }
    }
  }

  def validateModel[T, M <: Any](model: T, rules: FieldRule[M]*): Directive1[T] = {
    import scala.collection.mutable.Set
    val errorsSet: Set[FieldErrorInfo] = Set[FieldErrorInfo]()
    val keyValuePairs: Seq[(String, M)] = caseClassFields(model.asInstanceOf[AnyRef])
    Try {
      rules.map { rule =>
        keyValuePairs.find(_._1 == rule.fieldName) match {
          case None => throw new IllegalArgumentException(s"No such field for validation: ${rule.fieldName}")
          case Some(pair) => {
            if (rule.isInvalid(pair._2)) errorsSet += FieldErrorInfo(rule.fieldName, rule.errorMsg)
          }
        }
      }
      errorsSet.toSet[FieldErrorInfo]
    } match {
      case Success(set) => if (set.isEmpty) provide(model) else reject(ModelValidationRejection(set))
      case Failure(ex) => reject(ValidationRejection(ex.getMessage))
    }
  }
} 
开发者ID:Fruzenshtein,项目名称:akka-http-validation,代码行数:51,代码来源:ValidationDirective.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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