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

Scala Instant类代码示例

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

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



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

示例1: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:sarathraj-coder,项目名称:play2_6curd_rest,代码行数:27,代码来源:ApplicationTimer.scala


示例2: Session

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

import java.security.PrivateKey
import java.time.Instant

import akka.actor.ActorSystem
import akka.stream.Materializer

import scala.concurrent.Future

@akka.annotation.InternalApi
private[pubsub] class Session(clientEmail: String, privateKey: PrivateKey) {
  protected var maybeAccessToken: Option[Future[AccessTokenExpiry]] = None
  protected def now = Instant.now()
  protected val httpApi: HttpApi = HttpApi

  private def getNewToken()(implicit as: ActorSystem, materializer: Materializer): Future[AccessTokenExpiry] = {
    val accessToken = httpApi.getAccessToken(clientEmail = clientEmail, privateKey = privateKey, when = now)
    maybeAccessToken = Some(accessToken)
    accessToken
  }

  private def expiresSoon(g: AccessTokenExpiry): Boolean =
    g.expiresAt < (now.getEpochSecond + 60)

  def getToken()(implicit as: ActorSystem, materializer: Materializer): Future[String] = {
    import materializer.executionContext
    maybeAccessToken
      .getOrElse(getNewToken())
      .flatMap { result =>
        if (expiresSoon(result)) {
          getNewToken()
        } else {
          Future.successful(result)
        }
      }
      .map(_.accessToken)
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:40,代码来源:Session.scala


示例3: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:Tkanbara,项目名称:bookmarkShare,代码行数:27,代码来源:ApplicationTimer.scala


示例4: E2ESpec

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

import java.time.Instant

import org.scalatest.{FunSuite, Matchers}
import org.slf4j.LoggerFactory

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


class E2ESpec extends FunSuite with Matchers with SQSSupport {
  val logger = LoggerFactory.getLogger(getClass.getName)
  private val KafkaTopic: String = "connect-test"
  override val queueName = "test-sqs" // kafka connect should be setup with this SQS
  queueUrl = sqs.getQueueUrl(queueName).getQueueUrl

  private val props = Map(
    "bootstrap.servers" -> sys.env.getOrElse("KAFKA", "localhost:9092"),
    "schema.registry.url" -> sys.env.getOrElse("SCHEMA_REGISTRY", "http://localhost:8081"))

  val consumer = KafkaAvroConsumer[String, String](props, topicName = KafkaTopic)

  // Test is ignored because it does not run without dependent services
  ignore("should route message SQS -> Kafka") {
    Future {
      // sleep is required so that the message to SQS
      // is sent after the consumer is listening on the kafka topic
      Thread.sleep(500)
      logger.debug("sending message..")
      sendMessage(Instant.now().toString)
      logger.debug("sent message..")
    }

    val msgs = consumer.poll(1, accept = _ => true)

    msgs should have size 1
  }
} 
开发者ID:ConnectedHomes,项目名称:sqs-kafka-connect,代码行数:40,代码来源:E2ESpec.scala


示例5: ScheduleParser

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

import java.time.{Clock, Instant}
import javax.inject._

import akka.actor.{ActorRef, ActorSystem, Cancellable}
import play.api.Logger
import play.api._
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future
import logic.actors.schedule.CheckScheduleDateActor._

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global


@Singleton
class ScheduleParser @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,system: ActorSystem , env: Environment,
                               @Named("checkSchedule") checkScheduleDateActor: ActorRef) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  private var cancellable1:Cancellable = null



  Logger.info(s"ScheduleParser: Starting application at ${start}.")

  if(env.mode == Mode.Prod || env.mode == Mode.Dev) {
    cancellable1 = system.scheduler.schedule(2 second, 1 day ,checkScheduleDateActor , CheckScheduleDate)
  }

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ScheduleParser: Stopping application at ${clock.instant} after ${runningTime}s.")
    if(cancellable1 != null){
      cancellable1.cancel()
    }
    Future.successful(())
  }

} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:48,代码来源:ScheduleParser.scala


