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

Scala TimeZone类代码示例

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

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



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

示例1: Total

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

import akka.Done
import akka.actor.Actor
import sample.stream_actor.Total.Increment
import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

object Total {
  case class Increment(value: Long, avg: Double, id: String)
}

class Total extends Actor {
  var total: Long = 0

  override def receive: Receive = {
    case Increment(value, avg, id) =>
      println(s"Recieved $value new measurements from id: $id -  Avg wind speed is: $avg")
      total = total + value

      val date = new Date()
      val df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      df.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"))

      println(s"${df.format(date) } - Current total of all measurements: $total")
      sender ! Done
  }
} 
开发者ID:pbernet,项目名称:akka_streams_tutorial,代码行数:29,代码来源:Total.scala


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


示例3: TestListBuckets

//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4

import java.text.SimpleDateFormat
import java.util.TimeZone

import com.squareup.okhttp.mockwebserver.{MockResponse, MockWebServer}
import edu.goldlok.minio_scala.mio.MioClient
import okio.Buffer
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.Await


class TestListBuckets extends FlatSpec with Matchers with MockitoSugar {
  import edu.goldlok.minio_scala.s3v4.TestElem._
  val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
  dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
  private val bucketCreateTime = Map("bucket" -> dateFormat.parse("2015-05-05T20:35:51.410Z"),
    "foo" -> dateFormat.parse("2015-05-05T20:35:47.170Z"))
  private val entity = "<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\">" +
    "<Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><Buckets><Bucket><Name>bucket</Name>" +
    "<CreationDate>2015-05-05T20:35:51.410Z</CreationDate></Bucket><Bucket><Name>foo</Name>" +
    "<CreationDate>2015-05-05T20:35:47.170Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>"


  private def obtListBucketServer(): MockWebServer = {
    val server = new MockWebServer()
    val response = new MockResponse()

    response.addHeader("Date", MON_29_JUN_2015_22_01_10_GMT)
    response.addHeader(CONTENT_LENGTH, "351")
    response.addHeader(CONTENT_TYPE, "application/xml")
    response.setBody(new Buffer().writeUtf8(entity))
    response.setResponseCode(200)

    server.enqueue(response)
    server.start()
    server
  }

  private def testListBucket() = {
    val server = obtListBucketServer()
    val response = MioClient(server.getHostName, server.getPort, keys).listBuckets()
    val listResult = Await.result(response, timeout)
    listResult.isSuccess should be (true)
    listResult.buckets foreach { elem =>
      bucketCreateTime.contains(elem.name) should be (true)
      val date = bucketCreateTime.get(elem.name)
      date.get should be (elem.creationDate)
    }
  }

