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

Scala Lang类代码示例

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

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



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

示例1: IfTag

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

import models._
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Days}
import org.joda.time.Minutes
import org.joda.time.Hours
import play.api.Play
import play.api.Play.current
import play.api.i18n.Lang
import play.twirl.api.Html
import utils.DateUtils
import utils.m
import play.api.mvc.WrappedRequest

class IfTag(condition: Boolean, content: => Html) extends scala.xml.NodeSeq {

  def theSeq = Nil // just ignore, required by NodeSeq

  override def toString = if (condition) content.toString else ""

  def orElse(failed: => Html) = if (condition) content else failed
}

object CustomTag {

  
  def date2delay(d: DateTime)(implicit request: WrappedRequest[_]): String = {
    val d_minus_seven_days = DateUtils.now.minusDays(7)
    val d_minus_one_days = DateUtils.now.minusDays(1)
    val d_minus_one_hours = DateUtils.now.minusHours(1)
    val now = DateUtils.now

    if (d.isAfterNow) { "" }
    else if (d.isAfter(d_minus_one_hours)) {
      val minutes_delta = Minutes.minutesBetween(d, now)
      m("general.date.delay.minutes", Math.abs(minutes_delta.getMinutes))
    } else if (d.isAfter(d_minus_one_days)) {
      val hours_delta = Hours.hoursBetween(d, now)
      m("general.date.delay.hours", Math.abs(hours_delta.getHours))
    } else if (d.isAfter(d_minus_seven_days.toInstant)) {
      val day_delta = Days.daysBetween(d, now)
      m("general.date.delay.days", Math.abs(day_delta.getDays))
    } else {
      m("general.date.delay.on", date_format(d, Some("MMM")), d.getDayOfMonth)
    }
  }

  def date_format(date: DateTime, format: Option[String] = None)(implicit lang: Lang): String = {
    val pattern = format
      .orElse(Play.configuration.getString(s"date.i18n.date.format.${lang.language}"))
      .getOrElse("dd/MM/yyyy")
    val locale = lang.toLocale

    val formatter = DateTimeFormat.forPattern(pattern).withLocale(locale)
    formatter.print(date)
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:59,代码来源:CustomTag.scala


示例2: toResult

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

import ApiResponse._
import ApiError._
import models.ApiLog
import play.api.mvc.Results._
import play.api.mvc.{ Result, RequestHeader }
import play.api.libs.json._
import play.api.libs.json.Json._
import play.api.i18n.Lang


  def toResult[R <: RequestHeader](implicit request: R, lang: Lang): Result = {
    val envelope = request.getQueryString("envelope") == Some("true")
    toResult(envelope)
  }
  def toResult(envelope: Boolean = false)(implicit lang: Lang): Result = {
    val js = if (envelope) envelopedJson else json
    (status match {
      case STATUS_CREATED => if (js == JsNull) Created else Created(js)
      case STATUS_ACCEPTED => if (js == JsNull) Accepted else Accepted(js)
      case STATUS_NOCONTENT => NoContent
      case s if s < 300 => if (js == JsNull) Ok else Ok(js)

      case STATUS_BADREQUEST => BadRequest(js)
      case STATUS_UNAUTHORIZED => Unauthorized(js)
      case STATUS_FORBIDDEN => Forbidden(js)
      case STATUS_NOTFOUND => NotFound(js)
      case s if s > 400 && s < 500 => BadRequest(js)
      case _ => InternalServerError(js)
    }).withHeaders((headers ++ Api.basicHeaders): _*)
  }
} 
开发者ID:fvthree,项目名称:play-rest-api-2.4-anorm-mysql,代码行数:34,代码来源:ApiResult.scala


示例3: SelectionItem

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

import play.api.i18n.Messages
import play.api.i18n.Lang

case class SelectionItem(text: String,
                         icon: Option[String] = None,
                         localized: Boolean = true) {

  def localizedText(implicit lang: Lang, messages: Messages) = {
    if (localized) {
      Messages(text)
    } else {
      text
    }
  }
} 
开发者ID:intracer,项目名称:wlxjury,代码行数:18,代码来源:SelectionItem.scala


示例4: Application

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

import models.web._
import play.api._
import play.api.mvc._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang }
import javax.inject.Inject