示例6: Marshalling

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

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala


示例7: ApplicationTimer

//设置package包名称以及导入依赖的类
@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
}
*/ 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:19,代码来源:ApplicationTimer.scala


示例8: 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


示例9: 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


示例10: string

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

import java.net.InetAddress
import java.sql.Time
import java.time.Instant
import java.util.UUID

trait DbValue {
  def string: String
  def stringOpt: Option[String]
  def strings: Seq[String]
  def int: Int
  def intOpt: Option[Int]
  def ints: Seq[Int]
  def bigInt: BigInt
  def bigIntOpt: Option[BigInt]
  def bigInts: Seq[BigInt]
  def double: Double
  def doubleOpt: Option[Double]
  def doubles: Seq[Double]
  def float: Float
  def floatOpt: Option[Float]
  def floats: Seq[Float]
  def long: Long
  def longOpt: Option[Long]
  def longs: Seq[Long]
  def bool: Boolean
  def boolOpt: Option[Boolean]
  def bools: Seq[Boolean]
  def short: Short
  def shortOpt: Option[Short]
  def shorts: Seq[Short]
  def inetAddress: InetAddress
  def inetAddresses: Seq[InetAddress]
  def inetAddressOpt: Option[InetAddress]
  def uuid: UUID
  def uuids: Seq[UUID]
  def uuidOpt: Option[UUID]
  def instant: Instant
  def instantOpt: Option[Instant]
  def time: Time
  def timeOpt: Option[Time]
  def bytes: Seq[Byte]
  def bytesOpt: Option[Seq[Byte]]
  def any: Any
} 
开发者ID:alenkacz,项目名称:postgres-scala,代码行数:47,代码来源:DbValue.scala


示例11: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._

import play.api.Logger
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:aNkM,项目名称:homework-pokemon,代码行数:29,代码来源:ApplicationTimer.scala


示例12: timestampToInstant

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

import java.time.Instant

import akka.AdapterActor
import cats.instances.option._
import fluent._

trait BlogAdapterActor extends AdapterActor {

  implicit def timestampToInstant(timestamp: Long): Instant = Instant.ofEpochMilli(timestamp)
  implicit def instantToTimestamp(instant: Instant): Long = instant.toEpochMilli

  override def translate: PartialFunction[Any, Any] = {
    case Protocol.AllPosts         => Model.AllPosts
    case message: Protocol.Post    => message.transformTo[Model.Publish]
    case message: Model.Published  => message.transformTo[Protocol.Published.type]
    case message: Model.Posts      => message.posts.map(_.transformTo[Protocol.Post])
  }

} 
开发者ID:btlines,项目名称:antikkor,代码行数:22,代码来源:BlogAdapterActor.scala


示例13: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:uryyyyyyy,项目名称:adReferenceImplementation,代码行数:27,代码来源:ApplicationTimer.scala


示例14: InfluxQueryBuilder

//设置package包名称以及导入依赖的类
package io.waylay.influxdb.query

import java.time.Instant

import io.waylay.influxdb.{SharedProtocol, InfluxDB}
import io.waylay.influxdb.InfluxDB._

object InfluxQueryBuilder extends SharedProtocol{


  sealed trait IInstant
  object Now extends IInstant
  case class Exact(instant: Instant) extends IInstant
  case class RelativeTo(to: IInstant = Now, timeToGoBack: Duration) extends IInstant



  
  private def escapeStringLiteral(tag: String) = {
    "'" + tag.replace("'","\'") + "'"
  }



  private def instantToExpression(instant: IInstant):String = instant match {
    case Now => "now()"
    case Exact(inst) => inst.toEpochMilli.toString + "ms" // TODO do we want to go more precise?
    case RelativeTo(to, timeToGoBack) => instantToExpression(to) + " - " + durationLiteral(timeToGoBack)
  }