  "list buckets " should "return" in {
    testListBucket()
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:58,代码来源:TestListBuckets.scala


示例4: Converter

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

import java.util.TimeZone

import akka.util.ByteString

object Converter {
  def bytes2hex(bytes: Seq[Byte], sep: Option[String] = Some(" ")): String = {
    if (!bytes.isEmpty) {
      val str1 = sep match {
        case None => bytes.take(bytes.length - 1).map("%02x".format(_)).mkString
        case _ => bytes.take(bytes.length - 1).map("%02x".format(_) + sep.get).mkString
      }
      val str2 = bytes.takeRight(1).map("%02x".format(_)).mkString
      str1 + str2
    } else ""
  }
  def bytes2hexLen(bytes: Seq[Byte], len:Int=16, sep: Option[String] = Some(" ")): String = {
    (if (bytes.length>len) "("+len+"/"+bytes.length+")" else "("+bytes.length+")") +
      "["+ bytes2hex(bytes.take(len), sep) +
      (if (bytes.length>len) "..." else "") +
      "]"
  }
  def bytes2StringUTF(seq:Seq[Byte]):String = {ByteString(seq.toArray).decodeString("UTF-8")}
  def stringUTF2Bytes(value:String):Seq[Byte] = {ByteString.fromString(value, "UTF-8")}
  def stringASCII2Bytes(value:String):Seq[Byte] = ByteString.fromString(value, "ASCII")
  def string2Time(value:String):Int = {
    val format = value.substring(value.indexOf("[") + 1, value.indexOf("]"))
    val datetime = value.substring(value.indexOf("]")+1)
    val dateformat = new java.text.SimpleDateFormat(format)
    dateformat.setTimeZone(TimeZone.getTimeZone("GMT"))
    val res = dateformat.parse(datetime)
    (res.getTime/1000 + 2208988800L).toInt
  }
} 
开发者ID:dbuhryk,项目名称:DiameterCoder,代码行数:36,代码来源:Converter.scala


示例5: Model

//设置package包名称以及导入依赖的类
package org.scalawag.jibe.report

import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

import spray.json._

object Model extends DefaultJsonProtocol {

  case class Run(version: Int, startTime: Date)
  //    extends Ordered[Run] {
  //    override def compare(that: Run) = this.startTime.getTime.compare(that.startTime.getTime)
  //  }

  val ISO8601DateFormat = {
    val f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
    f.setTimeZone(TimeZone.getTimeZone("UTC"))
    f
  }

  implicit object dateFormat extends RootJsonFormat[Date] {
    def write(obj: Date): JsValue = JsString(ISO8601DateFormat.format(obj.getTime))
    def read(json: JsValue): Date = json match {
      case JsString(str) => ISO8601DateFormat.parse(str)
      case x => throw new RuntimeException(s"expecting a string in ISO8601 format: $x")
    }
  }

  implicit val runFormat = jsonFormat2(Run.apply)
} 
开发者ID:scalawag,项目名称:jibe,代码行数:31,代码来源:Model.scala


示例6: AlarmUtil

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.util

import java.util.{Calendar, TimeZone}

import android.app.{AlarmManager, PendingIntent}
import android.content.{Context, Intent}
import com.android.perrier1034.post_it_note.App
import com.android.perrier1034.post_it_note.receiver.AlarmBroadcastReceiver

object AlarmUtil {

  val alarmIntentDataKey = "alarmIntentDataKey "
  def set(id: Long, year: Int, month: Int, date: Int) = {
    val cal = Calendar.getInstance
    cal.setTimeInMillis(System.currentTimeMillis)
    cal.setTimeZone(TimeZone.getDefault)
    cal.set(Calendar.YEAR, year)
    cal.set(Calendar.MONTH, month)
    cal.set(Calendar.DAY_OF_MONTH, date)
    cal.set(Calendar.HOUR_OF_DAY, 0)
    cal.set(Calendar.MINUTE, 0)
    val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
    intent.putExtra(alarmIntentDataKey, id)
    intent.setAction(AlarmBroadcastReceiver.KEY_INTENT_ALARM_USUAL)
    val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis, pendingIntent)
  }

  def clear(noteId: Long) = {
    val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
    intent.putExtra(alarmIntentDataKey, noteId)
    val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
    alarmManager.cancel(pendingIntent)
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:38,代码来源:AlarmUtil.scala


示例7: MariaDbConnectionManager

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

import java.sql.Connection
import java.util.TimeZone

import com.gs.fw.common.mithra.bulkloader.BulkLoaderException
import com.gs.fw.common.mithra.connectionmanager.{SourcelessConnectionManager, XAConnectionManager}
import com.gs.fw.common.mithra.databasetype.{DatabaseType, MariaDatabaseType}

class MariaDbConnectionManager private() extends SourcelessConnectionManager {
  private val xaConnectionManager: XAConnectionManager = new XAConnectionManager()
  private val MAX_POOL_SIZE_KEY = "maxPoolSize"
  private val DEFAULT_MAX_WAIT = 500
  private val DEFAULT_POOL_SIZE = 10
  private val TOKYO_TIMEZONE = TimeZone.getTimeZone("Asia/Tokyo")
  private val driverClassname = "org.mariadb.jdbc.Driver"
  private val connectionString = "jdbc:mariadb://127.0.0.1:3306/"
  private val schemaName = "testdb"
  private val userName = "root"
  private val password = "mariadb"

  createConnectionManager()

  private def createConnectionManager(): XAConnectionManager = {
    xaConnectionManager.setDriverClassName(driverClassname)
    xaConnectionManager.setMaxWait(DEFAULT_MAX_WAIT)
    xaConnectionManager.setJdbcConnectionString(connectionString + schemaName)
    xaConnectionManager.setJdbcUser(userName)
    xaConnectionManager.setJdbcPassword(password)
    xaConnectionManager.setPoolName("myproj connection pool")
    xaConnectionManager.setInitialSize(1)
    xaConnectionManager.setPoolSize(DEFAULT_POOL_SIZE)
    xaConnectionManager.initialisePool()
    xaConnectionManager
  }

  def getConnection: Connection = xaConnectionManager.getConnection

  def getDatabaseType: DatabaseType = MariaDatabaseType.getInstance

  def getDatabaseTimeZone = TOKYO_TIMEZONE

  @throws[BulkLoaderException]
  def createBulkLoader = throw new RuntimeException("BulkLoader is not supported")

  def getDatabaseIdentifier: String = schemaName

}

object MariaDbConnectionManager {
  private val _instance = new MariaDbConnectionManager()

  def getInstance(): MariaDbConnectionManager = _instance
} 
开发者ID:itohiro73,项目名称:reladomo-sbt,代码行数:55,代码来源:MariaDbConnectionManager.scala


示例8: UserAvatars

//设置package包名称以及导入依赖的类
package ru.pavkin.todoist.api.core.model

import java.util.{Date, TimeZone}

import ru.pavkin.todoist.api.core.tags
import [email protected]@

case class UserAvatars(small: Option[String],
                       medium: Option[String],
                       big: Option[String],
                       s640: Option[String])

case class User(id: Int @@ tags.UserId,
                email: String,
                fullName: String,
                inboxProject: Int @@ tags.ProjectId,
                timezone: TimeZone,
                startPageQuery: String,
                weekStartDay: DayOfWeek,
                postponeTo: DayOfWeek,
                timeFormat: TimeFormat,
                dateFormat: DateFormat,
                projectsSortOrder: ProjectsSortOrder,
                hasPushReminders: Boolean,
                defaultReminder: Option[ReminderService],
                autoReminder: Option[Int],
                mobileNumber: Option[String],
                mobileHost: Option[String],
                totalCompletedTasksCount: Int,
                todayCompletedTasksCount: Int,
                karma: Double,
                premiumUntil: Option[Date],
                isBusinessAccountAdmin: Boolean,
                businessAccountId: Option[Int],
                isBeta: Boolean,
                isDummy: Boolean,
                dateJoined: Date,
                theme: Theme,
                avatars: UserAvatars) 
开发者ID:vpavkin,项目名称:scalist,代码行数:40,代码来源:User.scala


示例9: TodoistDateSpec

//设置package包名称以及导入依赖的类
package ru.pavkin.todoist.api.core.model

import java.text.SimpleDateFormat
import java.util.{TimeZone, Calendar, Date}

import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}

class TodoistDateSpec extends FunSuite with Matchers with GeneratorDrivenPropertyChecks {

  private val dateFormatter = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss Z")
  dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))