class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def index = Action { implicit request =>
    Ok(views.html.web.index())
  }

  def selectLang(lang: String) = Action { implicit request =>
    Logger.logger.debug("Change user lang to : " + lang)
    request.headers.get(REFERER).map { referer =>
      Redirect(referer).withLang(Lang(lang))
    }.getOrElse {
      Redirect(routes.ApplicationController.index).withLang(Lang(lang))
    }
  }

} 
开发者ID:pawank,项目名称:play-silhouette-mongodb-multi-project-sbt,代码行数:25,代码来源:Application.scala


示例5: Application

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

import models.admin._
import play.api._
import play.api.mvc._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang }
import javax.inject.Inject

class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def index = Action { implicit request =>
    val computers = ComputerAdmin.list
    Ok(views.html.admin.index(Messages("admin.subtitle"), computers))
  }

  def selectLang(lang: String) = Action { implicit request =>
    Logger.logger.debug("Change user lang to : " + lang)
    request.headers.get(REFERER).map { referer =>
      Redirect(referer).withLang(Lang(lang))
    }.getOrElse {
      Redirect(routes.Application.index).withLang(Lang(lang))
    }
  }

} 
开发者ID:pawank,项目名称:play-silhouette-mongodb-multi-project-sbt,代码行数:26,代码来源:Application.scala


示例6: password

//设置package包名称以及导入依赖的类
package views.html.htmlForm

import play.api.data.Field
import play.api.i18n.Lang
import play.twirl.api.Html
import views.html.helper.FieldConstructor


object password {
  def apply(field: Field, label: String, args: (Symbol, Any)*)
           (implicit handler: FieldConstructor, lang: Lang): Html =
    Html {
      val label2 = if (label.endsWith("*")) s"${ label.substring(0, label.length-1) }<sup>*</sup>" else label
      s"""<dl ${ if (field.errors.nonEmpty) "class='error'" else "" } id="${ field.id }_label">
         |  <dt><label for="${ field.id }">$label2</label></dt>
         |    <dd><input type="password" id="${ field.id }" name="${ field.id }" value="${ field.value }">
         |  ${ if (field.errors.nonEmpty)  field.errors else "" }</dd>
         |</dl>
         |""".stripMargin
    }
} 
开发者ID:mslinn,项目名称:html-form-scala,代码行数:22,代码来源:password.scala


示例7: checkbox

//设置package包名称以及导入依赖的类
package views.html.htmlForm.bootstrap3

import play.api.data.Field
import play.api.i18n.{Lang, Messages}
import play.api.templates.PlayMagic.toHtmlArgs
import play.twirl.api.Html
import views.html.helper.{FieldConstructor, input => playInput}


object checkbox {
  def apply(field: Field, args: (Symbol, Any)*)
           (implicit handler: FieldConstructor, lang: Lang, messages: Messages): Html = {
    val boxValue = args.toMap.getOrElse('value, "true")
    playInput(field, args:_*) { (id, name, value, htmlArgs) =>
      Html(s"""<label class="checkbox">
              |  <input type="checkbox" name="$name" value="$boxValue"
              |    ${ if (value.contains(boxValue)) "checked" else "" } ${ toHtmlArgs(htmlArgs.filterKeys(_ != 'value)) } />
              |  ${ args.toMap.getOrElse('_text, "") }
              |</label>
              |""".stripMargin)
    }
  }
} 
开发者ID:mslinn,项目名称:html-form-scala,代码行数:24,代码来源:checkbox.scala


示例8: LocalizationController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Silhouette
import play.api.i18n.{ I18nSupport, MessagesApi, Lang }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

class LocalizationController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv])
  extends Controller with I18nSupport {

  def langDE = silhouette.UserAwareAction { implicit request =>
    val referrer = request.headers.get(REFERER).getOrElse("/")
    Redirect(referrer).withLang(Lang("de"))
  }

  def langEN = silhouette.UserAwareAction { implicit request =>
    val referrer = request.headers.get(REFERER).getOrElse("/")
    Redirect(referrer).withLang(Lang("en"))
  }
} 
开发者ID:fstiehle,项目名称:de.htwg.wt.nmm,代码行数:25,代码来源:LocalizationController.scala