  private def functionToSelect(iFunction: IFunction):String = iFunction match{
    case Count(Left(field)) => s"""COUNT(${escapeValue(field)})"""
    case Count(Right(func)) => s"""COUNT(${functionToSelect(func)})"""
    case Min(field)         => s"""MIN(${escapeValue(field)})"""
    case Max(field)         => s"""MAX(${escapeValue(field)})"""
    case Mean(field)        => s"""MEAN(${escapeValue(field)})"""
    case Median(field)      => s"""MEDIAN(${escapeValue(field)})"""
    case Distinct(field)    => s"""DISTINCT(${escapeValue(field)})"""
    case Sum(field)         => s"""SUM(${escapeValue(field)})"""
    case Stddev(field)      => s"""STDDEV(${escapeValue(field)})"""
    case Last(field)        => s"""LAST(${escapeValue(field)})"""
    case First(field)       => s"""FIRST(${escapeValue(field)})"""
    case other => throw new RuntimeException("not implemented: " + other.toString)
  }

  private def instantToWhereExpression(interval: Interval): Option[String] = {
    interval match {
      case Interval(None, None) => None
      case Interval(Some(start), None) => Some("time >= " + instantToExpression(start))
      case Interval(None, Some(end)) => Some("time < " + instantToExpression(end))
      case Interval(Some(start), Some(end)) => Some("time >= " + instantToExpression(start) + " AND time < " + instantToExpression(end))
    }
  }
} 
开发者ID:waylayio,项目名称:influxdb-scala,代码行数:55,代码来源:InfluxQueryBuilder.scala


示例15: DoobieHelpers

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

import java.net.{URL, URLDecoder}
import java.time.Instant

import doobie.imports._

object DoobieHelpers {
  implicit val URLMeta: Meta[URL] =
    Meta[String].nxmap(
      i => new URL(i),
      i => URLDecoder.decode(i.toString, "UTF-8")
    )

  implicit val InstantMeta: Meta[Instant] =
    Meta[java.sql.Timestamp].nxmap(
      i => i.toInstant,
      i => new java.sql.Timestamp(i.toEpochMilli)
    )
} 
开发者ID:ImageIntelligence,项目名称:pix-api,代码行数:21,代码来源:DoobieHelpers.scala


示例16: CandleDeal

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

import java.time.Instant

import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._

case class CandleDeal(ticker: String, timestamp: Long, open: Double, high: Double, low: Double, close: Double, volume: Long) {

  def updateCandleWithDeal(d: Deal): CandleDeal = {
    CandleDeal(ticker, timestamp, open, Math.max(high, d.price), Math.min(low, d.price), d.price, volume + d.size)
  }

  def toJson: String = {
    val json =
      ("ticker" -> ticker) ~
        ("timestamp" -> Instant.ofEpochMilli(timestamp).toString) ~
        ("open" -> open) ~
        ("high" -> high) ~
        ("low" -> low) ~
        ("close" -> close) ~
        ("volume" -> volume)

    compact(render(json)) + "\n"
  }

} 
开发者ID:MysterionRise,项目名称:F36161DF3FCAB001C272FD10495FAFAF,代码行数:28,代码来源:CandleDeal.scala


示例17: TemplateOpSpec

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

import java.time.Instant

import cats._
import com.ovoenergy.comms.model.{CommManifest, CommType, Service}
import models.{TemplateVersion, ZippedRawTemplate}
import org.scalatest.{FlatSpec, Matchers}

class TemplateOpSpec extends FlatSpec with Matchers {

  val templateFiles = Map(
    "emailBody" -> "My email body".getBytes,
    "header"    -> "My header".getBytes,
    "textBody"  -> "My text body".getBytes
  )

  val publishedAt = Instant.now()

  def genTemplateVersion(commManifest: CommManifest) =
    TemplateVersion(
      commManifest.name,
      commManifest.version,
      publishedAt,
      "Mr Test",
      commManifest.commType
    )