  test("TodoistDate.format holds the format") {
    forAll(arbitrary[Date]) { (d: Date) =>
      TodoistDate.format(d) shouldEqual dateFormatter.format(d)
    }
  }

  test("TodoistDate.parse parses it's own results") {
    forAll(Gen.choose(new Date().getTime - 1000000L, new Date().getTime + 1000000L)) { (l: Long) =>
      TodoistDate.parse(TodoistDate.format(new Date(l))).map(_.getTime()) shouldEqual
        Some((l / 1000) * 1000)
    }
  }

  test("TodoistDate.parse parses some realworld dates") {
    TodoistDate.parse("Fri 26 Feb 2016 10:39:51 +0000").map(_.getTime) shouldEqual Some(1456483191000L)
    TodoistDate.format(new Date(1456483191000L)) shouldBe "Fri 26 Feb 2016 10:39:51 +0000"
  }
} 
开发者ID:vpavkin,项目名称:scalist,代码行数:34,代码来源:TodoistDateSpec.scala


示例10: SimpleJsonSerializer

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

import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

object SimpleJsonSerializer {

  
  def apply(fields: Seq[(String, Any)]) = {
    "{" +
      fields.map {
        case (key: String, value: Number) =>
          "\"" + key + "\":" + value
        case (key: String, value: Date) =>
          "\"" + key + "\":" + "\"" + formatDateIso8601(value) + "\""
        case (key: String, value: String) =>
          "\"" + key + "\":" + "\"" + value + "\""
        case (key: String, value: Any) =>
          "\"" + key + "\":" + "\"" + value.toString + "\""
      }.mkString(",") +
      "}"
  }

