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

Scala Locale类代码示例

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

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



在下文中一共展示了Locale类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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("* * * * *")))
  }
} 
开发者ID:shigemk2,项目名称:my-cron-utils-scala,代码行数:21,代码来源:Hello.scala


示例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
) 
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:22,代码来源:StoryQueryObject.scala


示例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)
    }
  )
} 
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:53,代码来源:package.scala


示例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}}"""
} 
开发者ID:francois,项目名称:family,代码行数:32,代码来源:Family.scala


示例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
        }
    }
} 
开发者ID:francois,项目名称:family,代码行数:37,代码来源:AccountWithInterest.scala


示例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)
    }
} 
开发者ID:francois,项目名称:family,代码行数:50,代码来源:I18n.scala


示例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}")))
} 
开发者ID:francois,项目名称:family,代码行数:59,代码来源:Config.scala


示例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
  }
} 
开发者ID:wix,项目名称:libpay-stripe,代码行数:27,代码来源:LocaleCountrySerializer.scala


示例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})"
} 
开发者ID:S-Mach,项目名称:s_mach.i18n,代码行数:18,代码来源:MessagesMap.scala


示例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
  )
} 
开发者ID:S-Mach,项目名称:s_mach.i18n,代码行数:20,代码来源:UTF8Messages.scala


示例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()
  }
} 
开发者ID:S-Mach,项目名称:s_mach.i18n,代码行数:45,代码来源:MessageNTestCodeGen.scala


示例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)
} 
开发者ID:stonexx,项目名称:utils,代码行数:41,代码来源:ClassOps.scala


示例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)
  }

} 
开发者ID:wvlet,项目名称:wvlet,代码行数:60,代码来源:TimeStampFormatter.scala


示例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)
} 
开发者ID:dzufferey,项目名称:libgcode,代码行数:59,代码来源:GCode.scala


示例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")
} 
开发者ID:Sciss,项目名称:ImperfectHough,代码行数:35,代码来源:package.scala


示例16: ItalianVATIdNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.pdfextractor.algorithm.candidate.Candidate
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.VATIN
import org.pdfextractor.db.domain.dictionary.{PaymentFieldType, SupportedLocales}
import org.springframework.stereotype.Service

import scala.collection.mutable
import scala.util.matching.Regex

@Service
class ItalianVATIdNumberFinder
  extends AbstractFinder(SupportedLocales.ITALY, VATIN, ItVatinR, ItVatinValueR, true, true) {

 override def searchValuesFromPhrase(
                                       phrase: Phrase,
                                       parseResult: ParseResult,
                                       valuePattern2: Regex): mutable.Buffer[Candidate] = {
    searchPattern.get
      .findAllIn(parseResult.text)
      .map(getValuePattern.findAllIn(_))
      .filter(isValueAllowed(_))
      .map(buildCandidate1(_))
      .toBuffer
  }

  override def isValueAllowed(value: Any): Boolean = {
    Option(value).isDefined &&
      value.isInstanceOf[String] &&
      value.asInstanceOf[String].length == 11 &&
      value.asInstanceOf[String].matches("""\d*""")
  }

  override def parseValue(raw: String): Any = raw

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:42,代码来源:ItalianVATIdNumberFinder.scala


示例17: ItalianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{CandidateMetadata, MetaPhraseType}
import org.pdfextractor.algorithm.finder._
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class ItalianNameFinder extends AbstractFinder(SupportedLocales.ITALY, NAME, None, None, false) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?ims)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ITALY,
        NAME) + "$").r)
    valuePattern = Some(("^(?ims)(.*)$").r)
  }

  def isValueAllowed(value: Any): Boolean = {
    !isVoidText(value.asInstanceOf[String]) &&
      ItNameForbiddenWordsR.findFirstIn(value.asInstanceOf[String]).isEmpty &&
      ItNameMinR.findFirstIn(value.asInstanceOf[String]).nonEmpty
  }

  def parseValue(raw: String): Any = {
    if (Option(raw).isEmpty) None
    else StringUtils.normalizeSpace(raw).split(",")(0)
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ITALY, NAME, phrase.text)
    Map(MetaPhraseType -> phraseType)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:45,代码来源:ItalianNameFinder.scala


示例18: EstonianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{Candidate, CandidateMetadata, HasPank, MetaPhraseType}
import org.pdfextractor.algorithm.finder.{AbstractFinder, isPankPresent}
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianNameFinder extends AbstractFinder(SupportedLocales.ESTONIA, NAME) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?m)" + phraseTypesStore
        .buildAllStarts(SupportedLocales.ESTONIA, NAME) + "$").r)
    valuePattern = Some(
      ("(?m)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        NAME)).r)
  }

  override def isValueAllowed(value: Any) = true

  override def parseValue(raw: String): Any = {
    StringUtils normalizeSpace (raw
      .replaceAll("(Registrikood)(.{0,})", "")
      .split("""[\s]{3,}""")(0))
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ESTONIA, NAME, phrase.text)
    val pankPresent = isPankPresent(phrase.text)
    Map(MetaPhraseType -> phraseType, HasPank -> pankPresent)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:43,代码来源:EstonianNameFinder.scala


示例19: EstonianReferenceNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.math.BigInteger
import java.util.Locale

import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.finder.{AbstractFinder, _}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.REFERENCE_NUMBER
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianReferenceNumberFinder extends AbstractFinder(SupportedLocales.ESTONIA, REFERENCE_NUMBER, EstRefNoLineR, EstRefNoR) {

  override def parseValue(raw: String): Any = raw

  override def isValueAllowed(raw: Any): Boolean = {
    try {
      val value = new BigInteger(raw.asInstanceOf[String])
      isCorrectFormat(value) && checkDigitMatches(value,
        calculateCheckDigit(value))
    } catch {
      case _: Throwable => false
    }
  }

  private def calculateCheckDigit(value: BigInteger) = {
    val productsSum = calculate731Sum(digitsToPenultimateInReverse(value))

    findTensMultiple(productsSum) - productsSum
  }

  private def checkDigitMatches(value: BigInteger, checkDigit: Int) = {
    val lastDigit =
      Integer.valueOf("" + value.toString.charAt(value.toString.length - 1))
    lastDigit == checkDigit
  }

  private def isCorrectFormat(value: BigInteger): Boolean = {
    Option(value).isDefined &&
      value.signum > 0 && // must be positive
      value.toString.length >= 2 && // must have 2 - 20 digits
      value.toString.length <= 20
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:47,代码来源:EstonianReferenceNumberFinder.scala


示例20: EstonianInvoiceIDFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.INVOICE_ID
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianInvoiceIDFinder extends AbstractFinder(SupportedLocales.ESTONIA, INVOICE_ID) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("(?ism)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        INVOICE_ID)).r)
    valuePattern = Some(("(?ism)" + phraseTypesStore.buildAllPhrases(
      SupportedLocales.ESTONIA,
      INVOICE_ID) +
      """([.]{0,1})([\s]{0,})([:]{0,1})([\s]{0,})([^\s]{1,})""").r)
  }

  override def isValueAllowed(value: Any): Boolean = {
    EstIBANCorrectR
      .findFirstIn(value.asInstanceOf[String])
      .isEmpty &&
      TwoOrMoreDigitsR
        .findFirstIn(value.asInstanceOf[String])
        .nonEmpty
  }

  override def parseValue(raw: String): Any = StringUtils.normalizeSpace(raw)

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:41,代码来源:EstonianInvoiceIDFinder.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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