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


Scala Duration类代码示例

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


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

示例1: HermesGameTickerModuleSettings

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

import java.time.Duration
import java.util.concurrent.TimeUnit

import proton.game.GameTickerModuleSettings

import scala.concurrent.duration.FiniteDuration

class HermesGameTickerModuleSettings(baseSettings: GameTickerModuleSettings,
                                     val port: Int,
                                     val chunkSize: Int,
                                     val gameTimeoutDuration: Duration,
                                     val namesDDataTimeoutDuration: Duration,
                                     val chunkedTimeoutDuration: Duration,
                                     val chunkedAppendTimeoutDuration: Duration,
                                     val chunkedRepositoryTimeoutDuration: Duration)
  extends GameTickerModuleSettings(baseSettings) {
  val namesDDataTimeout = FiniteDuration(namesDDataTimeoutDuration.toNanos, TimeUnit.NANOSECONDS)
  val gameTimeout = FiniteDuration(gameTimeoutDuration.toNanos, TimeUnit.NANOSECONDS)
  val chunkedTimeout = FiniteDuration(chunkedTimeoutDuration.toNanos, TimeUnit.NANOSECONDS)
  val chunkedAppendTimeout = FiniteDuration(chunkedAppendTimeoutDuration.toNanos, TimeUnit.NANOSECONDS)
  val chunkedRepositoryTimeout = FiniteDuration(chunkedRepositoryTimeoutDuration.toNanos, TimeUnit.NANOSECONDS)
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:25,代码来源:HermesGameTickerModuleSettings.scala

示例2: connectionFactory

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.jms

import scala.collection.JavaConversions._
import java.util
import java.time.Duration
import javax.jms.ConnectionFactory

sealed trait JmsSettings {
  def connectionFactory: ConnectionFactory
  def destination: Option[Destination]
  def credentials: Option[Credentials]
}

sealed trait Destination
final case class Topic(name: String) extends Destination
final case class Queue(name: String) extends Destination

final case class JmsTextMessage(body: String, properties: Map[String, Any] = Map.empty) {

  
  def create(body: String, properties: util.Map[String, Any]) = JmsTextMessage(body, properties.toMap)
}

object JmsSourceSettings {

  def create(connectionFactory: ConnectionFactory) = JmsSourceSettings(connectionFactory)

}

final case class JmsSourceSettings(connectionFactory: ConnectionFactory,
                                   destination: Option[Destination] = None,
                                   credentials: Option[Credentials] = None,
                                   bufferSize: Int = 100,
                                   selector: Option[String] = None)
    extends JmsSettings {
  def withCredential(credentials: Credentials) = copy(credentials = Some(credentials))
  def withBufferSize(size: Int) = copy(bufferSize = size)
  def withQueue(name: String) = copy(destination = Some(Queue(name)))
  def withTopic(name: String) = copy(destination = Some(Topic(name)))
  def withSelector(selector: String) = copy(selector = Some(selector))
}

object JmsSinkSettings {

  def create(connectionFactory: ConnectionFactory) = JmsSinkSettings(connectionFactory)

}

final case class JmsSinkSettings(connectionFactory: ConnectionFactory,
                                 destination: Option[Destination] = None,
                                 credentials: Option[Credentials] = None,
                                 timeToLive: Option[Duration] = None)
    extends JmsSettings {
  def withCredential(credentials: Credentials) = copy(credentials = Some(credentials))
  def withQueue(name: String) = copy(destination = Some(Queue(name)))
  def withTopic(name: String) = copy(destination = Some(Topic(name)))
  def withTimeToLive(ttl: Duration) = copy(timeToLive = Some(ttl))
}

final case class Credentials(username: String, password: String) 
开发者ID:akka,项目名称:alpakka,代码行数:61,代码来源:Jms.scala

示例3: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:chriswk,项目名称:gameranker,代码行数:60,代码来源:JsonFormats.scala

示例4: ExtendedConfig

//设置package包名称以及导入依赖的类
package cz.alenkacz.marathon.scaler

import java.time.Duration

import com.typesafe.config.Config
import cz.alenkacz.marathon.scaler.rabbitmq.Client
import scala.collection.JavaConverters._

object ExtendedConfig {
  def getApplicationConfigurationList(
      config: Config,
      rabbitMqClients: Map[String, Client]): Seq[Application] = {
    if (config.hasPath("applications")) {
      config
        .getConfigList("applications")
        .asScala
        .map(a =>
          ApplicationFactory.tryCreate(
            rabbitMqClients(
              a.getOptionalString("rmqServerName").getOrElse("")),
            a.getString("name"),
            a.getOptionalString("rmqServerName").getOrElse(""),
            a.getOptionalString("vhost").getOrElse("/"),
            a.getString("queue"),
            a.getInt("maxMessagesCount"),
            a.getOptionalInt("maxInstancesCount"),
            a.getOptionalInt("minInstancesCount")
        ))
        .filter(_.isSuccess)
        .map(_.get)
    } else {
      Seq.empty
    }
  }

  implicit class RichConfig(val underlying: Config) extends AnyVal {
    def getOptionalInt(path: String): Option[Int] =
      if (underlying.hasPath(path)) {
        Some(underlying.getInt(path))
      } else {
        None
      }

    def getOptionalString(path: String): Option[String] =
      if (underlying.hasPath(path)) {
        Some(underlying.getString(path))
      } else {
        None
      }

    def getOptionalDuration(path: String): Option[Duration] =
      if (underlying.hasPath(path)) {
        Some(underlying.getDuration(path))
      } else {
        None
      }
  }
} 
开发者ID:alenkacz,项目名称:marathon-rabbitmq-autoscale,代码行数:59,代码来源:ExtendedConfig.scala

示例5: NettyBench

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

import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors

import com.naoh.beef.Client
import com.naoh.beef.Server
import com.naoh.beef.proto.echo.EchoGrpc
import com.naoh.beef.proto.echo.EchoGrpc.EchoBlockingStub
import com.naoh.beef.proto.echo.EchoReq
import io.grpc.CallOptions
import io.grpc.ManagedChannelBuilder
import io.grpc.ServerBuilder
import io.grpc.netty.NettyChannelBuilder
import io.grpc.netty.NettyServerBuilder

import scala.concurrent.ExecutionContext
import scala.util.Try


class NettyBench {

  val serverCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val clientCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val server = NettyServerBuilder.forPort(8899).addService(EchoGrpc.bindService(EchoImpl, serverCtx)).build().start()
  val ch = NettyChannelBuilder.forAddress("localhost", 8899).usePlaintext(true).build()
  val client = new EchoBlockingStub(ch, CallOptions.DEFAULT.withExecutor(clientCtx))
  Thread.sleep(1000)

  val base = Instant.now
  Iterator.range(0, 3000).toSeq.toParArray.foreach { _ => Try(client.retEcho(EchoReq("12"))); print(".") }
  val record = Duration.between(base, Instant.now())

  println(s"\n\nDuration $record \n")

  Thread.sleep(2000)
  clientCtx.shutdown()
  serverCtx.shutdown()
  server.shutdown()
  ch.shutdown()
} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:43,代码来源:NettyBench.scala

示例6: BeefTest

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

import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.naoh.beef.Auth
import com.naoh.beef.Beef
import com.naoh.beef.Client
import com.naoh.beef.Region
import com.naoh.beef.Server
import com.naoh.beef.proto.echo.EchoGrpc
import com.naoh.beef.proto.echo.EchoReq
import com.typesafe.config.ConfigFactory

import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.util.Try


class BeefTest {

  val serverSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("server.conf").resolve())
  val clientSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("client.conf").resolve())
  Cluster(serverSystem).join(Cluster(serverSystem).selfAddress)
  Cluster(clientSystem).join(Cluster(serverSystem).selfAddress)
  val serverCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val clientCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))

  val region = Region("rg")
  val auth = Auth("au")

  Thread.sleep(1000)

  Beef(serverSystem)(
    Server(region)
      << EchoGrpc.bindService(EchoImpl, serverCtx))
  Thread.sleep(1000)

  val builder = Client(region, auth, clientCtx) connect Beef(clientSystem)
  val client = builder.build(new EchoGrpc.EchoBlockingStub(_, _))
  Thread.sleep(1000)

  val base = Instant.now
  Iterator.range(0, 3000).toSeq.toParArray.foreach{_ => Try(client.retEcho(EchoReq("12"))); print(".")}
  val record = Duration.between(base, Instant.now())

  println(s"\n\nDuration $record \n")

  Thread.sleep(2000)
  clientCtx.shutdown()
  serverCtx.shutdown()
  clientSystem.shutdown()
  serverSystem.shutdown()
} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:58,代码来源:BeefTest.scala

