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

Scala UUID类代码示例

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

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



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

示例1: Service

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

import java.util.UUID

import onextent.oemap.server.entities.IdAble

import scala.concurrent.{ExecutionContext, Future}

class Service[T <: IdAble](implicit val executionContext: ExecutionContext) {

  var entries = Vector.empty[T]

  def create(entry: T): Future[Option[UUID]] =
    Future {
      entries.find(_.id == entry.id) match {
        case Some(_) => None // Conflict! id is already taken
        case None =>
          entries = entries :+ entry
          Some(entry.id)
      }
    }


  def get(id: UUID): Future[Option[T]] =
    Future {
      entries.find(_.id == id)
    }

  def delete(id: UUID): Future[Unit] =
    Future {
      entries = entries.filterNot(_.id == id)
    }
} 
开发者ID:navicore,项目名称:oemap-server,代码行数:34,代码来源:Service.scala


示例2: ApiService

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

import java.util.{UUID, Date}

import spatutorial.shared._

class ApiService extends Api {
  var todos = Seq(
    TodoItem("41424344-4546-4748-494a-4b4c4d4e4f50", 0x61626364, "Wear shirt that says “Life”. Hand out lemons on street corner.", TodoLow, completed = false),
    TodoItem("2", 0x61626364, "Make vanilla pudding. Put in mayo jar. Eat in public.", TodoNormal, completed = false),
    TodoItem("3", 0x61626364, "Walk away slowly from an explosion without looking back.", TodoHigh, completed = false),
    TodoItem("4", 0x61626364, "Sneeze in front of the pope. Get blessed.", TodoNormal, completed = true)
  )

  override def welcomeMsg(name: String): String =
    s"Welcome to SPA, $name! Time is now ${new Date}"

  override def getAllTodos(): Seq[TodoItem] = {
    // provide some fake Todos
    Thread.sleep(300)
    println(s"Sending ${todos.size} Todo items")
    todos
  }

  // update a Todo
  override def updateTodo(item: TodoItem): Seq[TodoItem] = {
    // TODO, update database etc :)
    if(todos.exists(_.id == item.id)) {
      todos = todos.collect {
        case i if i.id == item.id => item
        case i => i
      }
      println(s"Todo item was updated: $item")
    } else {
      // add a new item
      val newItem = item.copy(id = UUID.randomUUID().toString)
      todos :+= newItem
      println(s"Todo item was added: $newItem")
    }
    Thread.sleep(300)
    todos
  }

  // delete a Todo
  override def deleteTodo(itemId: String): Seq[TodoItem] = {
    println(s"Deleting item with id = $itemId")
    Thread.sleep(300)
    todos = todos.filterNot(_.id == itemId)
    todos
  }
} 
开发者ID:wrotki,项目名称:spacommander,代码行数:52,代码来源:ApiService.scala


示例3: Access

//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy

import java.nio.file.{Files, StandardCopyOption}
import java.util.{Properties, UUID}

import awscala.s3.S3
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.model.GetObjectRequest
import hu.blackbelt.cd.bintray.VFS.FS

object Access {
  val bintray_organization = "bintray.organization"
  val bintray_user = "bintray.user"
  val bintray_apikey = "bintray.apikey"
  val aws_accessKeyId = "aws.accessKeyId"
  val aws_secretKey = "aws.secretKey"


  def collect = {
    implicit val s3 = S3()(com.amazonaws.regions.Region.getRegion(Regions.EU_CENTRAL_1))



    val destination = FS.getPath(s"/tmp/${UUID.randomUUID().toString}")
    Files.createDirectories(destination)
    val s3Object = s3.getObject(new GetObjectRequest("blackbelt-secrets", "bintray-deploy/access.properties"))
    Files.copy(s3Object.getObjectContent, destination, StandardCopyOption.REPLACE_EXISTING)

    import scala.collection.JavaConverters._
    val prop = new Properties()
    prop.load(Files.newInputStream(destination))
    prop.entrySet().asScala.foreach {
      (entry) => {
        sys.props += ((entry.getKey.asInstanceOf[String], entry.getValue.asInstanceOf[String]))
      }
    }
  }
} 
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:39,代码来源:Access.scala


示例4: RequestNormalization

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