示例9: Import

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

import javax.inject.Inject

import services.VocabularyService
import models.Vocabulary

import play.api.mvc._
import play.api.i18n.Lang

class Import @Inject() (vocabulary: VocabularyService) extends Controller {

  def importWord(
    sourceLanguage: Lang,
    word: String,
    targetLanguage: Lang,
    translation: String) = Action { request =>
    val added = vocabulary.addVocabulary(
      Vocabulary(sourceLanguage, targetLanguage, word, translation)
    )
    if (added) Ok else Conflict
  }

} 
开发者ID:juanitodread,项目名称:simple-vocabulary-teacher,代码行数:25,代码来源:Import.scala


示例10: Quizz

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

import javax.inject.Inject

import services.VocabularyService

import play.api.mvc._
import play.api.i18n.Lang

class Quizz @Inject() (vocabulary: VocabularyService) extends Controller {

  def quizz(sourceLanguage: Lang, targetLanguage: Lang) = Action { request =>
    vocabulary.findRandomVocabulary(sourceLanguage, targetLanguage) match {
      case Some(_) => Ok
      case None => NotFound
    }
  }

  def check(sourceLanguage: Lang, word: String, targetLanguage: Lang, translation: String) = Action { request =>
    vocabulary.verify(sourceLanguage, word, targetLanguage, translation) match {
      case true => Ok
      case false => NotAcceptable
    }
  }

} 
开发者ID:juanitodread,项目名称:simple-vocabulary-teacher,代码行数:27,代码来源:Quizz.scala


示例11: VocabularyService

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

import models.Vocabulary

import javax.inject.Singleton

import scala.util.Random

import play.api.i18n.Lang

@Singleton
class VocabularyService {

  private var allVocabulary = List(
    Vocabulary(Lang("en"), Lang("es"), "hello", "hola"),
    Vocabulary(Lang("en"), Lang("es"), "play", "jugar")
  )

  def addVocabulary(v: Vocabulary): Boolean = {
    if (!allVocabulary.contains(v)) {
      allVocabulary = v :: allVocabulary
      true
    } else {
      false
    }
  }

  def findRandomVocabulary(sourceLanguage: Lang, targetLanguage: Lang): Option[Vocabulary] = {
    Random.shuffle(allVocabulary.filter { v =>
      v.sourceLanguage == sourceLanguage &&
        v.targetLanguage == targetLanguage
    }).headOption
  }

  def verify(sourceLanguage: Lang, word: String, targetLanguage: Lang, translation: String): Boolean = {
    allVocabulary.contains(Vocabulary(sourceLanguage, targetLanguage, word, translation))
  }

} 
开发者ID:juanitodread,项目名称:simple-vocabulary-teacher,代码行数:40,代码来源:VocabularyService.scala


示例12: JsDump

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

import java.io._
import scala.concurrent.Future

import play.api.i18n.Lang
import play.api.libs.json.{ JsString, JsObject }

