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

Scala DateTimeZone类代码示例

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

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



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

示例1: GeoTagSpec

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

import java.util.UUID
import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._
import scala.io.Source

@RunWith(classOf[JUnitRunner])
class GeoTagSpec extends Specification {
  
  private val DATE_TIME_PATTERN = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")

  "The sample geotag" should {
    
    "be properly created from JSON" in {
      val json = Source.fromFile("test/resources/models/geotag/geotag.json").getLines().mkString("\n")
      val result = Json.fromJson[GeoTag](Json.parse(json))
      
      // Parsed without errors?
      result.isSuccess must equalTo(true) 
      
      val geotag = result.get
      geotag.annotationId must equalTo(UUID.fromString("5c25d207-11a5-49f0-b2a7-61a6ae63d96c"))
      geotag.documentId must equalTo("qhljvnxnuuc9i0")
      geotag.filepartId must equalTo(UUID.fromString("f903b736-cae8-4fe3-9bda-01583783548b"))
      geotag.gazetteerUri must equalTo("http://pleiades.stoa.org/places/118543")
      geotag.lastModifiedAt must equalTo(DateTime.parse("2016-09-19T13:09:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
    }
    
  }
  
  "JSON serialization/parsing roundtrip" should {
    
    "yield an equal geotag" in {
      val geotag = GeoTag(
        UUID.randomUUID(),
        "qhljvnxnuuc9i0",
        UUID.fromString("841f9462-beb0-4967-ad48-64af323fc4c1"),
        "http://pleiades.stoa.org/places/118543",
        Seq.empty[String], // toponym
        Seq.empty[String], // contributors
        None, // lastModifiedBy
        DateTime.parse("2016-02-23T18:24:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
        
      // Convert to JSON
      val serialized = Json.prettyPrint(Json.toJson(geotag))
      
      val parseResult = Json.fromJson[GeoTag](Json.parse(serialized))
      parseResult.isSuccess must equalTo(true)
      parseResult.get must equalTo(geotag)
    }
    
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:GeoTagSpec.scala


示例2: RecordPaymentRequest

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

import models.Entry
import org.joda.time.{DateTime, DateTimeZone}

import scala.util.Try


case class RecordPaymentRequest(
                            coupleId: Long,
                            payerUserId: Long,
                            amount: Double,
                            submitterUserId: Long
                          ) {
  def toEntry: Try[Entry] = Try {
    val subPer = if (submitterUserId == payerUserId) 0 else 100
    Entry(
      id = None,
      coupleId = coupleId,
      date = DateTime.now(DateTimeZone.UTC),
      payerUserId = payerUserId,
      amount = amount,
      submitterUserId = submitterUserId,
      submitterPercent = subPer
    )
  }
} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPaymentRequest.scala


示例3: RecordPurchaseRequest

//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Entry
import org.joda.time.{DateTime, DateTimeZone}

import scala.util.Try


case class RecordPurchaseRequest(
                               payerUserId: Long,
                               amount: Double,
                               submitterPercent: Long,
                               note: Option[String]
) {
  def toEntry(coupleId: Long, submitterUserId: Long): Try[Entry] = Try {
    Entry(
      id = None,
      coupleId = coupleId,
      date = DateTime.now(DateTimeZone.UTC),
      payerUserId = payerUserId,
      amount = amount,
      submitterUserId = submitterUserId,
      submitterPercent = submitterPercent,
      note = note
    )
  }

} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPurchaseRequest.scala


示例4: PlayGlobalSettings

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

import java.util.TimeZone

import jdub.async.Database
import org.joda.time.DateTimeZone
import play.api.{ Application, GlobalSettings }
import services.database.Schema

object PlayGlobalSettings extends GlobalSettings {
  override def onStart(app: Application) = {
    DateTimeZone.setDefault(DateTimeZone.UTC)
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"))

    val cnf = play.api.Play.current.configuration
    val host = cnf.getString("db.host").getOrElse("localhost")
    val port = 5432
    val database = cnf.getString("db.database")
    val username = cnf.getString("db.username").getOrElse("silhouette")
    val password = cnf.getString("db.password")

    Database.open(username, host, port, password, database)
    Schema.update()

    super.onStart(app)
  }

  override def onStop(app: Application) = {
    Database.close()
    super.onStop(app)
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:33,代码来源:PlayGlobalSettings.scala


示例5: PelagiosRDFCrosswalk

//设置package包名称以及导入依赖的类
package models.place.crosswalks

import java.io.InputStream
import models.place._
import org.joda.time.{ DateTime, DateTimeZone }
import org.pelagios.Scalagios
import org.pelagios.api.PeriodOfTime
import java.io.File
import java.io.FileInputStream

object PelagiosRDFCrosswalk {
  
  private def convertPeriodOfTime(period: PeriodOfTime): TemporalBounds = {
    val startDate = period.start
    val endDate = period.end.getOrElse(startDate)
    
    TemporalBounds(
      new DateTime(startDate).withZone(DateTimeZone.UTC), 
      new DateTime(endDate).withZone(DateTimeZone.UTC))          
  }
  
  def fromRDF(filename: String): InputStream => Seq[GazetteerRecord] = {
    
    val sourceGazetteer = Gazetteer(filename.substring(0, filename.indexOf('.')))
  
    def convertPlace(place: org.pelagios.api.gazetteer.Place): GazetteerRecord =
      GazetteerRecord(
        GazetteerRecord.normalizeURI(place.uri),
        sourceGazetteer,
        DateTime.now().withZone(DateTimeZone.UTC),
        None,
        place.label,
        place.descriptions.map(l => Description(l.chars, l.lang)),
        place.names.map(l => Name(l.chars, l.lang)),
        place.location.map(_.geometry),
        place.location.map(_.pointLocation),
        place.temporalCoverage.map(convertPeriodOfTime(_)),
        place.category.map(category => Seq(category.toString)).getOrElse(Seq.empty[String]),
        None, // country code
        None, // population
        place.closeMatches.map(GazetteerRecord.normalizeURI(_)),
        place.exactMatches.map(GazetteerRecord.normalizeURI(_)))
    
    // Return crosswalk function
    { stream: InputStream =>
      Scalagios.readPlaces(stream, filename).map(convertPlace).toSeq }
  }
  
  def readFile(file: File): Seq[GazetteerRecord] =
    fromRDF(file.getName)(new FileInputStream(file))
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:53,代码来源:PelagiosRDFCrosswalk.scala


示例6: TemporalBounds

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

import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

case class TemporalBounds(from: DateTime, to: DateTime)

object TemporalBounds {

  private val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd").withZone(DateTimeZone.UTC)

  implicit val dateFormat =
    Format(
      JsPath.read[JsString].map { json =>
        dateFormatter.parseDateTime(json.value)
      },

      Writes[DateTime] { dt =>
        Json.toJson(dateFormatter.print(dt))
      }
    )

  
  private def flexDateWrite(dt: DateTime): JsValue =
    if (dt.monthOfYear == 1 && dt.dayOfMonth == 1 && dt.minuteOfDay == 0)
      Json.toJson(dt.year.get)
    else
      Json.toJson(dt)

  implicit val temporalBoundsFormat: Format[TemporalBounds] = (
    (JsPath \ "from").format[JsValue].inmap[DateTime](flexDateRead, flexDateWrite) and
    (JsPath \ "to").format[JsValue].inmap[DateTime](flexDateRead, flexDateWrite)
  )(TemporalBounds.apply, unlift(TemporalBounds.unapply))

  def computeUnion(bounds: Seq[TemporalBounds]): TemporalBounds = {
    val from = bounds.map(_.from.getMillis).min
    val to = bounds.map(_.to.getMillis).max
    TemporalBounds(
      new DateTime(from, DateTimeZone.UTC),
      new DateTime(to, DateTimeZone.UTC))
  }

  def fromYears(from: Int, to: Int): TemporalBounds = {
    val f = new DateTime(DateTimeZone.UTC).withDate(from, 1, 1).withTime(0, 0, 0, 0)
    val t = new DateTime(DateTimeZone.UTC).withDate(to, 1, 1).withTime(0, 0, 0, 0)
    TemporalBounds(f, t)
  }

} 
开发者ID:pelagios,项目名称:recogito2,代码行数:53,代码来源:TemporalBounds.scala


示例7: MongoImplicits

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

import org.joda.time.{DateTimeZone, DateTime}
import play.api.libs.json._
import reactivemongo.bson.BSONObjectID


object MongoImplicits {
  // Reads / Writes implicit for BSONObjectID
  implicit val objectIdRead: Reads[BSONObjectID] =
    (__ \ "$oid").read[String].map { oid =>
      BSONObjectID(oid)
    }
  implicit val objectIdWrite: Writes[BSONObjectID] = new Writes[BSONObjectID] {
    def writes(objectId: BSONObjectID): JsValue = Json.obj(
      "$oid" -> objectId.stringify
    )
  }
  // Read / write implicit for DateTime
  implicit val dateTimeRead: Reads[DateTime] =
    (__ \ "$date").read[Long].map { dateTime =>
      new DateTime(dateTime, DateTimeZone.UTC)
    }

  implicit val dateTimeWrite: Writes[DateTime] = new Writes[DateTime] {
    def writes(dateTime: DateTime): JsValue = Json.obj(
      "$date" -> dateTime.getMillis
    )
  }

  implicit val objectIdFormats = Format(objectIdRead, objectIdWrite)
  implicit val dateTimeFormats = Format(dateTimeRead, dateTimeWrite)

} 
开发者ID:ranraj,项目名称:reactive-play-angular,代码行数:35,代码来源:MongoImplicits.scala


示例8: Rfc3339Spec

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query

import com.pygmalios.reactiveinflux.{PointTime, Rfc3339, StringValue}
import org.joda.time.{DateTime, DateTimeZone}
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Rfc3339Spec extends FlatSpec {
  behavior of "apply"

  it should "parse ISO time 1970-01-01T00:00:00Z" in {
    assert(Rfc3339(StringValue("1970-01-01T00:00:00Z")) ==
      PointTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC)))
  }

  it should "parse ISO time 2015-01-29T21:55:43.702900257Z" in {
    assert(Rfc3339(StringValue("2015-01-29T21:55:43.702900257Z")) ==
      PointTime(new DateTime(2015, 1, 29, 21, 55, 43, 702, DateTimeZone.UTC)))
  }
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:23,代码来源:Rfc3339Spec.scala


示例9: PointSpec

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.write

import com.pygmalios.reactiveinflux._
import org.joda.time.{DateTime, DateTimeZone, Duration}

object PointSpec {
  val dateTime1 = new DateTime(1983, 1, 10, 11, 42, 7, 13, DateTimeZone.UTC)
  val time1 = PointTime(dateTime1)
  val point1 = Point(time1, "m1", Map.empty, Map("fk" -> LongFieldValue(-1)))

  val time2 = time1.plus(Duration.millis(3))
  val point2 = Point(time2, "m2", Map("tk1" -> "tv1", "tk2" -> "tv2"),
    Map(
      "fk" -> BooleanFieldValue(true),
      "fk2" -> BigDecimalFieldValue(1),
      "fk3" -> StringFieldValue("abcXYZ")
    ))
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:19,代码来源:PointSpec.scala


示例10: JsonSupport

//设置package包名称以及导入依赖的类
package se.meldrum.machine.http

import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTime, DateTimeZone}
import se.meldrum.machine.db.models.Task

object JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  // To make Joda DateTime available
  // cred to suin
  implicit object DateTimeJsonFormat extends RootJsonFormat[DateTime] {
    private lazy val format = ISODateTimeFormat.dateTimeNoMillis()
    def write(datetime: DateTime): JsValue = JsString(format.print(datetime.withZone(DateTimeZone.UTC)))
    def read(json: JsValue): DateTime = json match {
      case JsString(x) => format.parseDateTime(x)
      case x           => deserializationError("Expected DateTime as JsString, but got " + x)
    }
  }
  implicit val taskFormat = jsonFormat5(Task)
  implicit val userCreationFormat = jsonFormat3(UserCreation)
  implicit val userNamesFormat = jsonFormat1(UserNames)
} 
开发者ID:Max-Meldrum,项目名称:machine,代码行数:24,代码来源:JsonSupport.scala


示例11:

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

import salat._
import salat.json._
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.DateTimeZone

package object TypeHintContext {
  implicit val ctx = new Context {
      val name = "json-test-context"
      override val typeHintStrategy = StringTypeHintStrategy(
				when = TypeHintFrequency.Always,
        typeHint = "_t")
      override val jsonConfig = JSONConfig(
				dateStrategy = StringDateStrategy(
					dateFormatter = ISODateTimeFormat.dateTime.withZone(
						DateTimeZone.UTC)))
    }
} 
开发者ID:enpassant,项目名称:rapids,代码行数:20,代码来源:TypeHintContext.scala


示例12: DateHelper

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

import java.sql.{Timestamp,Date,Time}
import org.joda.time.{DateTime,LocalDate,LocalTime,DateTimeZone}
import org.joda.time.format._

object DateHelper {
  def dateTimeToSqlTimestamp: DateTime => Timestamp = { dt => new Timestamp(dt.getMillis) }
  def sqlTimestampToDateTime: Timestamp => DateTime = { ts => new DateTime(ts.getTime) }
  def localDateToSqlDate: LocalDate => Date = { ld => new Date(ld.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis) }
  def sqlDateToLocalDate: Date => LocalDate = { d  => new LocalDate(d.getTime) }
  def localTimeToSqlTime: LocalTime => Time = { lt => new Time(lt.toDateTimeToday.getMillis) }
  def sqlTimeToLocalTime: Time => LocalTime = { t  => new LocalTime(t, DateTimeZone.UTC) }
  
  def dateToString(date:java.util.Date, format:String = "yyyy-MM-dd HH:mm:ss"):String = {
    import java.text._
    val sdf = new SimpleDateFormat(format)
    sdf.format(date)
  }
  def stringToDate(datestr:String, format:String = "yyyy-MM-dd HH:mm:ss"):java.util.Date = {
    import java.text._
    val sdf = new SimpleDateFormat(format)
    sdf.parse(datestr)
  }
} 
开发者ID:bananapianist,项目名称:playfw_sample,代码行数:26,代码来源:DateHelper.scala


示例13: DummyDeviceHistory

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.test.tools.model

import java.util.UUID

import com.ubirch.avatar.model.rest.device.DeviceHistory
import com.ubirch.util.uuid.UUIDUtil

import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JsonAST.JValue
import org.json4s.native.JsonMethods._

import scala.collection.mutable.ListBuffer


object DummyDeviceHistory {

  def data(deviceId: String = UUIDUtil.uuidStr,
           messageId: UUID = UUIDUtil.uuid,
           deviceType: String = "lightsLamp",
           timestamp: DateTime = DateTime.now,
           deviceTags: Set[String] = Set("ubirch#0", "actor"),
           deviceMessage: JValue = parse("""{"foo": 23, "bar": 42}""")
          ): DeviceHistory = {

    DeviceHistory(
      messageId = messageId,
      deviceDataRawId = UUIDUtil.uuid,
      deviceId = deviceId,
      deviceName = s"$deviceType $deviceId",
      deviceType = deviceType,
      deviceTags = deviceTags,
      deviceMessage = deviceMessage,
      timestamp = timestamp
    )
  }

  def dataSeries(deviceId: String = UUIDUtil.uuidStr,
                 dType: String = "lightsLamp",
                 tags: Set[String] = Set("ubirch#0", "actor"),
                 message: JValue = parse("""{"foo": 23, "bar": 42}"""),
                 intervalMillis: Long = 1000 * 10, // 10s
                 timestampOffset: Long = -1000 * 60 * 60, // 1h
                 elementCount: Int = 5
                ): List[DeviceHistory] = {

    val deviceDataList: ListBuffer[DeviceHistory] = ListBuffer()
    val newestDateTime = DateTime.now(DateTimeZone.UTC).minus(timestampOffset)

    val range = 0 until elementCount
    for (i <- range) {
      val timestamp = newestDateTime.minus(i * intervalMillis)
      val deviceData = data(deviceId = deviceId, deviceType = dType, timestamp = timestamp, deviceTags = tags, deviceMessage = message)
      deviceDataList.+=:(deviceData)
    }

    deviceDataList.toList

  }

} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:61,代码来源:DummyDeviceHistory.scala


示例14: MsgPacker

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.core.msgpack

import java.io.ByteArrayInputStream

import com.typesafe.scalalogging.slf4j.StrictLogging
import org.joda.time.{DateTime, DateTimeZone}
import org.msgpack.ScalaMessagePack
import org.msgpack.`type`.ValueType

import scala.collection.mutable

object MsgPacker extends StrictLogging {

  def unpack(binData: Array[Byte]) = {

    val ids: mutable.ArrayBuffer[Long] = mutable.ArrayBuffer.empty
    val temps: mutable.Map[DateTime, Int] = mutable.HashMap.empty

    val unpacker = ScalaMessagePack.messagePack.createUnpacker(new ByteArrayInputStream(binData))
    val itr = unpacker.iterator()
    var done = false
    while (itr.hasNext && !done) {
      val v = itr.next()
      v.getType match {
        case ValueType.INTEGER =>
          val value = v.asIntegerValue.getLong
          ids.append(value)
        case ValueType.MAP =>
          val map = v.asMapValue()
          val keys = map.keySet()
          val kItr = keys.iterator()
          while (kItr.hasNext) {
            val key = kItr.next()
            val dt = new DateTime(key.asIntegerValue().longValue() * 1000, DateTimeZone.UTC)
            val temp = map.get(key)
            temps.update(key = dt, value = temp.asIntegerValue().getInt)
          }
          done = true
        case _ =>
      }
    }
    if (ids.size.equals(4)) {
      val did = ids.mkString("-")
      logger.info(s"deviceId: $did / t: $temps")
      (did, temps.toMap)
    }
    else
      throw new Exception("invalid data")
  }

} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:52,代码来源:MsgPacker.scala


示例15: DummyDeviceHistory

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

import java.util.UUID

import com.ubirch.avatar.model.rest.device.DeviceHistory
import com.ubirch.util.uuid.UUIDUtil

import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JsonAST.JValue
import org.json4s.native.JsonMethods._

import scala.collection.mutable.ListBuffer


object DummyDeviceHistory {

  def data(deviceId: String = UUIDUtil.uuidStr,
           messageId: UUID = UUIDUtil.uuid,
           deviceType: String = "lightsLamp",
           timestamp: DateTime = DateTime.now,
           deviceTags: Set[String] = Set("ubirch#0", "actor"),
           deviceMessage: JValue = parse("""{"foo": 23, "bar": 42}""")
          ): DeviceHistory = {

    DeviceHistory(
      messageId = messageId,
      deviceDataRawId = UUIDUtil.uuid,
      deviceId = deviceId,
      deviceName = s"$deviceType $deviceId",
      deviceType = deviceType,
      deviceTags = deviceTags,
      deviceMessage = deviceMessage,
      timestamp = timestamp
    )
  }

  def dataSeries(deviceId: String = UUIDUtil.uuidStr,
                 dType: String = "lightsLamp",
                 tags: Set[String] = Set("ubirch#0", "actor"),
                 message: JValue = parse("""{"foo": 23, "bar": 42}"""),
                 intervalMillis: Long = 1000 * 10, // 10s
                 timestampOffset: Long = -1000 * 60 * 60, // 1h
                 elementCount: Int = 5
                ): List[DeviceHistory] = {

    val deviceDataList: ListBuffer[DeviceHistory] = ListBuffer()
    val newestDateTime = DateTime.now(DateTimeZone.UTC).minus(timestampOffset)

    val range = 0 until elementCount
    for (i <- range) {
      val timestamp = newestDateTime.minus(i * intervalMillis)
      val deviceData = data(deviceId = deviceId, deviceType = dType, timestamp = timestamp, deviceTags = tags, deviceMessage = message)
      deviceDataList.+=:(deviceData)
    }

    deviceDataList.toList

  }

} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:61,代码来源:DummyDeviceHistory.scala


示例16: AvatarState

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.model.rest.device

import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JValue


case class AvatarState(deviceId: String,
                       inSync: Option[Boolean] = None,
                       desired: Option[JValue] = None,
                       reported: Option[JValue] = None,
                       delta: Option[JValue] = None,
                       // update on device
                       deviceLastUpdated: Option[DateTime] = Some(DateTime.now(DateTimeZone.UTC)),
                       // update on server side
                       avatarLastUpdated: Option[DateTime] = Some(DateTime.now(DateTimeZone.UTC))
                      ) 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:17,代码来源:AvatarState.scala


示例17: Device

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.model.db.device

import java.util.UUID

import com.ubirch.avatar.config.Config
import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JValue
import org.json4s.JsonAST.{JBool, JString}


case class Device(deviceId: String,
                  groups: Set[UUID] = Set.empty,
                  deviceTypeKey: String = "unknownDeviceType",
                  deviceName: String = "unnamedDevice",
                  hwDeviceId: String = "unknownHwDeviceId",
                  hashedHwDeviceId: String = "unknownHwDeviceId",
                  tags: Set[String] = Set(),
                  deviceConfig: Option[JValue] = None,
                  deviceProperties: Option[JValue] = None,
                  subQueues: Option[Set[String]] = None,
                  pubQueues: Option[Set[String]] = Some(Set(Config.awsSqsQueueTransformerOut)),
                  avatarLastUpdated: Option[DateTime] = None,
                  deviceLastUpdated: Option[DateTime] = None,
                  updated: Option[DateTime] = None,
                  created: DateTime = DateTime.now(DateTimeZone.UTC)
                 ) {

  override def equals(obj: scala.Any): Boolean = {
    obj match {
      case dev: Device =>
        if (
          dev.deviceId == this.deviceId
        )
          true
        else
          false
      case _ => false
    }
  }

  override def hashCode(): Int = this.deviceId.hashCode

  def checkProperty(propertyKey: String): Boolean = {
    if (deviceConfig.isDefined) {
      (deviceProperties.get.camelizeKeys \ propertyKey).equals(JString("true")) ||
        (deviceProperties.get.camelizeKeys \ propertyKey).equals(JBool(true))
    }
    else
      false
  }
} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:52,代码来源:Device.scala


示例18: Trends

//设置package包名称以及导入依赖的类
package se.qvantel.generator

import org.joda.time.{DateTime, DateTimeZone}
import se.qvantel.generator.model.product.{Product, Point}
import com.typesafe.scalalogging.LazyLogging
import se.qvantel.generator.utils.property.config.ApplicationConfig

object Trends extends ApplicationConfig with LazyLogging {

  
  def nextTrendEventSleep(product: Product, tsNs: Long) : Long = {
    // Get the hour as a double in the timestamp
    val ts = new DateTime(tsNs / 1000000, DateTimeZone.UTC)
    val hour = ts.millisOfDay().get().toDouble/60/60/1000
    // Find the previous and next trend points
    val prevNextPoints = getPrevNextPoints(product.points, hour)
    // Calculate sleep until next event
    val sleep = getSleepTimeFromPoints(prevNextPoints, tsNs, hour)
    sleep.toLong
  }

  def getFractionBetweenPoints(prevHour: Double, nextHour: Double, currentHour: Double): Double = {
    // Calculate the diff between the previous and next points and calculate a fraction of the current hour between the points
    val (hourDiffLow, hourDiffHigh) = {
      if (prevHour < nextHour) {
        (currentHour - prevHour, nextHour - prevHour)
      } else if (currentHour < prevHour) {
        (24 - prevHour + currentHour, 24 - prevHour + nextHour)
      } else {
        (currentHour - prevHour, 24 - prevHour + nextHour)
      }
    }

    hourDiffLow/hourDiffHigh
  }
} 
开发者ID:qvantel,项目名称:orcd-generator,代码行数:37,代码来源:Trends.scala


示例19: LastCdrChecker

//设置package包名称以及导入依赖的类
package se.qvantel.generator.utils

import com.typesafe.scalalogging.LazyLogging
import org.joda.time.{DateTime, DateTimeZone}
import se.qvantel.generator.CDRGenerator._

object LastCdrChecker extends LazyLogging {
  def getStartTime(): DateTime = {
    val backInTimeTs = DateTime.now(DateTimeZone.UTC).minusHours(backInTimeHours)
    // If sudden crash, look into the last inserted record and begin generating from that timestamp
    val rows = session.execute(
      s"SELECT created_at FROM $keyspace.$cdrTable " +
        "WHERE clustering_key=0 ORDER BY created_at DESC LIMIT 1")
      .all()

    // By default set startTs to backInTimeTs
    // If events exists in cassandra and last event is newer than backInTimeTs, start at lastEventTs
    // This is done in case for example the CDR Generator crashes or is shut down it will continue where it stopped
    val startTs = !rows.isEmpty match {
      case true => {
        val tsNs = rows.get(0).getLong("created_at")
        val lastEventTs = new DateTime(tsNs / 1000000, DateTimeZone.UTC)
        logger.info(s"BackInTimeTs: $backInTimeTs")
        logger.info(s"LastEventTs: $lastEventTs")
        lastEventTs.getMillis > backInTimeTs.getMillis match {
          case true => lastEventTs
          case false => backInTimeTs
        }
      }
      case false => backInTimeTs
    }
    startTs
  }
} 
开发者ID:qvantel,项目名称:orcd-generator,代码行数:35,代码来源:LastCdrChecker.scala


示例20: UserWebSocketActor

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

import actors.FeedbackAggregatorActor.{Feedback, StoreInfo, UnwatchFeedback, WatchFeedback}
import akka.actor._
import org.joda.time.{DateTime, DateTimeZone}
import play.api.libs.json.{JsValue, Json, Reads, Writes}

object UserWebSocketActor {
  def props(outActorRef: ActorRef, feedbackActor: ActorRef) = Props(new UserWebSocketActor(outActorRef, feedbackActor))
}

class UserWebSocketActor(outActorRef: ActorRef, feedbackActor: ActorRef) extends Actor {

  println("Making UserVoiceActor actor")

  // Subscribe to feedback
  feedbackActor ! WatchFeedback()

  def receive = {

    //Receive JSON from the client
    case msg: JsValue =>
      println(s"Got message: $msg")
      val surveyResponse = Feedback("1234", 9, "Pretty good", StoreInfo("1028AA", "99 Atlantic"), new DateTime(DateTimeZone.UTC))

    //Send feedback to the user when we receive it
    case [email protected](orderNumber, _, _, _, _) =>
      println(s"yo, feedback from order: $orderNumber")

      // TODO these belong in a companion object for SurveyResponse and StoreInfo
      implicit val yourJodaDateReads = Reads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ss'Z'")
      implicit val yourJodaDateWrites = Writes.jodaDateWrites("yyyy-MM-dd'T'HH:mm:ss'Z'")
      implicit val storeInfoFormat = Json.format[StoreInfo]
      implicit val surveyResponseFormat = Json.format[Feedback]

      outActorRef ! Json.toJson(feedback)
  }

  
  override def postStop() = {
    feedbackActor ! UnwatchFeedback()
    println("UserVoiceActor actor stopped")
  }
} 
开发者ID:ChrisCooper,项目名称:customer-feedback-screen,代码行数:45,代码来源:UserWebSocketActor.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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