本文整理汇总了Scala中java.util.Locale类的典型用法代码示例。如果您正苦于以下问题:Scala Locale类的具体用法?Scala Locale怎么用?Scala Locale使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Locale类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Hello
//设置package包名称以及导入依赖的类
package com.example
import java.util.Locale
import com.cronutils.descriptor.CronDescriptor
import com.cronutils.model.CronType
import com.cronutils.model.definition.CronDefinitionBuilder
import com.cronutils.parser.CronParser
import org.joda.time.DateTime
object Hello {
def main(args: Array[String]): Unit = {
val cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
val parser = new CronParser(cronDefinition)
val now = DateTime.now()
val descriptor = CronDescriptor.instance(Locale.UK)
// val executionTime = ExecutionTime.forCron(parser.parse("* 49 * * * ? 2016"))
println(descriptor.describe(parser.parse("* * * * *")))
}
}
示例2: StoryQueryObject
//设置package包名称以及导入依赖的类
package io.soheila.cms.vos
import java.util.Locale
import io.soheila.cms.entities.UserReference
import io.soheila.cms.types.StoryType.StoryType
import io.soheila.commons.entities.Attribute
import io.soheila.commons.geospatials.Coordinate
case class StoryQueryObject(
title: Option[String],
storyType: StoryType,
tags: Option[Set[String]] = None,
authors: Option[Seq[UserReference]],
attributes: Option[Seq[Attribute]] = None,
text: Option[String] = None,
locations: Option[Seq[Coordinate]],
language: String = Locale.getDefault.getLanguage,
published: Option[Boolean] = None,
archived: Option[Boolean] = None
)
示例3: LocalDateTimeCoercionViolation
//设置package包名称以及导入依赖的类
package io.soheila.cms.api
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import sangria.ast.StringValue
import sangria.schema.ScalarType
import sangria.validation.ValueCoercionViolation
import scala.util.{ Failure, Success, Try }
package object graphql {
case object LocalDateTimeCoercionViolation extends ValueCoercionViolation("Date value expected")
case object LocaleCoercionViolation extends ValueCoercionViolation("Locale value expected")
private[graphql] def parseLocalDateTime(s: String) = Try(LocalDateTime.parse(s)) match {
case Success(date) => Right(date)
case Failure(_) => Left(LocalDateTimeCoercionViolation)
}
private[graphql] def parseLocale(s: String) = Try(Locale.forLanguageTag(s)) match {
case Success(locale) => Right(locale)
case Failure(_) => Left(LocaleCoercionViolation)
}
val LocalDateTimeType = ScalarType[LocalDateTime](
"LocalDateTime",
coerceOutput = (value, caps) => value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
coerceUserInput = {
case s: String => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
}
)
val LocaleType = ScalarType[Locale](
"Locale",
coerceOutput = (value, caps) => value.toLanguageTag,
coerceUserInput = {
case s: String => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
}
)
}
示例4: Family
//设置package包名称以及导入依赖的类
package teksol.mybank.domain.models
import java.util.{Locale, UUID}
import teksol.domain.FamilyId
import teksol.infrastructure.{EventBus, ToJson}
import teksol.mybank.domain.events.InterestRateChanged
import teksol.mybank.infrastructure.MyBankRepository
case class Family(familyId: FamilyId,
locale: Locale,
repository: MyBankRepository,
eventBus: EventBus) extends ToJson {
import teksol.infrastructure.Helpers._
def accounts: Set[Account] = repository.listAccounts(familyId)
def changeYearlyInterestRate(yearlyInterestRate: InterestRate): Unit = {
repository.changeYearlyInterestRate(familyId, yearlyInterestRate)
eventBus.publish(InterestRateChanged(familyId, yearlyInterestRate))
}
def createAccount(name: AccountName): Account = {
val account = Account(familyId, AccountId(UUID.randomUUID()), locale, name, Amount.ZERO, Amount.ZERO, repository, eventBus)
repository.saveAccount(account)
account
}
override def toJson: String = s"""{"family_id":${familyId.toJson},"locale":${locale.toJson}}"""
}
示例5: AccountWithInterest
//设置package包名称以及导入依赖的类
package teksol.mybank.domain.models
import java.util.Locale
import teksol.domain.FamilyId
import teksol.infrastructure.EventBus
import teksol.mybank.infrastructure.MyBankRepository
case class AccountWithInterest(familyId: FamilyId,
accountId: AccountId,
locale: Locale,
name: AccountName,
salary: Amount,
balance: Amount,
yearlyInterestRate: InterestRate,
repository: MyBankRepository,
eventBus: EventBus) {
def interests: Amount = {
val base = balance * yearlyInterestRate / 100 / 365
if (balance.isNegative) {
if (base > Amount.NEG_PENNY) {
Amount.NEG_PENNY
} else {
base.ceilPennies
}
} else if (balance.isPositive) {
if (base < Amount.PENNY) {
Amount.PENNY
} else {
base.ceilPennies
}
} else {
Amount.ZERO
}
}
}
示例6: translate
//设置package包名称以及导入依赖的类
package teksol.infrastructure
import java.util.Locale
import org.springframework.util.Assert
import teksol.mybank.domain.models.{Amount, InterestRate}
trait I18n {
def translate(locale: Locale, key: String, default: Option[String] = None, params: Map[String, String]): Option[String]
def amountWithDelimiter(locale: Locale, amount: Amount): String
def numberToPercentage(locale: Locale, interestRate: InterestRate): String
}
class InMemoryI18n(private[this] val dictionary: Map[Locale, Map[String, String]]) extends I18n {
override def translate(locale: Locale, key: String, default: Option[String] = None, params: Map[String, String] = Map.empty): Option[String] = {
Assert.notNull(locale, "locale")
Assert.notNull(key, "key")
dictionary.get(locale) match {
case None => default
case Some(translations) =>
translations.get(key) match {
case None => default
case Some(value) =>
val result = params.foldLeft(value) {
case (memo, (param, replacement)) =>
memo.replaceAll(s"""%[{]$param[}]""", replacement)
}
Some(result)
}
}
}
override def numberToPercentage(locale: Locale, interestRate: InterestRate): String = {
Assert.notNull(locale, "locale")
Assert.notNull(interestRate, "interestRate")
"%,.2f %%".formatLocal(locale, interestRate.value)
}
override def amountWithDelimiter(locale: Locale, amount: Amount): String = {
Assert.notNull(locale, "locale")
Assert.notNull(amount, "value")
"%,.2f".formatLocal(locale, amount.value.bigDecimal)
}
}
示例7: dataSource
//设置package包名称以及导入依赖的类
package teksol
import java.util.Locale
import javax.sql.DataSource
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.support.TransactionTemplate
import teksol.infrastructure.{EventBus, InMemoryI18n}
import teksol.mybank.domain.services.MyBankAppService
import teksol.mybank.infrastructure.postgres.PostgresMyBankRepository
import teksol.postgres.{PostgresEventBus, PostgresFamilyApp}
trait Config {
def dataSource: DataSource
lazy val jdbcTemplate: JdbcTemplate = new JdbcTemplate(dataSource)
lazy val transactionManager: PlatformTransactionManager = new DataSourceTransactionManager(dataSource)
lazy val transactionTemplate: TransactionTemplate = new TransactionTemplate(transactionManager)
lazy val eventBus: EventBus = new PostgresEventBus(jdbcTemplate)
lazy val app = new PostgresFamilyApp(jdbcTemplate, eventBus)
lazy val myBankRepository = new PostgresMyBankRepository(jdbcTemplate, eventBus)
lazy val myBankService = {
val service = new MyBankAppService(myBankRepository, eventBus)
eventBus.register(service)
service
}
val en_US = Locale.US
val fr_CA = Locale.CANADA_FRENCH
val fr_FR = Locale.FRANCE
lazy val i18n = new InMemoryI18n(Map(
en_US -> Map(
"salary.none" -> "No completed chores this period",
"salary.positive" -> "%{numUnitsCompleted} completed this week",
"salary.negative" -> "%{numUnitsCompleted} completed this week",
"interests.none" -> "No interests for period",
"interests.negative" -> "Negative interests on $ %{balance} balance, at a rate of %{rate}",
"interests.positive" -> "Interests on $ %{balance} balance, at a rate of %{rate}"),
fr_CA -> Map(
"salary.none" -> "Aucune tâche ménagères complétées cette semaine",
"salary.positive" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
"salary.negative" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
"interests.none" -> "Aucun intérêts pour la période",
"interests.negative" -> "Intérêts négatifs calculés sur un solde de %{balance} $ et un taux de %{rate}",
"interests.positive" -> "Intérêts calculés sur un solde de %{balance} $ et un taux de %{rate}"),
fr_FR -> Map(
"salary.none" -> "Aucune tâche ménagères complétées cette semaine",
"salary.positive" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
"salary.negative" -> "%{numUnitsCompleted} tâches ménagères complétées cette semaine",
"interests.none" -> "Aucun intérêts pour la période",
"interests.negative" -> "Intérêts négatifs calculés sur un solde de %{balance} $ et un taux de %{rate}",
"interests.positive" -> "Intérêts calculés sur un solde de %{balance} $ et un taux de %{rate}")))
}
示例8: LocaleCountrySerializer
//设置package包名称以及导入依赖的类
package com.wix.pay.stripe
import java.util.Locale
import org.json4s.JsonAST.JString
import org.json4s.reflect.TypeInfo
import org.json4s.{Formats, JsonDSL, MappingException, Serializer, _}
class LocaleCountrySerializer extends Serializer[Locale] {
private val LocaleClass = classOf[Locale]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Locale] = {
case (TypeInfo(LocaleClass, _), json) => json match {
case JString(country) =>
new Locale("", country)
case x => throw new MappingException("Can't convert " + x + " to LocaleClass")
}
}
def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
case x: Locale =>
import JsonDSL._
x.getCountry
}
}
示例9: MessagesMap
//设置package包名称以及导入依赖的类
package s_mach.i18n.impl
import java.util.Locale
import s_mach.i18n.messages.{MessageFormat, Messages}
case class MessagesMap(
locale: Locale,
formats: Map[Symbol,MessageFormat]
) extends Messages {
def keys = formats.keys
def contains(key: Symbol) = formats.contains(key)
def get(key: Symbol) = formats.get(key)
def apply(key: Symbol) = formats(key)
def applyOrElse(key: Symbol, default: Symbol => MessageFormat): MessageFormat =
formats.applyOrElse(key,default)
override def toString = s"Messages(keys.size=${keys.size})"
}
示例10: apply
//设置package包名称以及导入依赖的类
package s_mach.i18n.messages
import java.util.Locale
import s_mach.i18n.impl.DefaultUTF8Messages
def apply(
locale: Locale,
fileBaseDir: String = "conf",
fileBaseName: String = "messages",
fileExt: String = "txt"
) : Messages = DefaultUTF8Messages(
locale = locale,
fileBaseDir = fileBaseDir,
fileBaseName = fileBaseName,
fileExt = fileExt
)
}
示例11: MessageNTestCodeGen
//设置package包名称以及导入依赖的类
package s_mach.i18n.codegen
import Header.header
object MessageNTestCodeGen {
def gen(n: Int) = {
s"""
"Message$n.apply" should "resolve interpolation" in {
val m_test$n = 'm_test$n.m[${Seq.fill(n)("Int").mkString(",")}]
m_test$n(${(1 to n).mkString(",")}) should equal ("test ${(1 to n).mkString(" ")}")
}
"""
}
def genMessage(n: Int) = {
s"m_test$n=test ${(0 until n).map(i => s"{$i}").mkString(" ")}"
}
def genToFile(path: String) : Unit = {
val contents =
s"""$header
package s_mach.i18n.test
import java.util.Locale
import org.scalatest.{FlatSpec, Matchers}
import s_mach.i18n._
import s_mach.i18n.messages._
class MessageNTest extends FlatSpec with Matchers {
implicit val i18ncfg = I18NConfig(Locale.ENGLISH)
${(1 to 22).map(i => gen(i)).mkString("\n")}
}
"""
import java.io._
val out = new PrintWriter(new BufferedWriter(new FileWriter(path)))
out.println(contents)
out.close()
}
}
示例12: ClassOps
//设置package包名称以及导入依赖的类
package com.github.stonexx.scala.util
import java.lang.annotation.Annotation
import java.net.URI
import java.util.{Date, Locale}
import org.apache.commons.lang3.ClassUtils
import scala.reflect.ClassTag
final class ClassOps[T](val self: Class[T]) extends AnyVal {
import cls._
def isSimpleType: Boolean = ClassUtils.isPrimitiveOrWrapper(self) ||
classOf[CharSequence].isAssignableFrom(self) ||
classOf[Number].isAssignableFrom(self) ||
classOf[Date].isAssignableFrom(self) ||
classOf[URI] == self ||
classOf[Locale] == self ||
classOf[Class[_]] == self ||
self.isEnum
def findAnnotation[A <: Annotation : ClassTag](annotationClass: Class[A]): Option[A] =
Option(self getAnnotation annotationClass).orElse {
self.getInterfaces.find(_ isAnnotationPresent annotationClass).flatMap(_.findAnnotation[A])
}.orElse {
if (classOf[Annotation] isAssignableFrom self) None
else self.getAnnotations.map(_.annotationType).find(_ isAnnotationPresent annotationClass).flatMap(_.findAnnotation[A])
}.orElse {
Option(self.getSuperclass).filter(_ != classOf[Object]).flatMap(_.findAnnotation[A])
}
@inline
def findAnnotation[A <: Annotation](implicit atag: ClassTag[A]): Option[A] =
findAnnotation(atag.runtimeClass.asInstanceOf[Class[A]])
}
trait ToClassOps {
implicit def toClassOps[T](x: Class[T]): ClassOps[T] = new ClassOps(x)
}
示例13: 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)
}
}
示例14: CmdType
//设置package包名称以及导入依赖的类
package libgcode
import java.text.{DecimalFormat,DecimalFormatSymbols}
import java.util.Locale
object CmdType extends Enumeration {
type CmdType = Value
val G, M, O, T, Empty = Value
}
object ParamType extends Enumeration {
type ParamType = Value
val A, B, C, D, E, F, H, I, J, K, L, P, Q, R, S, T, X, Y, Z = Value
}
import CmdType._
import ParamType.{T => PT, _}
// each line is a command
case class Command( ctype: CmdType, // Empty means it is a comment only
code: Seq[Int], // code X.Y corresponds to Seq(X, Y)
parameters: Seq[Param], // parameters
line: Option[Int], // line number (optional)
comment: Option[String]) { // trailing comment
def replaceComment(c: Option[String]) = {
if (c == comment) this
else Command(ctype, code, parameters, line, comment)
}
}
sealed abstract class Param
case class ParamT(ptype: ParamType) extends Param {
override def toString = ptype.toString
}
case class RealParam(ptype: ParamType, value: Double) extends Param {
assert(RealParam.is(ptype), ptype + " is not a real valued parameter")
override def toString = ptype.toString + RealParam.format(value)
}
case class IntParam(ptype: ParamType, value: Int) extends Param {
assert(IntParam.is(ptype), ptype + " is not an integer valued parameter")
override def toString = ptype.toString + value
}
object RealParam {
val types = Set(A, B, C, D, E, F, H, I, J, K, Q, R, X, Y, Z)
def is(t: ParamType) = types(t)
protected val df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH))
df.setMaximumFractionDigits(340)
def format(d: Double) = df.format(d)
}
object IntParam {
val types = Set(L, P, S, PT)
def is(t: ParamType) = types(t)
}
示例15: log
//设置package包名称以及导入依赖的类
package de.sciss.imperfect
import java.awt.Color
import java.awt.image.BufferedImage
import java.text.SimpleDateFormat
import java.util.{Date, Locale}
import scala.annotation.elidable
import scala.annotation.elidable.CONFIG
package object hough {
var showLog = true
private[this] val logHeader = new SimpleDateFormat("[d MMM yyyy, HH:mm''ss.SSS] 'imperfect' - ", Locale.US)
final val NominalWidth = 1920
final val NominalHeight = 1080
final val VisibleWidth = 3840
final val VisibleHeight = 540
// final val OffScreenImg = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_BYTE_GRAY)
final val OffScreenImg = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_INT_ARGB)
final val OffScreenG = {
val res = OffScreenImg.createGraphics()
res.setColor(Color.black)
res.fillRect(0, 0, VisibleWidth, VisibleHeight)
res
}
@elidable(CONFIG) def log(what: => String): Unit =
if (showLog) Console.out.println(s"${logHeader.format(new Date())}$what")
def warn(s: String): Unit =
Console.err.println(s"Warning: $s")
}