  private def formatDateIso8601(date: Date): String = {
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
    dateFormat.format(date)
  }

} 
开发者ID:astrofed,项目名称:akka-slick-auth-token-microservices,代码行数:31,代码来源:SimpleJsonSerializer.scala


示例11: BingAnalyzer

//设置package包名称以及导入依赖的类
package com.microsoft.partnercatalyst.fortis.spark.analyzer

import java.text.SimpleDateFormat
import java.util.TimeZone
import java.net.URL

import com.github.catalystcode.fortis.spark.streaming.bing.dto.BingPost
import com.microsoft.partnercatalyst.fortis.spark.transforms.image.ImageAnalyzer

@SerialVersionUID(100L)
class BingAnalyzer extends Analyzer[BingPost] with Serializable
  with AnalysisDefaults.EnableAll[BingPost] {

  private val DefaultFormat = "yyyy-MM-dd'T'HH:mm:ss"
  private val DefaultTimezone = "UTC"

  override def toSchema(item: BingPost, locationFetcher: LocationFetcher, imageAnalyzer: ImageAnalyzer): ExtendedDetails[BingPost] = {
    ExtendedDetails(
      eventid = item.url,
      eventtime = convertDatetimeStringToEpochLong(item.dateLastCrawled),
      externalsourceid = new URL(item.url).getHost,
      body = item.snippet,
      title = item.name,
      pipelinekey = "Bing",
      sourceurl = item.url,
      original = item
    )
  }

  private def convertDatetimeStringToEpochLong(dateStr: String, format: Option[String] = None, timezone: Option[String] = None): Long ={
      val sdf = new SimpleDateFormat(format.getOrElse(DefaultFormat))
      sdf.setTimeZone(TimeZone.getTimeZone(timezone.getOrElse(DefaultTimezone)))

      sdf.parse(dateStr).getTime
  }
} 
开发者ID:CatalystCode,项目名称:project-fortis-spark,代码行数:37,代码来源:BingAnalyzer.scala


示例12: instantGen

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

import java.time.{Duration, Instant, ZonedDateTime}
import java.util.TimeZone

import org.scalacheck.Gen

trait Gens {
  def instantGen: Gen[Instant] = Gen.chooseNum(0L, Long.MaxValue).map(Instant.ofEpochMilli)

  def zonedDateTimeGen: Gen[ZonedDateTime] = for {
    instant <- instantGen
    zoneId <- Gen.oneOf(TimeZone.getAvailableIDs.map(TimeZone.getTimeZone(_).toZoneId))
  } yield ZonedDateTime.ofInstant(instant, zoneId)

  def durationGen: Gen[Duration] = for {
    start <- instantGen
    end <- instantGen
  } yield Duration.between(start, end)
} 
开发者ID:opt-tech,项目名称:chronoscala,代码行数:21,代码来源:Gens.scala


示例13: WorklogFilter

//设置package包名称以及导入依赖的类
package com.github.macpersia.planty.worklogs

import java.time.LocalDate
import java.util.TimeZone

package object model {

  class WorklogFilter( author_ : Option[String],
                       fromDate_ : LocalDate,
                       toDate_ : LocalDate,
                       timeZone_ : TimeZone ) {
    val author = author_
    val fromDate = fromDate_
    val toDate = toDate_
    val timeZone = timeZone_
  }

  case class WorklogEntry( date: LocalDate,
                           description: String,
                           duration: Double )
} 
开发者ID:macpersia,项目名称:planty-worklogs-common,代码行数:22,代码来源:model.scala


示例14: DateFormatSpec

//设置package包名称以及导入依赖的类
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.{Date, TimeZone}

import com.typesafe.scalalogging.LazyLogging
import org.scalatest.{Matchers, WordSpecLike}

class DateFormatSpec extends WordSpecLike with Matchers with LazyLogging {
//  2011-12-03T10:15:30Z
  "Instant" should {

    val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    format.setTimeZone(TimeZone.getTimeZone("UTC"))

    "format date 1" in {
      val formattedDate = Instant.now().toString
      formattedDate shouldBe format.format(new Date())
    }

    "format date 2" in {
      val date = new Date()
      val formattedDate = Instant.ofEpochMilli(date.getTime).toString
      formattedDate shouldBe format.format(date)
    }

    "format date 3" in {
      for (timestamp <- 0 to 20){
        val date = new Date(System.currentTimeMillis() + timestamp)
        val formattedDate = Instant.ofEpochMilli(date.getTime).toString
        formattedDate shouldBe format.format(date)
      }

    }


  }
} 
开发者ID:otrebski,项目名称:sbt-flaky-demo,代码行数:38,代码来源:DateFormatSpec.scala