  val templateFileStream = "testing-is-fun".getBytes()

  val testInterpreter: TemplateOpA ~> Id = new (TemplateOpA ~> Id) {
    override def apply[A](fa: TemplateOpA[A]): Id[A] = fa match {
      case RetrieveTemplateFromS3(commManifest)            => templateFiles
      case RetrieveTemplateVersionFromDynamo(commManifest) => genTemplateVersion(commManifest)
      case CompressTemplates(templatesFiles)               => templateFileStream
      case _                                               => ???
    }
  }

  it should "Retrieve a template" in {

    val commManifest = CommManifest(Service, "testTemplate", "1.0")

    val template       = TemplateOp.retrieveTemplate(commManifest).foldMap(testInterpreter)
    val expectedResult = ZippedRawTemplate(templateFileStream)

    template shouldBe expectedResult
  }

} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:51,代码来源:TemplateOpSpec.scala


示例18: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant     = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:digital-wonderland,项目名称:play-webpack-typescript-react,代码行数:27,代码来源:ApplicationTimer.scala


示例19: PersonDAO

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

import java.time.Instant

import doobie.imports._

import scalaz.stream.Process

object PersonDAO {
  implicit val metaInstant =
    Meta[java.sql.Timestamp].nxmap(
      _.toInstant,
      (i: Instant) => new java.sql.Timestamp(i.toEpochMilli)
    )

  val streamPeople: Process[ConnectionIO, Person] =
    sql"select id, first_name, family_name, registered_at from people"
      .query[Person]
      .process

  val listPeople: ConnectionIO[List[Person]] =
    sql"select id, first_name, family_name, registered_at from people"
      .query[Person]
      .list

  def getPerson(id: Long): ConnectionIO[Option[Person]] =
    sql"select id, first_name, family_name, registered_at from people where id = $id"
      .query[Person]
      .option

  def updatePerson(id: Int, firstName: String, familyName: String): ConnectionIO[Person] =
    sql"update people set first_name=$firstName, family_name=$familyName where id=$id"
      .update
      .withUniqueGeneratedKeys("id", "first_name", "family_name", "registered_at")

  def insertPerson(firstName: String, familyName: String, registeredAt: Instant = Instant.now()): ConnectionIO[Person] =
    sql"insert into people (first_name, family_name, registered_at) values ($firstName, $familyName, $registeredAt)"
      .update
      .withUniqueGeneratedKeys("id", "first_name", "family_name", "registered_at")
} 
开发者ID:kbrumer,项目名称:http4s-talk,代码行数:41,代码来源:PersonDAO.scala


示例20: GpxFileReader

//设置package包名称以及导入依赖的类
package eu.kraml.io

import java.io.File
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter

import eu.kraml.model.{GpsCoordinate, Record}

import scala.collection.mutable.ListBuffer
import scala.xml.XML


object GpxFileReader {
    val formatter = DateTimeFormatter.ISO_INSTANT

    def read(gpxFile: Path): Option[List[Record]] = {
        read(gpxFile.toFile)
    }

    def read(gpxFile: File): Option[List[Record]] = {
        try {
            Some(readInternal(gpxFile))
        } catch {
            case e:Exception =>
                None
        }
    }

    private def readInternal(gpxFile: File): List[Record] = {
        val gpx = XML.loadFile(gpxFile)
        val segment = gpx \ "trk" \ "trkseg"
        val points = segment \ "trkpt"
        val records = ListBuffer[Record]()
        points.foreach(n => {
            val lat = n.attribute("lat").get.head.text
            val lon = n.attribute("lon").get.head.text
            val timestampText = (n \ "time").text
            val timestamp = Instant.parse(timestampText)
            records += Record(new GpsCoordinate(lat.toDouble, lon.toDouble), timestamp)
        })
        records.toList
    }
} 
开发者ID:jkraml,项目名称:gpsplot,代码行数:45,代码来源:GpxFileReader.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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