private[i18n] final class JsDump(
    path: String,
    pool: I18nPool,
    keys: I18nKeys
) {

  def keysToObject(keys: Seq[I18nKey], lang: Lang) = JsObject {
    keys.map { k =>
      k.key -> JsString(k.to(lang)())
    }
  }

  def keysToMessageObject(keys: Seq[I18nKey], lang: Lang) = JsObject {
    keys.map { k =>
      k.en() -> JsString(k.to(lang)())
    }
  }

  def apply: Funit = Future {
    pathFile.mkdir
    writeRefs
    writeFullJson
  } void

  private val pathFile = new File(path)

  private def dumpFromKey(messages: List[I18nKey], lang: Lang): String =
    messages.map { key =>
      """"%s":"%s"""".format(key.key, escape(key.to(lang)()))
    }.mkString("{", ",", "}")

  private def writeRefs {
    val code = pool.names.toList.sortBy(_._1).map {
      case (code, name) => s"""["$code","$name"]"""
    }.mkString("[", ",", "]")
    val file = new File("%s/refs.json".format(pathFile.getCanonicalPath))
    val out = new PrintWriter(file)
    try { out.print(code) }
    finally { out.close }
  }

  private def writeFullJson {
    pool.langs foreach { lang =>
      val code = dumpFromKey(keys.keys, lang)
      val file = new File("%s/%s.all.json".format(pathFile.getCanonicalPath, lang.language))
      val out = new PrintWriter(file)
      try { out.print(code) }
      finally { out.close }
    }
  }

  private def escape(text: String) = text.replace(""""""", """\"""")
} 
开发者ID:DrNixx,项目名称:line,代码行数:62,代码来源:JsDump.scala


示例13: FileFix

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

import scala.concurrent.Future

import play.api.i18n.Lang

private[i18n] final class FileFix(
    pool: I18nPool,
    path: String,
    keys: I18nKeys,
    messages: Messages
) {

  val apply: Funit =
    Future.traverse(pool.nonDefaultLangs.toList)(fix).void

  private def fix(lang: Lang): Funit =
    write(lang, sanitize((messages get lang.language) | Map.empty))

  private def sanitize(messages: Map[String, String]) =
    keys.keys map { key =>
      messages get key.key filter { message =>
        hasVariable(key.to(pool.default)()).fold(hasVariable(message), true)
      } map (key.key -> _)
    } flatten

  private def hasVariable(message: String) = message contains "%s"

  private def write(lang: Lang, messages: List[(String, String)]) = {
    val file = "%s/messages.%s".format(path, lang.language)
    printToFile(file) { writer =>
      messages foreach {
        case (name, trans) => writer.println(name + "=" + trans)
      }
    }
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:38,代码来源:FileFix.scala


示例14: Translator

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

import play.api.i18n.Lang
import play.api.mvc.RequestHeader
import play.twirl.api.Html

private[i18n] final class Translator(messages: Messages, pool: I18nPool) {

  private val defaultMessages = messages.get("default") err "No default messages"

  def html(key: String, args: List[Any])(implicit req: RequestHeader): Html =
    Html(str(key, args)(req))

  def str(key: String, args: List[Any])(implicit req: RequestHeader): String =
    translate(key, args)(pool lang req) getOrElse key

  def transTo(key: String, args: Seq[Any])(lang: Lang): String =
    translate(key, args)(lang) getOrElse key

  def rawTranslation(lang: Lang)(key: String): Option[String] =
    messages get lang.language flatMap (_ get key)

  private def defaultTranslation(key: String, args: Seq[Any]): Option[String] =
    defaultMessages get key flatMap { pattern =>
      formatTranslation(key, pattern, args)
    }

  private def translate(key: String, args: Seq[Any])(lang: Lang): Option[String] =
    if (lang.language == pool.default.language) defaultTranslation(key, args)
    else messages get lang.language flatMap (_ get key) flatMap { pattern =>
      formatTranslation(key, pattern, args)
    } orElse defaultTranslation(key, args)

  private def formatTranslation(key: String, pattern: String, args: Seq[Any]) = try {
    Some(if (args.isEmpty) pattern else pattern.format(args: _*))
  }
  catch {
    case e: Exception =>
      logger.warn(s"Failed to translate $key -> $pattern ($args)", e)
      None
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:43,代码来源:Translator.scala


示例15: TransInfo

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

import play.api.i18n.Lang

case class TransInfo(
    lang: Lang,
    name: String,
    contributors: List[String],
    nbTranslated: Int,
    nbMissing: Int
) {

  def code = lang.language

  def codeAndName = code + " - " + name

  def nbMessages = nbTranslated + nbMissing

  def percent = nbTranslated * 100 / nbMessages

  def complete = percent == 100

  def nonComplete = !complete
}

private[i18n] case class TransInfos(all: List[TransInfo]) {

  lazy val byCode = all map { info =>
    info.code -> info
  } toMap

  def get(code: String): Option[TransInfo] = byCode get code

  def get(lang: Lang): Option[TransInfo] = get(lang.language)
}

private[i18n] object TransInfos {

  val defaultCode = "en"

  def apply(messages: Messages, keys: I18nKeys): TransInfos = TransInfos {
    val nbMessages = keys.count
    LangList.sortedList.filter(_._1 != defaultCode) map {
      case (code, name) => TransInfo(
        lang = Lang(code),
        name = name,
        contributors = Contributors(code),
        nbTranslated = messages.get(code) ?? (_.size),
        nbMissing = nbMessages - (messages.get(code) ?? (_.size))
      )
    }
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:54,代码来源:TransInfo.scala


示例16: DetectLanguage

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

import play.api.i18n.Lang
import play.api.libs.json._
import play.api.libs.ws.WS
import play.api.Play.current

// http://detectlanguage.com
final class DetectLanguage(url: String, key: String) {

  private case class Detection(
    language: String,
    confidence: Float,
    isReliable: Boolean
  )

  private implicit val DetectionReads = Json.reads[Detection]

  private val messageMaxLength = 2000

  def apply(message: String): Fu[Option[Lang]] =
    WS.url(url).post(Map(
      "key" -> Seq(key),
      "q" -> Seq(message take messageMaxLength)
    )) map { response =>
      (response.json \ "data" \ "detections").asOpt[List[Detection]] match {
        case None =>
          lila.log("DetectLanguage").warn(s"Invalide service response ${response.json}")
          None
        case Some(res) => res.filter(_.isReliable)
          .sortBy(-_.confidence)
          .headOption map (_.language) flatMap Lang.get
      }
    } recover {
      case e: Exception =>
        lila.log("DetectLanguage").warn(e.getMessage, e)
        Lang("en").some
    }
}

object DetectLanguage {

  import com.typesafe.config.Config
  def apply(config: Config): DetectLanguage = new DetectLanguage(
    url = config getString "api.url",
    key = config getString "api.key"
  )
} 
开发者ID:DrNixx,项目名称:line,代码行数:49,代码来源:DetectLanguage.scala


示例17: LanguageController

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

import javax.inject.Inject

import models.Languages
import play.api.data._
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.i18n.{I18nSupport, Lang, MessagesApi}

class LanguageController @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def changeLanguage() = Action { implicit request =>
    println("Changing language?")
    // Get URL of page the language was changed from, default to root
    val referer = request.headers.get(REFERER).getOrElse("/")
    // Define a single field form
    val form = Form("languageCode" -> nonEmptyText)
    // Populate the form with the data from the request
    form.bindFromRequest.fold(
      erroneousForm => {println("Invalid language form sent"); Redirect(referer)},
      languageCode => Redirect(referer).withLang(if (Languages.supported.contains(languageCode))
        Lang(languageCode)
      else
        Lang("lv")
      )
    )
  }

} 
开发者ID:rusins,项目名称:pusdieno,代码行数:31,代码来源:LanguageController.scala


示例18: WelcomeView

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

import controllers.routes
import play.api.i18n.{Lang, Messages}
import play.api.mvc.RequestHeader
import play.twirl.api.Html

import scala.concurrent.{ExecutionContext, Future}
import scalatags.Text.all._

object WelcomeView {

  def index()(implicit messages: Messages, lang: Lang,
              request: RequestHeader): Html = {
    val headers: Frag = meta(name := "google-site-verification", content := "l_AKKzyNYlbZcqLqbjlcZp40qf41mQkKxRJeUz9ph48")

    val body: Frag = SeqFrag(Seq(
      div(width := 100.pct, height := 100.pct, paddingTop := 100,
        backgroundImage := "url(\"/assets/images/cover_lowsize.jpg\")", backgroundSize := "cover")(
        div(cls := "container")(
          div(cls := "jumbotron", color := "#FFFFFF", backgroundColor := "rgba(0, 0, 0, 0.7)")(
            h1(color := "#FFFFFF")("Pusdieno!"),
            p(messages("welcome.text")),
            p(a(cls := "btn btn-success btn-lg", href := routes.AuthController.signIn().url)(messages("sign-in")))
          )
        )
      )
    ))

    MainTemplate("Pusdieno", "welcome", headers, body, None)
  }

} 
开发者ID:rusins,项目名称:pusdieno,代码行数:34,代码来源:WelcomeView.scala


示例19: SignInView

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

import com.mohiva.play.silhouette.impl.providers.SocialProviderRegistry
import controllers.routes
import play.api.i18n.{Lang, Messages}
import play.api.mvc.RequestHeader
import play.twirl.api.Html
import views.styles.SignInStyleSheet

import scala.concurrent.{ExecutionContext, Future}
import scalacss.DevDefaults._
import scalacss.ScalatagsCss._
import scalatags.Text
import scalatags.Text.all._

object SignInView {

  def apply(socialProviderRegistry: SocialProviderRegistry)
           (implicit request: RequestHeader, messages: Messages, lang: Lang): Html = {

    val headers = Seq(
      SignInStyleSheet.render[scalatags.Text.TypedTag[String]]
    )

    val errorSpot: Frag = request.flash.get("error") match {
      case Some(errorMessage) => div(`class` := "alert alert-danger center-block", maxWidth := 480)(
        errorMessage
      )
      case None => UnitFrag(Unit)
    }

    val body: Frag = div(`class` := "container", paddingTop := 100)(
      div(`class` := "panel panel-default center-block", maxWidth := 480)(
        div(`class` := "panel-heading")(messages("sign-in")),
        div(`class` := "panel-body")(
          a(href := routes.AuthController.authenticate("google").url)(
            img(src := "/assets/images/google_sign_in.png", `class` := "img-responsive center-block")
          ),
          div(`class` := "text-center")(messages("or")),
          a(href := routes.AuthController.authenticate("facebook").url)(
            img(src := "/assets/images/facebook_sign_in.png", `class` := "img-responsive center-block")
          )
        )
      ),
      errorSpot
    )

    MainTemplate(messages("sign-in"), "sign-in", headers, body, None)
  }
} 
开发者ID:rusins,项目名称:pusdieno,代码行数:51,代码来源:SignInView.scala


示例20: fetch

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

import com.google.inject.Inject
import play.api.Logger
import play.api.http.HeaderNames
import play.api.i18n.Lang
import play.api.libs.json.{JsError, JsSuccess, Json, Reads}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.{Cookie, Cookies}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.control.NonFatal


trait WsConsumer {
  def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang): Future[T]
}

class WsConsumerImpl @Inject()(ws: WSClient) extends WsConsumer {
  val log = Logger("WsConsumer")

  override def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang) =
    ws.url(url).
      withCookies(Cookie("PLAY_LANG", lang.language)).
      withRequestTimeout(timeout).
      get().flatMap { result =>
      Json.fromJson(result.json) match {
        case JsSuccess(s, _) =>
          Future.successful(s)
        case JsError(e) =>
          val errors = JsError.toJson(e).fields.foldLeft("")((acc, next) => acc + next + "\n")
          Future.failed(new RuntimeException(s"Failed to unmarshal:\n $errors"))
      }
    }.recoverWith {
      case NonFatal(t) =>
        log.warn(s"Failed to fetch '$url'")
        Future.failed(new RuntimeException(t))
    }

  implicit class WithCookiesOps(requestHolder: WSRequest) {
    def withCookies(cookies: Cookie*): WSRequest = {
      val encoded = Cookies.encodeSetCookieHeader(cookies.toSeq)
      requestHolder.withHttpHeaders(HeaderNames.COOKIE -> encoded)
    }
  }

} 
开发者ID:splink,项目名称:pagelets-seed,代码行数:49,代码来源:WsConsumer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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