import java.nio.charset.StandardCharsets
import java.util.UUID
import java.net.URLEncoder
import com.twitter.finagle.http.Request
import shapeless.tag._
import cats.implicits._
import com.lookout.ratelimitingfilter.models._


object RequestNormalization {
  def apply(
    serviceLookup: Request => Option[String @@ ServiceName],
    claimLookup: Request => Option[(UUID @@ EntClaim, UUID @@ SubClaim)],
    request: Request
  ): List[String] = {
    val method = request.method
    val path = encodePath(request.path)
    val serviceBuckets: Option[List[String]] = serviceLookup(request).map {
      serviceName => s"$method::$serviceName" :: s"$method::$path::$serviceName" :: Nil
    }
    val idBuckets: Option[List[String]] = claimLookup(request).map {
      case (entUuid, subUuid) =>
        s"$method::$path::$entUuid" :: s"$method::$path::$subUuid" :: Nil
    }

    (serviceBuckets |+| idBuckets).getOrElse(Nil)
  }

  def encodePath(path: String): String =
    URLEncoder.encode(path, StandardCharsets.UTF_8.toString).toLowerCase
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:34,代码来源:RequestNormalization.scala


示例5: OrderProcessor

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

import java.util.UUID

import scaldi.Injector
import akka.actor.{Actor, ActorRef, PoisonPill}
import scaldi.akka.AkkaInjectable

import scala.math.BigDecimal.RoundingMode

class OrderProcessor(implicit inj: Injector) extends Actor with AkkaInjectable {
  import Messages._

  val priceCalculator = injectActorRef [PriceCalculator]

  def receive = idle

  val idle: Receive = {
    case orderInfo @ ProcessOrder(user: User, itemId: Long, netAmount: Int) =>
      println(s"Processing order for user $user.")

      priceCalculator ! CalculatePrice(netAmount)

      context become workingHard(orderInfo, sender)
  }

  def workingHard(orderInfo: ProcessOrder, reportTo: ActorRef): Receive = {
    case CancelProcessing =>
      reportTo ! OrderProcessingFailed("Canceled..")
      self ! PoisonPill
    case GrossPriceCalculated(_, grossPrice) =>
      println("Processing order.....")

      reportTo ! OrderProcessed(UUID.randomUUID().toString, grossPrice)
      self ! PoisonPill
  }
}

class PriceCalculator extends Actor {
  import Messages._

  def receive = {
    case CalculatePrice(netAmount) =>
      val grossCent = (netAmount * BigDecimal("1.19")).setScale(0, RoundingMode.HALF_UP).toIntExact
      sender ! GrossPriceCalculated(netAmount, grossCent)
  }
} 
开发者ID:shigemk2,项目名称:my-scaldi-akka-sample,代码行数:48,代码来源:Order.scala


示例6: RegistryServiceActor

//设置package包名称以及导入依赖的类
package com.pacbio.secondary.smrtlink.actors

import java.util.UUID

import akka.actor.{Props, ActorRef, Actor}
import com.pacbio.common.actors.{PacBioActor, ActorRefFactoryProvider}
import com.pacbio.common.dependency.Singleton
import com.pacbio.secondary.smrtlink.models.{RegistryResourceUpdate, RegistryProxyRequest, RegistryResourceCreate}

// TODO(smcclellan): Add scaladoc

object RegistryServiceActor {
  case class GetResources(id: Option[String])
  case class GetResource(uuid: UUID)
  case class CreateResource(create: RegistryResourceCreate)
  case class UpdateResource(uuid: UUID, update: RegistryResourceUpdate)
  case class DeleteResource(uuid: UUID)
  case class ProxyRequest(uuid: UUID, req: RegistryProxyRequest)
}

class RegistryServiceActor(registryDao: RegistryDao) extends PacBioActor {
  import RegistryServiceActor._

  def receive: Receive = {
    case GetResources(id)             => respondWith(registryDao.getResources(id))
    case GetResource(uuid)            => respondWith(registryDao.getResource(uuid))
    case CreateResource(create)       => respondWith(registryDao.createResource(create))
    case UpdateResource(uuid, update) => respondWith(registryDao.updateResource(uuid, update))
    case DeleteResource(uuid)         => respondWith(registryDao.deleteResource(uuid))
    case ProxyRequest(uuid, req)      => respondWith(registryDao.proxyRequest(uuid, req))
  }
}

trait RegistryServiceActorRefProvider {
  this: RegistryDaoProvider with ActorRefFactoryProvider =>