示例15: Helpers

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

import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.{GregorianCalendar, TimeZone, Locale}
import java.util.regex.Pattern

object Helpers {
  private val XML_DATE_FORMAT: String = "yyyy-MM-dd'T'HH:mm:ss"

  def getXmlTimestamp: String = {
    val dateFormatter = new SimpleDateFormat(XML_DATE_FORMAT, Locale.US)
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"))
    val time = new GregorianCalendar()
    dateFormatter.format(time.getTime)
  }

  def makePattern(s: String): Pattern =
    Pattern.compile("^\\Q" + s.replace("?", "\\E.\\Q").replace("*", "\\E.*\\Q") + "\\E$")

  def urlEncode(s: String) = URLEncoder.encode(s, "UTF-8")

  def unixTimestamp: Long = System.currentTimeMillis / 1000
} 
开发者ID:madprogrammer,项目名称:scxmppd,代码行数:25,代码来源:Helpers.scala


示例16: Conversions

//设置package包名称以及导入依赖的类
package com.wix.pay.paybox.model

import java.math.{BigDecimal => JBigDecimal}
import java.util.{Calendar, Currency, TimeZone}

object Conversions {
  def toPayboxAmount(amount: Double): String = {
    val amountInt = JBigDecimal.valueOf(amount).movePointRight(2).intValueExact()
    f"$amountInt%010d"
  }

  def toPayboxCurrency(currency: String): String = {
    Currency.getInstance(currency).getNumericCode.toString
  }

  def toPayboxYearMonth(year: Int, month: Int): String = {
    f"$month%02d${year % 100}%02d"
  }

  def toPayboxDateTime(timestamp: Long): String = {
    val cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"))
    cal.setTimeInMillis(timestamp)

    f"${cal.get(Calendar.DAY_OF_MONTH)}%02d${cal.get(Calendar.MONTH) - Calendar.JANUARY + 1}%02d${cal.get(Calendar.YEAR)}%04d${cal.get(Calendar.HOUR_OF_DAY)}%02d${cal.get(Calendar.MINUTE)}%02d${cal.get(Calendar.SECOND)}%02d"
  }
} 
开发者ID:wix,项目名称:libpay-paybox,代码行数:27,代码来源:Conversions.scala


示例17: HttpDate

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

import java.util.{Date, Locale, TimeZone}
import java.text.SimpleDateFormat
import scala.util.Try


final class HttpDate(val date: Date) extends AnyVal

object HttpDate {
  private val dateFormat: SimpleDateFormat = {
    val df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"))
    df
  }

  def parse(s: String): Option[HttpDate] =
    Try(dateFormat.parse(s)).toOption.map(new HttpDate(_))

  def format(d: HttpDate): String =
    dateFormat.format(d.date)
} 
开发者ID:eddsteel,项目名称:feed-filter,代码行数:24,代码来源:HttpDate.scala


示例18: ResourceAction

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

import java.text.SimpleDateFormat
import java.util.{Calendar, Date, TimeZone}

import play.api.mvc._

import scala.concurrent.duration._

trait ResourceActions {
  def ResourceAction(fingerprint: String, validFor: Duration = 365.days): Action[AnyContent]
}

trait ResourceActionsImpl extends ResourceActions { self: Resources with BaseController =>
  override def ResourceAction(fingerprint: String, validFor: Duration = 365.days) = EtagAction { _ =>
    resources.contentFor(Fingerprint(fingerprint)).map { content =>
      Ok(content.body).as(content.mimeType.name).withHeaders(CacheHeaders(fingerprint, validFor): _*)
    }.getOrElse {
      BadRequest
    }
  }