示例7: LifeStage

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

import java.time.Duration



final class LifeStage(val name: String, val stageHours: Int, val hourDur: Duration,
                      val food: Int, val sleep: Int, val poop: Int)
{
  lazy val totalDur: Duration = hourDur.multipliedBy(stageHours)
  override def toString = name
}

object LifeStage {
  val stdHourDur: Duration = Duration.ofMillis(2000)
  val egg   = new LifeStage("Egg",   1 * 1 * 12, stdHourDur, 24, 24, 24)
  val child = new LifeStage("Child", 1 * 2 * 24, stdHourDur,  6, 12, 12)
  val teen  = new LifeStage("Teen",  1 * 2 * 24, stdHourDur,  6, 24, 24)
  val adult = new LifeStage("Adult", 1 * 4 * 24, stdHourDur,  8, 24, 24)
  val elder = new LifeStage("Elder", 1 * 4 * 24, stdHourDur, 10, 24, 24)
  val stdLifeCycle = Vector(egg, child, teen, adult, elder)
} 
开发者ID:rsazima,项目名称:tamagotchi,代码行数:23,代码来源:LifeStage.scala

示例8: jwtClaimsSetGen

//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.jwt.generators.nimbus

import java.time.{Duration, ZonedDateTime}
import java.util.Date

