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


Scala UUID类代码示例

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


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


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