  def EtagAction(f: Request[AnyContent] => Result) = Action { request =>
    request.headers.get(IF_NONE_MATCH).map { etag =>
      if (resources.contains(Fingerprint(etag.replaceAll(""""""", "")))) NotModified else f(request)
    }.getOrElse {
      f(request)
    }
  }

  def CacheHeaders(fingerprint: String, validFor: Duration = 365.days) = {
    val format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz")
    format.setTimeZone(TimeZone.getTimeZone("GMT"))

    val now = new Date()
    val futureDate = Calendar.getInstance()
    futureDate.add(Calendar.DATE, validFor.toDays.toInt)

    val diff = (futureDate.getTimeInMillis - now.getTime) / 1000

    Seq(
      DATE -> format.format(now),
      LAST_MODIFIED -> format.format(now),
      EXPIRES -> format.format(futureDate.getTime),
      ETAG -> s""""$fingerprint"""",
      CACHE_CONTROL -> s"public, max-age: ${diff.toString}")
  }

} 
开发者ID:splink,项目名称:pagelets,代码行数:50,代码来源:ResourceActions.scala


示例19: Utils

//设置package包名称以及导入依赖的类
package br.gov.es.prodest.spark

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.TimeZone


object Utils {
  val fOptString = (value : Any) =>  value match {
    case null => ""
    case s:String => value.toString.trim.toUpperCase
  }

  val fDateString = (value: Any, timezone: String) => value match {
    case null => null
    case s:Timestamp => {
      val dataf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
      dataf.setTimeZone(TimeZone.getTimeZone(timezone))
      dataf.format(value)
    }
  }

} 
开发者ID:prodest,项目名称:spark-jobs,代码行数:24,代码来源:Utils.scala


示例20: DiscoveryGuardian

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

import java.time.LocalDateTime
import java.util.TimeZone

import akka.actor.{Actor, ActorLogging, Props, SupervisorStrategy}

import scala.concurrent.duration._

object DiscoveryGuardian {
  def props(env: String, httpPort: Int, hostName: String) =
    Props(new DiscoveryGuardian(env, httpPort, hostName))
      .withDispatcher(HttpServer.HttpDispatcher)
}

class DiscoveryGuardian(env: String, httpPort: Int, hostName: String) extends Actor with ActorLogging {
  override val supervisorStrategy = SupervisorStrategy.stoppingStrategy

  val system = context.system
  val config = context.system.settings.config
  val timeout = FiniteDuration(config.getDuration("constructr.join-timeout").toNanos, NANOSECONDS)
  system.scheduler.scheduleOnce(timeout)(self ! 'Discovered)(system.dispatcher)

  override def receive: Receive = {
    case 'Discovered =>
      context.system.actorOf(HttpServer.props(httpPort, hostName,
        config.getString("akka.http.ssl.keypass"), config.getString("akka.http.ssl.storepass")), "http-server")

      println(Console.GREEN +
        """
              ___   ___   ___  __   __  ___   ___
             / __| | __| | _ \ \ \ / / | __| | _ \
             \__ \ | _|  |   /  \ V /  | _|  |   /
             |___/ |___| |_|_\   \_/   |___| |_|_\

        """ + Console.RESET)

      val tz = TimeZone.getDefault.getID
      val greeting = new StringBuilder()
        .append('\n')
        .append("=================================================================================================")
        .append('\n')
        .append(s"? ? ?  Environment: ${env} TimeZone: $tz Started at ${LocalDateTime.now}  ? ? ?")
        .append('\n')
        .append(s"? ? ?  ConstructR service-discovery: ${config.getString("constructr.coordination.class-name")} on ${config.getString("constructr.coordination.host")}  ? ? ?")
        .append('\n')
        .append(s"? ? ?  Akka cluster: ${config.getInt("akka.remote.netty.tcp.port")}  ? ? ?")
        .append('\n')
        .append(s"? ? ?  Akka seeds: ${config.getStringList("akka.cluster.seed-nodes")}  ? ? ?")
        .append('\n')
        .append(s"? ? ?  Cassandra domain points: ${config.getStringList("cassandra-journal.contact-points")}  ? ? ?")
        .append('\n')
        .append(s"? ? ?  Server online at https://${config.getString("akka.http.interface")}:${httpPort}   ? ? ?")
        .append('\n')
        .append("=================================================================================================")
      system.log.info(greeting.toString)
  }
} 
开发者ID:haghard,项目名称:linguistic,代码行数:59,代码来源:DiscoveryGuardian.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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