import com.fortysevendeg.scalacheck.datetime.GenDateTime._
import com.fortysevendeg.scalacheck.datetime.instances.jdk8._
import com.fortysevendeg.scalacheck.datetime.jdk8.granularity.minutes
import com.nimbusds.jwt.JWTClaimsSet
import org.scalacheck.Gen

trait JWTClaimsSetGen {

  def jwtClaimsSetGen(
      customClaims: Seq[(String, Any)] = Seq.empty): Gen[JWTClaimsSet] =
    for {
      issuer <- Gen.alphaStr suchThat (!_.isEmpty)
      subject <- Gen.alphaStr suchThat (!_.isEmpty)
      now = ZonedDateTime.now
      issuedAt <- Gen.const(now).map(t => Date.from(t.toInstant))
      expiration <- genDateTimeWithinRange(now.plusMinutes(5),
                                           Duration
                                             .ofMinutes(25))
        .map(t => Date.from(t.toInstant))
      builder = new JWTClaimsSet.Builder()
        .issuer(issuer)
        .subject(subject)
        .issueTime(issuedAt)
        .expirationTime(expiration)
    } yield
      customClaims
        .foldLeft(builder)((b, claim) => b.claim(claim._1, claim._2))
        .build()

} 
开发者ID:toolsplus,项目名称:atlassian-jwt,代码行数:36,代码来源:JWTClaimsSetGen.scala

示例9: CfExp

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

import java.time.{Duration, ZonedDateTime}

import io.circe.Json

trait CfExp[+T]

object CfExp {
  type E[+T] = CfExp[T]

  trait IsLit[A]

  object IsLit {
    implicit val stringLit: IsLit[String] = new IsLit[String] {}
    implicit val IntLit: IsLit[Int] = new IsLit[Int] {}
    implicit val longLit: IsLit[Long] = new IsLit[Long] {}
    implicit val doubleLit: IsLit[Double] = new IsLit[Double] {}
    implicit val boolLit: IsLit[Boolean] = new IsLit[Boolean] {}
    implicit val dateTimeLit: IsLit[ZonedDateTime] = new IsLit[ZonedDateTime] {}
    implicit val jsonLit: IsLit[Json] = new IsLit[Json] {}
    implicit val durationLit: IsLit[Duration] = new IsLit[Duration] {}
    implicit def propertyLit[T <: ResourceProperty]: IsLit[T] = new IsLit[T] {}
    implicit def listLit[A: IsLit]: IsLit[List[A]] = new IsLit[List[A]]{}
  }

  case class Lit[T: IsLit](value: T) extends E[T]

  
  case class ResourceRef(value: Resource) extends E[String]
  case class ParameterRef(value: Parameter) extends E[String]
  case class PseudoParameterRef(value: PseudoParameter) extends E[String]