  val registryServiceActorRef: Singleton[ActorRef] =
    Singleton(() => actorRefFactory().actorOf(Props(classOf[RegistryServiceActor], registryDao()), "RegistryServiceActor"))
}

trait RegistryServiceActorProvider {
  this: RegistryDaoProvider =>

  val registryServiceActor: Singleton[RegistryServiceActor] = Singleton(() => new RegistryServiceActor(registryDao()))
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:46,代码来源:RegistryServiceActor.scala


示例7: CustomerId

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

import java.util.UUID

import core.services.CustomerCreateDTO

case class CustomerId(id: String =  UUID.randomUUID().toString) extends ModelEntityKey

object CustomerId{
  implicit def fromUUID(uuid: UUID): CustomerId = {
    CustomerId(id = uuid.toString)
  }
}

case class Customer(id: CustomerId = CustomerId(), name: String, accounts: List[AccountId] = Nil) extends ModelEntity {
  type KeyType = CustomerId

  def linkWithAccount(accountId: AccountId) = {
    this.copy(accounts = accountId :: accounts)
  }
}

object Customer {
  def apply(customerCreateDTO: CustomerCreateDTO): Customer = {
    Customer(name = customerCreateDTO.name)
  }
} 
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:28,代码来源:Customer.scala


示例8: MerchantAreasDAOImpl

//设置package包名称以及导入依赖的类
package daos.merchant.impl

import java.util.UUID
import javax.inject.Inject

import models.{ MerchantAreas, ServeArea }
import daos.merchant.MerchantAreasDAO
import daos.util.ServeAreaDAO
import models.slick.SlickDAO
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class MerchantAreasDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider, serveAreaDAO: ServeAreaDAO) extends MerchantAreasDAO with SlickDAO {

  import driver.api._

  
  def save(userID: UUID, area: ServeArea) = {
    val dbMerchAreas = DBMerchantAreas(userID.toString, area.id)
    val act = (for {
      exist <- slickMerchantAreas += dbMerchAreas
    } yield ()).transactionally
    db.run(act).map { _ => area }

  }

  def clear(userID: UUID) = {
    val actions = for {
      merchants <- slickMerchantAreas.filter(_.merchantId === userID.toString)
    } yield merchants
    db.run(actions.delete).map(_ => MerchantAreas(Seq()))
  }

  def deleteOne(userID: UUID, serveArea: ServeArea) = {
    val actions = for {
      ma <- slickMerchantAreas.filter(ma => ma.merchantId === userID.toString && ma.areaId === serveArea.id)
    } yield ma
    db.run(actions.delete).map(_ => serveArea)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:41,代码来源:MerchantAreasDAOImpl.scala


示例9: MerchantCertificatesDAOImpl

//设置package包名称以及导入依赖的类
package daos.merchant.impl

import java.util.UUID
import javax.inject.Inject

import daos.merchant.MerchantCertificatesDAO
import models.slick.SlickDAO
import models.{ CertificateState, CertificateType, MerchantCertificate, MerchantCertificates }
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class MerchantCertificatesDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider) extends MerchantCertificatesDAO with SlickDAO {

  import driver.api._

  
  def save(userID: UUID, cert: MerchantCertificate) = {
    val dbCert = DBCertificates(None, cert.name, cert.description, cert.value, cert.certificate_type.id)
    val insertCertificate = slickCertificates.returning(slickCertificates.map(_.id)).
      into((cer, id) => cer.copy(certificateID = Some(id))) += dbCert
    val act = (for {
      certificate <- insertCertificate
      _ <- slickMerchantCertificates += DBMerchantCertificates(userID.toString, certificate.certificateID.get)
    } yield ()).transactionally
    db.run(act).map { _ => cert }
  }

  def clear(userID: UUID) = {
    val mc = slickMerchantCertificates.filter(_.merchantId === userID.toString)
    val c = slickCertificates.filter(_.id in mc.map(_.certificateId))
    db.run((mc.delete andThen c.delete).transactionally).map(_ => MerchantCertificates(Seq()))
  }

  def deleteOne(userID: UUID, cert: MerchantCertificate) = {
    val actions = for {
      ma <- slickMerchantCertificates.filter(ma => ma.merchantId === userID.toString && ma.certificateId === cert.id)
    } yield ma
    db.run(actions.delete).map(_ => cert)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:41,代码来源:MerchantCertificatesDAOImpl.scala


示例10: SubscriberRunner

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

import java.net.InetSocketAddress
import java.util.UUID
import java.util.concurrent.locks.ReentrantLock

import com.bwsw.tstreams.agents.consumer.Offsets.Oldest
import com.bwsw.tstreams.agents.consumer.subscriber.{Callback, SubscribingConsumer}
import com.bwsw.tstreams.agents.consumer.{ConsumerOptions, SubscriberCoordinationOptions}


object SubscriberRunner {
  def main(args: Array[String]) {
    import Common._
    val consumerOptions = new ConsumerOptions[String](transactionsPreload = 10, dataPreload = 7, arrayByteToStringConverter, RoundRobinPolicyCreator.getRoundRobinPolicy(stream, List(0)), Oldest, LocalGeneratorCreator.getGen(), useLastOffset = true)

    val lock = new ReentrantLock()
    var cnt = 0
    var timeNow = System.currentTimeMillis()
    val callback = new Callback[String] {
      override def onEvent(subscriber: SubscribingConsumer[String], partition: Int, transactionUuid: UUID): Unit = {
        lock.lock()
        if (cnt % 1000 == 0) {
          val time = System.currentTimeMillis()
          val diff = time - timeNow
          println(s"subscriber_time = $diff; cnt=$cnt")
          timeNow = time
        }
        cnt += 1
        lock.unlock()
      }
    }

    val subscribeConsumer = new SubscribingConsumer[String](
      name = "test_consumer",
      stream = stream,
      options = consumerOptions,
      subscriberCoordinationOptions =
        new SubscriberCoordinationOptions(agentAddress = "t-streams-4.z1.netpoint-dc.com:8588",
          zkRootPath = "/velocity",
          zkHosts = List(new InetSocketAddress(zkHost, 2181)),
          zkSessionTimeout = 7,
          zkConnectionTimeout = 7),
      callBack = callback,
      persistentQueuePath = "persistent_queue_path")
    subscribeConsumer.start()
  }
} 
开发者ID:bwsw,项目名称:t-streams-pts-benchmark,代码行数:49,代码来源:SubscriberRunner.scala


示例11: Validator

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

import java.net.InetSocketAddress
import java.util.UUID

import com.datastax.driver.core.Cluster

import scala.collection.mutable.ListBuffer

object Validator {
  def isSorted(list: ListBuffer[UUID]): Boolean = {
    if (list.isEmpty)
      return true
    var curVal = list.head
    var v = 0
    list foreach { el =>
      if (el.timestamp() < curVal.timestamp()) {
        println(s"value=$v")
        return false
      }
      if (el.timestamp() > curVal.timestamp())
        curVal = el
      v += 1
    }
    true
  }

  def main(args: Array[String]) {
    //    if (args.length != 1)
    //      throw new IllegalArgumentException("specify [keyspace]")
    //    val keyspace = args(0)

    val cluster = Cluster.builder().addContactPointsWithPorts(new InetSocketAddress("176.120.27.82", 9042)).build()
    val session = cluster.connect()

    val set = session.execute(s"select * from velocity.commit_log").all()
    val it = set.iterator()
    val buffers = scala.collection.mutable.Map[Int, ListBuffer[UUID]]()

    while (it.hasNext) {
      val row = it.next()
      val partition = row.getInt("partition")
      val uuid = row.getUUID("transaction")
      if (!buffers.contains(partition)) {
        buffers(partition) = ListBuffer(uuid)
      } else {
        buffers(partition) += uuid
      }
    }

    val checkVal = buffers.map(x => isSorted(x._2)).reduceLeft((a, b) => a & b)

    if (checkVal)
      println("sorted")
    else
      println("not sorted")

    cluster.close()
    session.close()
  }
} 
开发者ID:bwsw,项目名称:t-streams-pts-benchmark,代码行数:62,代码来源:Validator.scala


示例12: Person

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

import java.util.UUID

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
import spray.json._

trait JsonSupportProtocols extends DefaultJsonProtocol with SprayJsonSupport {
  implicit val personProtocol = jsonFormat3(Person.apply)
}

case class Person(
                   first_name: String,
                   last_name: Option[String] = None,
                   var uuid: Option[String] = Some(UUID.randomUUID().toString)
                 ) {

  def asTuple = {
    this.uuid = Some(this.uuid.getOrElse(UUID.randomUUID().toString))
    this.uuid.get -> this
  }
}

object Person extends JsonSupportProtocols 
开发者ID:otobrglez,项目名称:proto,代码行数:26,代码来源:Person.scala


示例13: Person

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

import java.sql.Timestamp
import java.util.UUID

trait IdAble { val id: UUID; val created: Timestamp }

case class Person(id: UUID,
                  name: String,
                  description: String,
                  created: Timestamp)
    extends IdAble

case class OeMap(id: UUID,
                 ownerId: UUID,
                 title: String,
                 created: Timestamp,
                 description: String)
    extends IdAble

case class Membership(id: UUID,
                      personId: UUID,
                      mapId: UUID,
                      description: String,
                      created: Timestamp,
                      role: String)
    extends IdAble

case class Location(id: UUID,
                    personId: UUID,
                    mapId: UUID,
                    description: String,
                    created: Timestamp,
                    lat: Double,
                    lon: Double)
    extends IdAble 
开发者ID:navicore,项目名称:oemap-server,代码行数:37,代码来源:OeMap.scala


示例14: ConnectionActor

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

import java.util.UUID

import akka.actor.{Actor, Props}
import pl.mtomanski.fsmdemo.actors.ConnectionActor._
import pl.mtomanski.fsmdemo.domain.{Connection, Destination, Origin}

class ConnectionActor extends Actor {

  override def receive = {
    case FetchSoonestConnections(origin) =>
      println("Connection actor is fetching soonest connections")
      sender() ! getSoonestConnections(origin)
  }

  private def getSoonestConnections(origin: Origin) = {
    val soonestConnections = Seq(
      Connection("1", origin, destination1, departure1),
      Connection("2", origin, destination2, departure2)
    )
    SoonestConnectionsFromOrigin(soonestConnections)
  }
}

object ConnectionActor {

  def props(): Props = Props(new ConnectionActor)

  case class FetchSoonestConnections(origin: Origin)

  case class SoonestConnectionsFromOrigin(connections: Seq[Connection])

  // Mocked
  val destination1 = Destination(UUID.randomUUID().toString, "Wroclaw")
  val destination2 = Destination(UUID.randomUUID().toString, "Warsaw")
  val departure1 = "18:15"
  val departure2 = "18:30"
} 
开发者ID:michaltomanski,项目名称:fsm-demo,代码行数:40,代码来源:ConnectionActor.scala


示例15: MerchantProfileServiceImpl

//设置package包名称以及导入依赖的类
package services.merchant.impl

import java.util.UUID

import com.google.inject.Inject
import daos.merchant.MerchantProfileDAO
import models.MerchantInfo
import play.api.libs.concurrent.Execution.Implicits._
import services.merchant.MerchantProfileService

import scala.concurrent.Future

class MerchantProfileServiceImpl @Inject() (merchantProfileDAO: MerchantProfileDAO) extends MerchantProfileService {

  def edit(userID: UUID, profile: MerchantInfo): Future[MerchantInfo] = {
    merchantProfileDAO.find(userID).flatMap {
      case Some(merchantInfo) =>
        merchantProfileDAO.save(userID, profile)
      case None => merchantProfileDAO.save(userID, profile)
    }
  }
  def view(userID: UUID): Future[Option[MerchantInfo]] = merchantProfileDAO.find(userID)

} 
开发者ID:Bakuchi,项目名称:certification,代码行数:25,代码来源:MerchantProfileServiceImpl.scala


示例16: Family

//设置package包名称以及导入依赖的类
package teksol.mybank.domain.models

import java.util.{Locale, UUID}

import teksol.domain.FamilyId
import teksol.infrastructure.{EventBus, ToJson}
import teksol.mybank.domain.events.InterestRateChanged
import teksol.mybank.infrastructure.MyBankRepository

case class Family(familyId: FamilyId,
                  locale: Locale,
                  repository: MyBankRepository,
                  eventBus: EventBus) extends ToJson {

    import teksol.infrastructure.Helpers._

    def accounts: Set[Account] = repository.listAccounts(familyId)

    def changeYearlyInterestRate(yearlyInterestRate: InterestRate): Unit = {
        repository.changeYearlyInterestRate(familyId, yearlyInterestRate)
        eventBus.publish(InterestRateChanged(familyId, yearlyInterestRate))
    }

    def createAccount(name: AccountName): Account = {
        val account = Account(familyId, AccountId(UUID.randomUUID()), locale, name, Amount.ZERO, Amount.ZERO, repository, eventBus)
        repository.saveAccount(account)
        account
    }

    override def toJson: String = s"""{"family_id":${familyId.toJson},"locale":${locale.toJson}}"""
} 
开发者ID:francois,项目名称:family,代码行数:32,代码来源:Family.scala


示例17: poll

//设置package包名称以及导入依赖的类
package com.hivehome.kafka.connect.sqs

import java.util.{Properties, UUID}

import io.confluent.kafka.serializers.KafkaAvroDeserializer
import org.apache.kafka.clients.consumer.{ConsumerConfig => ConsumerConfigConst, KafkaConsumer}
import org.apache.kafka.common.serialization.ByteArrayDeserializer
import org.slf4j.LoggerFactory

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.language.postfixOps


  def poll(numberOfMessagesExpected: Int,
           timeout: FiniteDuration = 30 seconds,
           accept: V => Boolean = _ => true): Vector[V] = {

    val deadline = timeout.fromNow
    var messages = Vector.empty[V]
    while (deadline.hasTimeLeft && messages.size < numberOfMessagesExpected) {
      val records = cons.poll(PollingInterval)
      // convert to Seq so that we have all the messages once we have
      // exhausted the iterator
      val msgsSeq = records.iterator().asScala.toSeq
      messages = messages ++ msgsSeq.map(_.value()).filter(accept).toVector
    }
    logger.debug("Number of messages received {}", messages.size)

    if (messages.size < numberOfMessagesExpected) {
      throw new AssertionError(s"Expected $numberOfMessagesExpected messages within $timeout, but only received ${messages.size}. $messages")
    }

    // Possibly throw exception if too many messages?
    messages
  }
}

object KafkaAvroConsumer {
  val logger = LoggerFactory.getLogger(getClass)

  def apply[K, V](kafkaProps: Map[String, String], topicName: String): KafkaAvroConsumer[K, V] = {
    val props = new Properties()
    props.putAll(kafkaProps.asJava)
    props.put(ConsumerConfigConst.GROUP_ID_CONFIG, "test" + UUID.randomUUID().toString.substring(0, 10))
    props.put(ConsumerConfigConst.KEY_DESERIALIZER_CLASS_CONFIG, classOf[ByteArrayDeserializer])
    props.put(ConsumerConfigConst.VALUE_DESERIALIZER_CLASS_CONFIG, classOf[KafkaAvroDeserializer])

    logger.info(s"Consuming from $topicName with properties $props")
    val cons = new KafkaConsumer[K, V](props)
    cons.subscribe(Seq(topicName).asJava)
    new KafkaAvroConsumer(cons)
  }
} 
开发者ID:ConnectedHomes,项目名称:sqs-kafka-connect,代码行数:55,代码来源:KafkaAvroConsumer.scala


示例18: generate

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

import java.security.SecureRandom
import java.util.UUID

trait GameIdGenerator {
  def generate(moduleName: String): UUID
}

class NameHashedGameIdGenerator(clusterName: String) extends GameIdGenerator{
  override def generate(moduleName: String): UUID = {
    var mostSigBits = asUnsigned(clusterName.hashCode.toLong) << 32
    mostSigBits |= asUnsigned(moduleName.hashCode.toLong)

    val numberGenerator: SecureRandom = new SecureRandom()
    numberGenerator.setSeed(System.nanoTime())

    val leastSigBits = numberGenerator.nextLong()

    new UUID(mostSigBits.toLong, leastSigBits)
  }

  private def asUnsigned(unsignedLong: Long) =
    (BigInt(unsignedLong >>> 1) << 1) + (unsignedLong & 1)
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:26,代码来源:GameIdGenerator.scala


示例19: Player

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

import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Clock, LocalDateTime}
import java.util.{Base64, UUID}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{KeyGenerator, Mac}

@SerialVersionUID(1L)
class Player(val id: UUID, val name: String, val secret: String) extends Serializable {
  override def hashCode = id.hashCode()

  override def equals(other: Any) = other match {
    case that: Player => this.id == that.id
    case _ => false
  }

  override def toString = s"$name ($id)"

  def identity = PlayerIdentity(id, name)

  def isAuthorized(time: LocalDateTime, signature: String): Boolean = {
    val seconds = ChronoUnit.SECONDS.between(time, LocalDateTime.now(Clock.systemUTC()))

    if (seconds < -300 || seconds > 300) {
      false
    } else {
      val secretKeySpec = new SecretKeySpec(secret.getBytes, "HmacSHA256")
      val mac = Mac.getInstance("HmacSHA256")
      mac.init(secretKeySpec)

      val message = id.toString.toLowerCase + "|" + time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
      val hmac = mac.doFinal(message.getBytes("UTF-8"))

      val encoded = Base64.getEncoder.encodeToString(hmac)

      encoded.equalsIgnoreCase(signature)
    }
  }
}

object Player {
  def apply(name: String) = new Player(UUID.randomUUID(), name, generateKey)

  def apply(id: UUID, name: String) = new Player(id, name, generateKey)

  private def generateKey: String = {
    val keyGenerator: KeyGenerator = KeyGenerator.getInstance("HmacSHA256")
    Base64.getEncoder.encodeToString(keyGenerator.generateKey().getEncoded)
  }

  def apply(id: UUID, name: String, secret: String) = new Player(id, name, secret)

  def apply(identity: PlayerIdentity) = new Player(identity.id, identity.name, generateKey)

  def apply(identity: PlayerIdentity, secret: String) = new Player(identity.id, identity.name, secret)
}

case class PlayerIdentity(id: UUID, name: String) 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:61,代码来源:Player.scala


示例20: getStackTrace

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

import java.io.{PrintWriter, StringWriter}
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID

import spray.json.{JsValue, JsonFormat, _}

trait UsersProtocol {
  private def getStackTrace(t: Throwable) = {
    val sw: StringWriter = new StringWriter()
    val pw: PrintWriter = new PrintWriter(sw)
    t.printStackTrace(pw)
    sw.toString
  }

  implicit object ThrowableWriter extends RootJsonWriter[Throwable] {
    def write(t: Throwable) = JsObject(
      "message" -> JsString(t.getMessage),
      "cause" -> t.getCause.toJson,
      "stackTrace" -> JsString(getStackTrace(t))
    )
  }

  implicit object MessageFormat extends RootJsonWriter[Message] {
    def write(m: Message) = JsObject(
      "summary" -> JsString(m.summary),
      "errorCode" -> JsNumber(m.errorCode)
    )
  }

  implicit object ValidationFormat extends RootJsonWriter[Validation] {
    def write(v: Validation) = {
      val fields = Seq[Option[JsField]](
        Some("message"   -> JsString(v.message)),
        Some("errorCode" -> JsNumber(v.errorCode)),
        v.exception.map(exception => "exception" -> exception.toJson)
      )
      JsObject(fields.flatten: _*)
    }
  }

  implicit object UUIDFormat extends JsonFormat[UUID] {
    def write(uuid: UUID) = JsString(uuid.toString)
    def read(value: JsValue) = value match {
      case JsString(uuid) => UUID.fromString(uuid)
      case _ => deserializationError("UUID expected.")
    }
  }

  implicit object LocalDateTimeFormat extends JsonFormat[LocalDateTime] {
    def write(dateTime: LocalDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
    def read(value: JsValue) = value match {
      case JsString(dateTime) => LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
      case _ => deserializationError("LocalDateTime expected.")
    }
  }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:60,代码来源:UsersProtocol.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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