本文整理汇总了Scala中java.time.ZonedDateTime类的典型用法代码示例。如果您正苦于以下问题:Scala ZonedDateTime类的具体用法?Scala ZonedDateTime怎么用?Scala ZonedDateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ZonedDateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Rfc3339Util
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.time.format.{ DateTimeFormatter, DateTimeParseException }
import java.time.{ LocalDate, ZoneId, ZonedDateTime }
object Rfc3339Util {
private val fullDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
private val shortDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
private val shortDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
private val fullDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'")
private val dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZ")
def parseDateTime(datestring: String): ZonedDateTime =
if (datestring.endsWith("Z") || datestring.endsWith("z")) parseFull(datestring)
else parseParts(datestring)
def parseDate(datestring: String): LocalDate =
LocalDate.parse(datestring, fullDate)
def writeDate(date: LocalDate): String = fullDate.format(date)
def writeDateTime(date: ZonedDateTime): String = dateTime.format(date)
private def parseParts(datestring: String): ZonedDateTime = {
//step one, split off the timezone.
val sepChar = if (datestring.indexOf('+') > 0) '+' else '-'
val firstpart = datestring.substring(0, datestring.lastIndexOf(sepChar.toInt))
val secondpart = datestring.substring(datestring.lastIndexOf(sepChar.toInt))
//step two, remove the colon from the timezone offset
val thirdpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1)
val dstring = firstpart + thirdpart
try {
ZonedDateTime.parse(dstring, shortDateTime)
} catch {
case pe: DateTimeParseException =>
ZonedDateTime.parse(dstring, dateTime)
}
}
private def parseFull(datestring: String): ZonedDateTime = {
val z = ZoneId.systemDefault()
try {
ZonedDateTime.parse(datestring, shortDTWithTicks.withZone(z))
} catch {
case p: DateTimeParseException => ZonedDateTime.parse(datestring, fullDTWithTicks.withZone(z))
}
}
}
示例2: genericEncoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.sql.{PreparedStatement, Types}
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
trait Encoders {
this: JdbcSource[_, _] =>
import Formatters._
private def genericEncoder[T](valueToString: (T => String)): Encoder[T] = {
new Encoder[T] {
override def apply(index: Int, value: T, row: PreparedStatement) = {
val sqlLiteral = valueToString(value)
row.setObject(index + 1, sqlLiteral, Types.OTHER)
row
}
}
}
private def tuple[T](t: (T, T))(valToStr: T => String) = s"[${valToStr(t._1)}, ${valToStr(t._2)}]"
implicit val dateTupleEncoder: Encoder[(Date, Date)] = genericEncoder(tuple(_)(formatDate))
implicit val localDateTimeTupleEncoder: Encoder[(LocalDateTime, LocalDateTime)] =
genericEncoder(tuple(_)(formatLocalDateTime))
implicit val zonedDateTimeTupleEncoder: Encoder[(ZonedDateTime, ZonedDateTime)] =
genericEncoder(tuple(_)(formatZonedDateTime))
implicit val dateTimeTupleEncoder: Encoder[(LocalDate, LocalDate)] =
genericEncoder(t => s"[${formatLocalDate(t._1)}, ${formatLocalDate(t._2)})")
}
示例3: MessageParser
//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.collector.parsing
import java.time.ZonedDateTime
import FromCSVtoCaseClass.rowParserFor
import com.darienmt.airplaneadventures.basestation.data.BaseStation._
import scala.util.{ Failure, Success, Try }
object MessageParser {
def apply(l: String): Message = parse(l.split(",").toList) match {
case Success(m) => m
case Failure(ex) => ErrorMessage(l, ex.toString, ZonedDateTime.now())
}
protected val parse: List[String] => Try[Message] = {
case "SEL" :: "" :: rest => rowParserFor[SelectionChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "ID" :: "" :: rest => rowParserFor[IdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "AIR" :: "" :: rest => rowParserFor[NewAircraftMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10))
case "STA" :: "" :: rest => rowParserFor[StatusChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "CLK" :: "" :: rest => rowParserFor[ClickMessage](rest, List(3, 7, 8, 9, 10))
case "MSG" :: "1" :: rest => rowParserFor[ESIdentificationAncCategoryMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "MSG" :: "2" :: rest => rowParserFor[ESSurfacePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 22))
case "MSG" :: "3" :: rest => rowParserFor[ESAirbornePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 19, 20, 21, 22))
case "MSG" :: "4" :: rest => rowParserFor[ESAirborneVelocityMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 17))
case "MSG" :: "5" :: rest => rowParserFor[SurveillanceAltMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 19, 21, 22))
case "MSG" :: "6" :: rest => rowParserFor[SurveillanceIdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 19, 20, 21, 22))
case "MSG" :: "7" :: rest => rowParserFor[AirToAirMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 22))
case "MSG" :: "8" :: rest => rowParserFor[AllCallReplyMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 22))
case x => Failure(new Exception(s"Unknown message => $x"))
}
}
示例4: Global
//设置package包名称以及导入依赖的类
package shared
import play.api.libs.json._
import models.Building
import java.time.{ ZonedDateTime, ZoneId, DayOfWeek }
//Constants or constnat builders that are not messages
object Global {
final val ZONEID = "Asia/Seoul"
val baseStartTime = 9
val baseEndTime = 17
val classroomList = ("1202" :: "1203" :: "1204" :: "1205" :: "1206" :: "1207" :: "1208" :: Nil) ++
("1210" :: "1211" :: "1301" :: "1302" :: "1303" :: "1304" :: "1305" :: "1306" :: "1307" :: Nil) ++
("1308" :: "1309" :: "1310" :: "1311" :: "1401" :: "1402" :: "1403" :: "1404" :: "1405" :: Nil) ++
("1406" :: "1407" :: "1408" :: "1409" :: "1501" :: "1502" :: "1503" :: "1504" :: "1505" :: Nil) ++
("1506" :: "1507" :: "1508" :: "1509" :: "1601" :: "1602" :: "1603" :: "1604" :: "1605" :: Nil) ++
("1606" :: "1607" :: "1608" :: "1609" :: "2201" :: "2202" :: "2203" :: "2204" :: "2205" :: Nil) ++
("2207" :: "2208" :: "2210" :: "2401" :: "2402" :: "2403" :: "2404" :: "2405" :: "2407" :: Nil) ++
("2408" :: "2409" :: "2501" :: "2502" :: "2503" :: "2504" :: "2506" :: "2507" :: "2508" :: Nil) ++
("2509" :: "3201" :: "3203" :: "3205" :: "3206" :: "3301" :: "3302" :: "3303" :: "3304" :: Nil) ++
("3305" :: "3306" :: "3307" :: "3308" :: "3401" :: "3402" :: "3403" :: "3404" :: "3405" :: Nil) ++
("3406" :: "3407" :: "3408" :: "3409" :: "3501" :: "3502" :: "3503" :: "3504" :: "3505" :: Nil) ++
("3506" :: "3507" :: "3508" :: "3509" :: "C301" :: "C302" :: "C304" :: "C305" :: "C306" :: Nil) ++
("C307" :: "C308" :: "C309" :: "C310" :: "C311" :: "C401" :: "C402" :: "C405" :: "C406" :: Nil) ++
("C407" :: "C408" :: "C409" :: "C410" :: "C411" :: "C412" :: "C413" :: "C501" :: "C509" :: Nil) ++
("C510" :: "C513" :: "C514" :: "C515" :: "C606" :: "C614" :: "C615" :: "C616" :: Nil) ++
("0109" :: "0115" :: "0116" :: "0117" :: "0118" :: "0221" :: "0225" :: "0328" :: "0329" :: "0330" :: "0338" :: Nil)
def keyboardTemplate(buttons: Seq[String]) = Json.obj(
"type" -> "buttons",
"buttons" -> buttons
)
def responseTemplate(message: String, buttons: Seq[String]) = Json.obj(
"message" -> Map(
"text" -> message
),
"keyboard" -> keyboardTemplate(buttons)
)
def nowIsApplicable() = {
val time = ZonedDateTime.now(ZoneId.of(ZONEID))
val dow = time.getDayOfWeek.getValue()
val hour = time.getHour()
dow <= 5 && dow >= 1 && hour >= 9 && hour < 17
}
}
示例5: putStatus
//设置package包名称以及导入依赖的类
package org.wex.cmsfs.common.monitor
import java.time.format.DateTimeFormatter
import java.time.{ZoneOffset, ZonedDateTime}
import com.redis.RedisClient
import play.api.libs.json._
trait MonitorStatus {
val r = new RedisClient("redis.cmsfs.org", 6379)
def putStatus(id: Int, stage: String)(state: Boolean, result: String) = {
val stageStatus = CoreMonitorStageStatus(state, result)
val key = s"${id}_${stage}"
r.set(key, Json.toJson(stageStatus).toString())
}
}
case class CoreMonitorStatus(id: Int, category: String, name: String, metric: String,
collect: CoreMonitorCollectStatus,
analyze: Option[CoreMonitorAnalyzeStatus],
Alarm: Option[CoreMonitorAlarmStatus])
object CoreMonitorStatus {
implicit val format: Format[CoreMonitorStatus] = Json.format
}
case class CoreMonitorStageStatus(state: Boolean, result: String,
timestamp: String = ZonedDateTime.now(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:m:s")))
object CoreMonitorStageStatus {
implicit val format: Format[CoreMonitorStageStatus] = Json.format
}
case class CoreMonitorCollectStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorCollectStatus {
implicit val format: Format[CoreMonitorCollectStatus] = Json.format
}
case class CoreMonitorAnalyzeStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorAnalyzeStatus {
implicit val format: Format[CoreMonitorAnalyzeStatus] = Json.format
}
case class CoreMonitorAlarmStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorAlarmStatus {
implicit val format: Format[CoreMonitorAlarmStatus] = Json.format
}
示例6: Signer
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.auth
import java.security.MessageDigest
import java.time.{ZoneOffset, ZonedDateTime}
import java.time.format.DateTimeFormatter
import akka.actor.ActorSystem
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.ActorMaterializer
object Signer {
private val dateFormatter = DateTimeFormatter.ofPattern("YYYYMMdd'T'HHmmssX")
private val unsignedPlayload = "UNSIGNED-PAYLOAD"
def signedRequest(request: HttpRequest,
key: SigningKey,
date: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC)): HttpRequest = {
//there we don't sha content, because we use the source to passthrough the data
val headersToAdd = Vector(RawHeader("x-amz-date", date.format(dateFormatter)),
RawHeader("x-amz-content-sha256", unsignedPlayload))
val reqWithHeaders = request.withHeaders(request.headers ++ headersToAdd)
val cr = CanonicalRequest.from(reqWithHeaders)
val authHeader = authorizationHeader("AWS4-HMAC-SHA256", key, date, cr)
reqWithHeaders.withHeaders(reqWithHeaders.headers :+ authHeader)
}
private[this] def authorizationHeader(algorithm: String,
key: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): HttpHeader = {
RawHeader("Authorization", authorizationString(algorithm, key, requestDate, canonicalRequest))
}
private[this] def authorizationString(algorithm: String,
key: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): String = {
val sign = key.hexEncodedSignature(stringToSign(algorithm, key, requestDate, canonicalRequest).getBytes())
s"$algorithm Credential=${key.credentialString}, SignedHeaders=${canonicalRequest.signedHeaders}, Signature=$sign"
}
def stringToSign(algorithm: String,
signingKey: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): String = {
val digest = MessageDigest.getInstance("SHA-256")
val hashedRequest = encodeHex(digest.digest(canonicalRequest.canonicalString.getBytes()))
val date = requestDate.format(dateFormatter)
val scope = signingKey.scope.scopeString
s"$algorithm\n$date\n$scope\n$hashedRequest"
}
def Md5(data: String): String = {
val md5 = java.security.MessageDigest.getInstance("MD5")
val byte = data.getBytes("UTF-8")
new sun.misc.BASE64Encoder().encode(md5.digest(byte))
}
}
示例7: TodoDas
//设置package包名称以及导入依赖的类
package example.db
import java.time.ZonedDateTime
import akka.NotUsed
import akka.stream.scaladsl.Source
import scala.concurrent.ExecutionContext
class TodoDas(todoDao: TodoDao) {
def findById(id: TodoId): Source[Todo, NotUsed] =
Source.fromPublisher(todoDao.resolveAsStream(id))
def findAll: Source[Todo, NotUsed] =
Source.fromPublisher(todoDao.resolveAllAsStream)
def create(todo: Todo)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.fromFuture {
todoDao.create(todo)
}
def update(id: TodoId, text: String, updateAt: ZonedDateTime, version: Long)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.fromFuture {
todoDao.update(id, text, updateAt, version)
}
def delete(id: TodoId)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.single(id).mapAsync(1) { id =>
todoDao.delete(id)
}
}
示例8: decoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
import io.gustavoamigo.quill.pgsql.encoding.GenericDecoder
trait Decoders extends GenericDecoder {
this: JdbcSource[_, _] =>
import Formatters._
private val rangePattern = """([0-9\-\+\. :]+)""".r
private def decoder[T](map: String => T) = decode(s => {
val dates = rangePattern.findAllIn(s).toList
(map(dates.head), map(dates.last))
})
implicit val dateTupleDecoder: Decoder[(Date, Date)] = decoder(parseDate)
implicit val localDateTimeTupleDecoder: Decoder[(LocalDateTime, LocalDateTime)] = decoder(parseLocalDateTime)
implicit val zonedDateTimeTupleDecoder: Decoder[(ZonedDateTime, ZonedDateTime)] = decoder(parseZonedDateTime)
implicit val localDateTupleDecoder: Decoder[(LocalDate, LocalDate)] = decoder(parseLocalDate)
}
示例9: PersistingAccountGroupSpec
//设置package包名称以及导入依赖的类
package com.gilesc
package mynab
import java.time.LocalDate
import com.gilesc.mynab.account._
import com.gilesc.mynab.category._
import com.gilesc.mynab.transaction._
import com.gilesc.mynab.user._
import com.gilesc.mynab.persistence.account.AccountGroupRepository.CreateContext
import com.gilesc.mynab.persistence.account._
import AccountGroupService.FindByName
import java.time.ZonedDateTime
class PersistingAccountGroupSpec extends TestCase
with MockAccountCreation {
val id = 1L
val validName = "newaccountgroup"
val invalidName = "r"
val time = ZonedDateTime.now()
"Giving the service an AccountName" should "persist the account group" in {
val userId = UserId(id)
val expected = AccountGroup.create(id, validName)
def mockSave(ctx: CreateContext) = Right(AccountGroupId(id))
AccountGroupService.create(mockSave)(userId, validName) should be(Right(expected))
}
it should "find an account group given a proper account name" in {
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
Right(Option(AccountGroupRow(id, an, time, time, None)))
AccountGroupService.find(mockFind)(FindByName(validName)) should be(
Right(Some(AccountGroup.create(1L, validName))))
}
it should "never call the mock function if an invalid account name is provided" in {
val expected = s"$invalidName is not a valid account name"
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
sys.error("Somehow passed the AccountName restriction")
AccountGroupService.find(mockFind)(FindByName(invalidName)) should be(Left(expected))
}
it should "fail gracefully if the database contains an invalid name" in {
val expected = s"n is not a valid account name"
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
Left(InvalidAccountNameLength("n"))
AccountGroupService.find(mockFind)(FindByName(validName)) should be(Left(expected))
}
}
示例10: 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()
}
示例11: Rfc3339UtilTest
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.time.{ LocalDateTime, ZoneId, ZoneOffset, ZonedDateTime }
import org.scalatest.{ FunSpec, MustMatchers }
class Rfc3339UtilTest extends FunSpec with MustMatchers {
val dtz = ZoneId.of("UTC")
val offset = ZoneOffset.UTC
//noinspection ScalaStyle
val date = ZonedDateTime.of(LocalDateTime.ofEpochSecond(1451911387L, 0, offset), dtz)
describe("Rfc3339UtilTest") {
it("should parse RFC3339 DateTime") {
Rfc3339Util.parseDateTime("2007-05-01T15:43:26-00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452-01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T16:43:26.345200Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T14:43:26.345200Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26.345200Z[UTC]"
}
it("should parse RFC3339 Date") {
Rfc3339Util.parseDate("2007-05-01").toString mustBe "2007-05-01"
Rfc3339Util.parseDate("2008-05-01").toString mustBe "2008-05-01"
Rfc3339Util.parseDate("2007-08-01").toString mustBe "2007-08-01"
Rfc3339Util.parseDate("2007-05-08").toString mustBe "2007-05-08"
}
it("should write DateTime") {
Rfc3339Util.writeDateTime(date) mustBe "2016-01-04T12:43:07.0000+0000"
}
it("should write Date") {
Rfc3339Util.writeDate(date.toLocalDate) mustBe "2016-01-04"
}
}
}
示例12: Value
//设置package包名称以及导入依赖的类
package all_of_imports
import java.time.ZonedDateTime
//noinspection ScalaStyle
package yaml {
trait IValue {
def `type`: String
}
case class Value(`type`: String) extends IValue
case class DatetimeValue(`type`: String, value: ZonedDateTime) extends IValue
import play.api.libs.json._
import play.api.libs.functional.syntax._
import de.zalando.play.controllers.MissingDefaultReads
object BodyReads extends MissingDefaultReads {
implicit val DatetimeValueReads: Reads[DatetimeValue] = (
(JsPath \ "`type`").read[String] and (JsPath \ "value").read[ZonedDateTime]
)(DatetimeValue.apply _)
implicit val ValueReads: Reads[Value] = (
(JsPath \ "`type`").read[String]
).map(Value.apply )
}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import de.zalando.play.controllers.MissingDefaultWrites
object ResponseWrites extends MissingDefaultWrites {
implicit val DatetimeValueWrites: Writes[DatetimeValue] = new Writes[DatetimeValue] {
def writes(ss: DatetimeValue) =
Json.obj(
"`type`" -> ss.`type`,
"value" -> ss.value
)
}
implicit val ValueWrites: Writes[Value] = new Writes[Value] {
def writes(ss: Value) =
Json.obj(
"`type`" -> ss.`type`
)
}
}
}
// should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922
//noinspection ScalaStyle
package object yaml {
type PostResponses400 = Null
}
示例13: 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]
}
示例14: TimeStampFormatter
//设置package包名称以及导入依赖的类
package wvlet.core.scales
import java.time.{Instant, ZoneId, ZoneOffset, ZonedDateTime}
import java.time.format.{DateTimeFormatterBuilder, SignStyle}
import java.util.Locale
object TimeStampFormatter {
import java.time.temporal.ChronoField._
val noSpaceTimestampFormat = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendLiteral('.')
.appendValue(MILLI_OF_SECOND, 3)
.appendOffset("+HHMM", "Z")
.toFormatter(Locale.US)
val humanReadableTimestampFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendOffset("+HHMM", "Z")
.toFormatter(Locale.US)
def formatTimestamp(time:ZonedDateTime): String = {
humanReadableTimestampFormatter.format(time)
}
def formatTimestamp(timeMillis: Long, zone:ZoneOffset=TimeWindow.systemZone): String = {
val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), zone)
humanReadableTimestampFormatter.format(timestamp)
}
def formatTimestampWithNoSpaace(timeMillis:Long) : String = {
val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), TimeWindow.systemZone)
noSpaceTimestampFormat.format(timestamp)
}
}
示例15: Metadata
//设置package包名称以及导入依赖的类
package delorean
import java.nio.file.{Files, Paths}
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter.ofPattern
import delorean.FileOps.getLinesOfFile
/**
* Class for holding metadata information. Basically a POJO.
*/
case class Metadata(pitstop: String, time: ZonedDateTime, rider: String, parents: Array[String], riderLog: String)
object Metadata {
/**
* Creates a Metadata object by parsing the metadata file of a pitstop
* Typical metadata looks like this
* *****
* Time:Mar 12 2017 10:07 PM India Standard Time
* Rider:dperla
* Parent(s):abc123def456:qwe098rty765
* RiderLog:
* A new Rider in town
* *****
* And using that structure, we parse the file to get the required information
*
* @param pitstopHash : Pitstop for which we need Metadata
* @return
*/
def apply(pitstopHash: String): Metadata = {
val metadataFile: String = {
if (Files.exists(Paths.get(INDICATORS_FOLDER + pitstopHash)))
METADATA_FOLDER + getLinesOfFile(INDICATORS_FOLDER + pitstopHash).head
else
METADATA_FOLDER + pitstopHash
}
val metadataFileContent: Seq[String] = getLinesOfFile(metadataFile)
val time: ZonedDateTime = {
ZonedDateTime.parse(metadataFileContent.head.split(":", 2)(1), ofPattern("MMM dd yyyy hh:mm a zzzz"))
}
val rider: String = metadataFileContent(1).split(":", 2)(1)
// parents hashes will be separated by ':'. So, split will split across all those :'s and tail gives us
// everything other than the first one.
val parents: Array[String] = metadataFileContent(2).split(":").tail
val riderLog: String = metadataFileContent.last
new Metadata(pitstopHash, time, rider, parents, riderLog)
}
}