  case class FnBase64(exp: E[String]) extends E[String]

  case class FnAnd(cond1: E[Boolean], cond2: E[Boolean]) extends E[Boolean]
  case class FnEquals[T](left: E[T], right: E[T]) extends E[Boolean]
  case class FnIf[T](cond: E[Boolean], ifTrue: E[T], ifFalse: E[T]) extends E[T]
  case class FnNot(cond: E[Boolean]) extends E[Boolean]
  case class FnOr(conds: E[Boolean]*) extends E[Boolean]
} 
开发者ID:typeformation,项目名称:typeformation,代码行数:42,代码来源:CfExp.scala

示例10: logicalId

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

import java.time.Duration

import io.circe.Json
import enum.Enum

package object scalacloudformation {
  trait ResourceProperty

  trait HasLogicalId {
    def logicalId: String
  }

  object ResourceAttributes {
    case class ResourceSignal(Count: CfExp[Int],
                              Timeout: CfExp[Duration])

    case class AutoscalingCreationPolicy(MinSuccessfulInstancesPercent: CfExp[Int])

    case class CreationPolicy(AutoscalingCreationPolicy: Option[AutoscalingCreationPolicy] = None,
                              ResourceSignal: Option[ResourceSignal] = None) extends ResourceProperty

    sealed trait DeletionPolicy extends ResourceProperty
    object DeletionPolicy {
      case object Delete extends DeletionPolicy
      case object Retain extends DeletionPolicy
      case object Snapshot extends DeletionPolicy

      implicit val enum: Enum[DeletionPolicy] = Enum.derived[DeletionPolicy]
    }

    case class AutoScalingReplacingUpdate(WillReplace: CfExp[Boolean])
    case class AutoScalingRollingUpdate(MaxBatchSize: Option[CfExp[Int]] = None,
                                        MinInstancesInService: Option[CfExp[Int]] = None,
                                        MinSuccessfulInstancesPercent: Option[CfExp[Int]] = None,
                                        PauseTime: Option[CfExp[Duration]] = None,
                                        WaitOnResourceSignals: Option[Boolean])
    case class AutoScalingScheduledAction(IgnoreUnmodifiedGroupSizeProperties: CfExp[Boolean])

    case class UpdatePolicy(AutoScalingReplacingUpdate: Option[AutoScalingReplacingUpdate] = None,
                            AutoScalingRollingUpdate: Option[AutoScalingRollingUpdate] = None,
                            AutoScalingScheduledAction: Option[AutoScalingScheduledAction] = None) extends ResourceProperty
  }



  trait Resource extends HasLogicalId {
    def fqn: String
    def logicalId: String
    def DependsOn: Option[Resource]
    def UpdatePolicy: Option[ResourceAttributes.UpdatePolicy]
    def DeletionPolicy: Option[ResourceAttributes.DeletionPolicy]
    def CreationPolicy: Option[ResourceAttributes.CreationPolicy]
    def jsonEncode: Json
  }

  case class Tag(key: String, value: String)
} 
开发者ID:typeformation,项目名称:typeformation,代码行数:60,代码来源:package.scala

示例11: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }

  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))

  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }

  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }

  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:adempiere,项目名称:ADReactiveSystem,代码行数:62,代码来源:JsonFormats.scala

示例12: DOExtensions

//设置package包名称以及导入依赖的类
package info.armado.ausleihe.util

import java.time.{Duration, LocalDateTime}

import info.armado.ausleihe.database.barcode._
import info.armado.ausleihe.database.entities._
import info.armado.ausleihe.remote.dataobjects.LendGameStatusData
import info.armado.ausleihe.remote.dataobjects.entities.{EnvelopeData, GameData, IdentityCardData}

object DOExtensions {
  implicit class GameExtension(game: Game) {
    def toGameData: GameData = game match {
      case Game(barcode, title, author, publisher, playerCount, gameDuration, minimumAge, _, _, available) =>
        GameData(barcode.toString, title, author, publisher, Option(minimumAge).map { _.toString() }.orNull, Option(playerCount).map { _.toString() }.orNull, Option(gameDuration).map { _.toString() }.orNull)
    }
  }

  implicit class IdentityCardExtension(idCard: IdentityCard) {
    def toIdentityCardData: IdentityCardData = IdentityCardData(idCard.barcode.toString)
  }

  implicit class EnvelopeExtension(envelope: Envelope) {
    def toEnvelopeData: EnvelopeData = EnvelopeData(envelope.barcode.toString)
  }

  implicit class LendIdentityCardExtension(lendIdCard: LendIdentityCard) {    
    def toIdentityCardData: IdentityCardData = IdentityCardData(lendIdCard.identityCard.barcode.toString, lendIdCard.owner)
    def toEnvelopeData: EnvelopeData = lendIdCard.envelope.toEnvelopeData
    def toGameData: Array[GameData] = lendIdCard.currentLendGames.map { _.toGameData }.toArray
  }

  implicit class LendGameExtension(lendGame: LendGame) {    
    def toGameData: GameData = lendGame.game.toGameData
    def toIdentityCardData: IdentityCardData = lendGame.lendIdentityCard.toIdentityCardData
    def toEnvelopeData: EnvelopeData = lendGame.lendIdentityCard.toEnvelopeData
  }

  implicit class LendGameStatusDataExtension(game: Game) {
    def toLendGameStatusData(lendGame: Option[LendGame]): LendGameStatusData = lendGame match {
      case None => LendGameStatusData(game.toGameData, false, null)
      case Some(lendGame) => LendGameStatusData(game.toGameData, true, Duration.between(lendGame.getLendTime(), LocalDateTime.now()))
    }
  }
  
  implicit def barcodeToString(barcode: Barcode): String = barcode.toString
} 
开发者ID:Spielekreis-Darmstadt,项目名称:lending,代码行数:47,代码来源:DOExtensions.scala

示例13: JsonFormats

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

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
      .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
        Try(Duration.parse(str)).toOption
      })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:lagom,项目名称:online-auction-scala,代码行数:60,代码来源:JsonFormats.scala

示例14: Pkcs12ConvertorSpec

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

import java.io.{FileOutputStream, StringReader}
import java.math.BigInteger
import java.time.{Duration, Instant}
import java.util.Date

import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers
import org.bouncycastle.asn1.x500.X500NameBuilder
import org.bouncycastle.asn1.x500.style.BCStyle
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.cert.X509v3CertificateBuilder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder
import org.specs2.mutable.Specification

class Pkcs12ConvertorSpec extends Specification {

  "Pkcs12Convertor" should {

    "parsePrivateKey" in {
      val keyPair = RSAKeyPairFactory.generate
      val pem = RSAKeyPairFactory.privateKeyToString(keyPair)
      val reader = new StringReader(pem)

      val pk = Pkcs12Convertor.parsePrivateKey(reader)
      keyPair.getPrivate.getEncoded must_== pk.getEncoded
    }

    "parseCertificate" in {
      val keyPair = RSAKeyPairFactory.generate
      val builder = new X500NameBuilder()
      builder.addRDN(BCStyle.C, "JP")
      builder.addRDN(BCStyle.CN, "Pigumer Group")
      val csr = CertificationSigningRequestFactory.generate(builder.build(), keyPair)

      val now = Instant.now()
      val notBefore = new Date(now.toEpochMilli)
      val notAfter = new Date(now.plus(Duration.ofDays(365)).toEpochMilli)

      val b = new X509v3CertificateBuilder(csr.getSubject, BigInteger.valueOf(1L), notBefore, notAfter, csr.getSubject, csr.getSubjectPublicKeyInfo)

      val sigAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA)
      val digAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)

      val privateKeyInfo = PrivateKeyFactory.createKey(keyPair.getPrivate.getEncoded)
      val contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyInfo)
      val certificate = new JcaX509CertificateConverter().getCertificate(b.build(contentSigner))

      val os = new FileOutputStream("test.p12")
      try {
        Pkcs12Convertor.write(os, keyPair.getPrivate, "test".toCharArray, certificate)
      } finally {
        os.close
      }

      success
    }
  }
} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:62,代码来源:Pkcs12ConvertorSpec.scala

示例15: JsonFormats

//设置package包名称以及导入依赖的类
package org.wex.cmsfs.monitor.api

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:shinhwazx160,项目名称:test,代码行数:57,代码来源:JsonFormats.scala


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