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

Scala CacheApi类代码示例

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

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



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

示例1: ProfileController

//设置package包名称以及导入依赖的类
package controllers
import javax.inject._

import play.api.cache.CacheApi
import play.api.mvc._
import models.UserData
import services.ImpConfService


@Singleton
class ProfileController @Inject()(cache: CacheApi,statusService: ImpConfService) extends Controller {

  def index = Action { implicit request=>
    val name = request.session.get("mySession").fold("unkown#@123")(identity) // use different name when there is no session
    val user = cache.get[UserData](name)
    val userkey = statusService.userdata
    user match {
      case Some(UserData(name,fname,mname,lname,age,pass,mobile,gender,hobbies,status,isSuspended)) if(status == "true")=> Redirect("/show ")
      case Some(UserData(uname,fname,mname,lname,age,pass,mobile,gender,hobbies,status,isSuspended)) =>  Ok(views.html.profile(uname,fname,mname,lname,age,mobile,gender,hobbies))
      case None =>  Redirect(routes.LoginController.index()).flashing("success" -> "login first")
    }
  }

  def outSession = Action{ implicit request=>

    Ok(views.html.index("with new session")).withNewSession
  }

} 
开发者ID:SHUB9914,项目名称:AjaxPlay-SHUBHAM,代码行数:30,代码来源:ProfileController.scala


示例2: CacheReadWriteService

//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import models.User
import play.api.cache.CacheApi


class CacheReadWriteService @Inject() (cache: CacheApi) extends ReadWriteService{

  override def checkUser(username: String): Boolean = {
    cache.get[User](username) match{
      case Some(_) => true
      case None => false
    }
  }

  override def addUser(user: User): Boolean = {
    cache.set(user.username,user)
    true
  }

  override def getUser(username: String, password: String): User = {
    cache.get[User](username) match {
      case Some(user) =>
        if(user.password == password) user else throw new Exception("Password incorrect")
      case None => throw new Exception("User not found")
    }
  }

} 
开发者ID:anuj1207,项目名称:play-scala-ajax,代码行数:30,代码来源:CacheReadWriteService.scala


示例3: cached

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

import javax.inject.{Inject, Singleton}

import play.api.cache.{CacheApi, _}
import play.api.mvc.{Action, AnyContent}

import scala.concurrent.duration._
import scala.reflect.ClassTag


  def cached(key: String, expiration: Duration = 4 hours)(response: => Action[AnyContent]) = {
    getOrElse(key) {
      val result = response()
      set(key, result, expiration)
      result
    }
  }

}

@Singleton
class SemesterModeCache @Inject()(@NamedCache("semester-mode-cache") semesterModeCache: CacheApi) extends CacheHelper {
  cache = semesterModeCache
}

@Singleton
class SessionCache @Inject()(@NamedCache("session-cache") sessionCache: CacheApi) extends CacheHelper {
  cache = sessionCache
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:31,代码来源:CacheHelper.scala


示例4: IntegrationSpec

//设置package包名称以及导入依赖的类
import org.scalatestplus.play._
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.{Configuration, Mode}
import play.api.cache.{CacheApi, EhCacheModule}
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test._
import play.api.test.Helpers._
import util.FakeCache


class IntegrationSpec extends PlaySpec with GuiceOneServerPerSuite with OneBrowserPerTest with HtmlUnitFactory {

  implicit override lazy val app = new GuiceApplicationBuilder()
    .overrides(bind[CacheApi].to[FakeCache])
    .loadConfig(env => Configuration.load(env))
    .in(Mode.Test)
    .build

  "Application" should {

    "work from within a browser" in {

      go to ("http://localhost:" + port)

      pageSource must include ("Aktuelles der Fakultät Informatik")
    }
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:30,代码来源:IntegrationSpec.scala


示例5: ApplicationSpec

//设置package包名称以及导入依赖的类
import org.scalatestplus.play._
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api._
import play.api.cache.CacheApi
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.Helpers._
import play.api.test._
import util.FakeCache


class ApplicationSpec extends PlaySpec with GuiceOneAppPerSuite {

  implicit override lazy val app = new GuiceApplicationBuilder()
    .overrides(bind[CacheApi].to[FakeCache])
    .loadConfig(env => Configuration.load(env))
    .in(Mode.Test)
    .build

  "Routes" should {

    "send 404 on a bad request" in {
      route(app, FakeRequest(GET, "/boum")).map(status(_)) mustBe Some(NOT_FOUND)
    }

  }

  "NewsPageController" should {

    "render the index page" in {
      val home = route(app, FakeRequest(GET, "/")).get

      status(home) mustBe OK
      contentType(home) mustBe Some("text/html")
      contentAsString(home) must include("Aktuelles der Fakultät Informatik")
    }

  }

} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:41,代码来源:ApplicationSpec.scala


示例6: AuthorizeStoreCache

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

import java.time.LocalDateTime
import play.api.cache.CacheApi

case class AuthorizeStoreCache(value: CacheApi) extends AnyVal

sealed abstract class AuthorizeStore

object AuthorizeStore {
  case class Token(accessToken: String,
                   expirationDate: LocalDateTime,
                   tokenType: TokenType,
                   grantType: GrantType,
                   uid: String,
                   realm: String,
                   scope: List[String])
      extends AuthorizeStore

  case class Code(state: String,
                  clientId: String,
                  redirectUri: String,
                  username: String,
                  scope: List[String])
      extends AuthorizeStore
} 
开发者ID:zalando-incubator,项目名称:OAuth2-mock-play,代码行数:27,代码来源:AuthorizeStore.scala


示例7: cachedLookup

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

import org.jooq.{ Table, Record, SortField }
import play.api.cache.CacheApi
import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.duration._
import scala.reflect.ClassTag
import storage.DB


  protected def cachedLookup[T: ClassTag](prefix: String, key: String, 
      dbLookup: String => Future[Option[T]])(implicit db: DB, cache: CacheApi, ctx: ExecutionContext): Future[Option[T]] = {
    
    val maybeCachedValue = cache.get[T](prefix + "_" + key)
    if (maybeCachedValue.isDefined) {
      Future.successful(maybeCachedValue)
    } else {
      dbLookup(key).map(maybeStoredValue => {
        if (maybeStoredValue.isDefined)
          cache.set(prefix + "_" + key, maybeStoredValue.get, 10.minutes)

        maybeStoredValue
      })
    }
  }
  
  protected def removeFromCache(prefix: String, key: String)(implicit cache: CacheApi) = {
    cache.remove(prefix + "_" + key)
  }

  protected def getSortField[T <: Table[_]](tables: Seq[T], fieldname: String, sortOrder: Option[SortOrder]) = {
    val maybeField = tables.flatMap(_.fields).find(_.getName.equalsIgnoreCase(fieldname))
    maybeField.map { field =>
      val order = sortOrder.getOrElse(SortOrder.ASC)
      if (order == SortOrder.ASC)
        field.asc
      else
        field.desc
    }
  }

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


示例8: WebSocketController

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

import javax.inject._

import akka.actor.{ActorSystem, _}
import akka.stream.Materializer
import play.api.libs.json._
import play.api.libs.streams.ActorFlow
import play.api.mvc._
import models._
import play.api.cache.{Cache, CacheApi}



@Singleton
class WebSocketController @Inject()(implicit system: ActorSystem, materializer: Materializer, cache: CacheApi) {

  object MyWebSocketActor {
    def props(out: ActorRef) = Props(new MyWebSocketActor(out))
  }

  class MyWebSocketActor(out: ActorRef) extends Actor {
    override def preStart() {
      println("open")
      println(self.path.parent.toSerializationFormat)
      val x = system.actorSelection(self.path.parent.toSerializationFormat)
      x ! "Message12"
    }

    override def postStop() {
      println("close")
    }

    override def receive = {
      case request: JsValue =>
        val response = handleMessage(request)
        out ! response
    }

    def handleMessage(event: Event): JsValue = {
      event match {
        case event: EventA => {
          val actorId = self.path.parent.toSerializationFormat
          cache.set("actor-id_" + event.data, actorId)
          Json.toJson(event)
        }
        case event: EventB => Json.toJson(event)
      }
    }
  }

  def socket = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(out => MyWebSocketActor.props(out))

  }

} 
开发者ID:koduki,项目名称:example-palyframework,代码行数:58,代码来源:WebSocketController.scala


示例9: HomeController

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

import javax.inject._

import akka.actor.{ActorSystem, _}
import dao.CatDAO
import models._
import play.api.cache.CacheApi
import play.api.data.Form
import play.api.data.Forms.{mapping, text}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc._



@Singleton
class HomeController @Inject()(implicit system: ActorSystem, catDao: CatDAO, cache: CacheApi) extends Controller {

  def index = Action.async {
    val actorId = cache.get[String]("actor-id_1").get
    println(actorId)
    val client = system.actorSelection(actorId)
    client ! Json.toJson(EventB("MessageB"))

    catDao.all().map {
      cats => Ok(views.html.index(cats))
    }
  }

  def insertCat = Action.async { implicit request =>
    val cat: Cat = catForm.bindFromRequest.get
    catDao.insert(cat).map(_ => Redirect(routes.HomeController.index))
  }

  def ws = Action { request => Ok(views.html.ws()) }

  val catForm = Form(
    mapping(
      "name" -> text(),
      "color" -> text()
    )(Cat.apply)(Cat.unapply)
  )
} 
开发者ID:koduki,项目名称:example-palyframework,代码行数:45,代码来源:HomeController.scala


示例10: UIController

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

import java.util.concurrent.TimeUnit
import play.api.cache.CacheApi
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Action, Controller }
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.Duration


class UIController(val messagesApi: MessagesApi, cacheApi: CacheApi, teaHubController: TEAHubController)(implicit executionContext: ExecutionContext) extends Controller with I18nSupport {
  val togglTokenForm = Form(single("togglToken" -> text()))
  val projectName = Form(single("projectName" -> text()))

  def management = Action { implicit request => Ok(views.html.user_management()) }

  def listPost = Action { implicit request =>
    {
      togglTokenForm.bindFromRequest().fold(
        error => // Warning here because 'error' is never used
          BadRequest(views.html.setup_projects(togglTokenForm, "An error occurred.")),
        data => {
          cacheApi.set("togglToken", data, Duration(1, TimeUnit.DAYS)) // TODO: in the future this will be stored on
          // the DB
          Ok(views.html.projects())
        }
      )
    }
  }

  def listGet = Action { implicit request =>
    Ok(views.html.projects())
  }

  def setup = Action { implicit request => Ok(views.html.setup_projects(togglTokenForm, "")) }
  def details = Action { implicit request => Ok(views.html.project_details()) }

  def newProject = Action.async { implicit request =>
    teaHubController.togglProjects.map(projects => Ok(views.html.new_project(projectName, projects)))
  }

  def issues = Action { implicit request => Ok(views.html.issues()) }
  def profile = Action { implicit request => Ok(views.html.profile()) }

} 
开发者ID:lunatech-labs,项目名称:teahub,代码行数:48,代码来源:UIController.scala


示例11: JsI18nController

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

import javax.inject.{ Inject, Singleton }
import play.api.mvc.Controller
import play.api.i18n.{ I18nSupport, MessagesApi }
import ejisan.play.i18n.JsI18nSupport
import play.api.cache.CacheApi

@Singleton
class JsI18nController @Inject()(
  val cacheApi: CacheApi,
  val messagesApi: MessagesApi
) extends Controller with I18nSupport with JsI18nSupport {
  def script = JsI18nAction.script

  def messages(prefix: String = "", variable: String = "messages") =
    JsI18nAction.messages(prefix, variable)

  def additionalMessages(prefix: String = "", variable: String = "messages") =
    JsI18nAction.additionalMessages(prefix, variable)

  def messagesJson(prefix: String = "") = JsI18nAction.messagesJson(prefix)
} 
开发者ID:ejisan,项目名称:play-i18n-js,代码行数:24,代码来源:JsI18nController.scala


示例12: ManageController

//设置package包名称以及导入依赖的类
package controllers
import services._
import javax.inject.Inject

import play.api.Configuration
import play.api.cache.CacheApi
import play.api.mvc.{Action, Controller}


class ManageController @Inject()(cache: CacheApi, cacheService:CacheTrait, configuration: Configuration) extends Controller{

  def ManagementArea()= Action { implicit  request =>

    val allUsers =  bufferService.getAllUsers
    val users = for {
      userName <- allUsers
    }yield  cacheService.getCache(userName)
    Ok(views.html.Manage(users.flatten.toList))

  }

  def suspendUser(username:String)= Action { implicit  request =>
    val users = cacheService.getCache(username)
    users match {
      case Some(user) => {
        val BlockedUser = user.copy(isAllow = true)
        cacheService.removeFromCache(username)
        cache.set(username,BlockedUser)
      }
      case None=>
    }
    Redirect(routes.ManageController.ManagementArea())
  }
  def resumeUser(username:String)= Action { implicit  request =>
    val users = cacheService.getCache(username)
    users match {
      case Some(user) => {
        val resumedUser = user.copy(isAllow = false)
        cacheService.removeFromCache(username)
        cacheService.setCache(username,resumedUser)
      }
    }
    Redirect(routes.ManageController.ManagementArea())
  }

} 
开发者ID:kunals201,项目名称:play2-assignment-kunal-testcases,代码行数:47,代码来源:ManageController.scala


示例13: ServiceSpec

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

import models._
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.cache.CacheApi
import services._

class ServiceSpec extends PlaySpec with MockitoSugar {

  "UserService" should {
    "set list" in {
      val cacheService = mock[CacheTrait]
      val cache = mock[CacheApi]
      cacheService.setCache("kunal", SignUp("", "", "", "", "", "", "", false, false))
      when(cache.get[SignUp]("kunal")) thenReturn (Option(SignUp("", "", "", "", "", "", "", false, false)))
    }

    "get list" in {
      val cacheService = mock[CacheTrait]
      val cache = mock[CacheApi]
      cache.set("kunal", SignUp("", "", "", "", "", "", "", false, false))
      when(cacheService.getCache("kunal")) thenReturn (Option(SignUp("", "", "", "", "", "", "", false, false)))
    }

    "remove list" in {
      val cacheService = mock[CacheTrait]
      val cache = mock[CacheApi]
      cache.set("kunal", SignUp("kunal", "", "", "", "", "", "", false, false))
      cacheService.removeFromCache("kunal")
      when(cache.get("kunal")) thenReturn (None)

    }
  }
} 
开发者ID:kunals201,项目名称:play2-assignment-kunal-testcases,代码行数:37,代码来源:ServiceSpec.scala


示例14: SessionActor

//设置package包名称以及导入依赖的类
package mazerunner.actor.session

import javax.inject.Inject

import akka.actor.Actor
import mazerunner.actor.session.SessionActor._
import play.api.cache.CacheApi

class SessionActor @Inject()(cache: CacheApi) extends Actor {

  def receive = {

    case CacheUser(username, token) => sender() ! {
      if (cache.get[String](username).isDefined) CacheDeclined
      else {
        cache.set(username, token)
        CacheAccepted
      }
    }

    case RemoveUser(username) => cache.remove(username)
  }

}

object SessionActor {
  case class CacheUser(username: String, token: String)
  case class RemoveUser(username: String)

  sealed trait CacheStatus
  case object CacheAccepted extends CacheStatus
  case object CacheDeclined extends CacheStatus
} 
开发者ID:mronethere,项目名称:maze-runner,代码行数:34,代码来源:SessionActor.scala


示例15: StravaAthleteService

//设置package包名称以及导入依赖的类
package com.themillhousegroup.play2.strava.services

import javax.inject.{ Inject, Singleton }

import com.themillhousegroup.play2.strava.models._

import scala.concurrent.Future
import scala.concurrent.duration.Duration
import StravaJson._
import play.api.cache.CacheApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import com.themillhousegroup.play2.strava.services.traits.CachingStravaService
import play.api.Logger
import com.themillhousegroup.play2.strava.services.helpers.AuthBearer._

@Singleton
class StravaAthleteService @Inject() (val stravaAPI: StravaAPI, val cache: CacheApi)
    extends CachingStravaService[List[StravaSegmentEffort], Long] {

  val logger = Logger("StravaAthleteService")

  def getFullAthleteInfo(stravaAccessToken: String, athleteId: Long): Future[Option[StravaAthlete]] = {
    getWithBearerAuth(stravaAPI.athleteFinder(athleteId), stravaAccessToken).map { response =>
      if (response.status == 200) {
        Some(response.json.as[StravaAthlete])
      } else {
        None
      }
    }
  }

  def listFriendsFor(stravaAccessToken: String, athleteId: Long): Future[Seq[EssentialStravaAthlete]] = {
    val paginatedFriendsList = (page: Int) =>
      getWithBearerAuth(stravaAPI.allMyFriendsFinder(athleteId, page), stravaAccessToken).map { response =>
        logger.info(s"Friends response for athlete $athleteId, page $page: using token: $stravaAccessToken \n${response.json}")
        response.json.as[Seq[StravaAthleteSummary]]
      }

    StravaAPI.paginate(paginatedFriendsList)
  }

  val komCacheExpiry = Duration(3, "hours")

  def cacheNameFor(athleteId: Long) = s"komCache[${athleteId}]"

  def withKOMCacheFor(athleteId: Long, accessToken: String): Future[Seq[StravaSegmentEffort]] =
    withCacheFor(athleteId, accessToken)(listKOMsFor)

  private def listKOMsFor(stravaAccessToken: String, athleteId: Long): Future[Seq[StravaSegmentEffort]] = {

    val paginatedKOMList = (page: Int) =>
      getWithBearerAuth(stravaAPI.allMyKOMsFinder(athleteId, page), stravaAccessToken).map { response =>
        logger.info(s"KOMS response for athlete $athleteId, page $page: using token: $stravaAccessToken \n${response.json}")
        response.json.as[Seq[StravaSegmentEffort]]
      }

    StravaAPI.paginate(paginatedKOMList)
  }
} 
开发者ID:themillhousegroup,项目名称:play2-strava,代码行数:60,代码来源:StravaAthleteService.scala


示例16: cacheNameFor

//设置package包名称以及导入依赖的类
package com.themillhousegroup.play2.strava.services.traits

import scala.concurrent.Future
import scala.concurrent.duration.Duration
import scala.reflect.ClassTag

import play.api.cache.CacheApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.Logger

trait CachingStravaService[T, ID] {
  val cache: CacheApi
  val logger: Logger

  protected val cacheExpiry = Duration(3, "hours")

  protected def cacheNameFor(entityId: ID): String

  protected def withCacheFor[T: ClassTag](entityId: ID, accessToken: String)(fetcher: (String, ID) => Future[T]): Future[T] = {
    val cacheName = cacheNameFor(entityId)
    val maybeResult = cache.get[T](cacheName)

    maybeResult.fold {
      logger.warn(s"Cache miss for $cacheName")
      fetcher(accessToken, entityId).map { entity =>
        cache.set(cacheName, entity, cacheExpiry)
        entity
      }
    } { hit =>
      logger.debug(s"Cache hit for $cacheName")
      Future.successful(hit)
    }
  }
} 
开发者ID:themillhousegroup,项目名称:play2-strava,代码行数:35,代码来源:CachingStravaService.scala


示例17: channelByPath

//设置package包名称以及导入依赖的类
package de.welt.contentapi.client.services.configuration

import javax.inject.{Inject, Singleton}

import de.welt.contentapi.core.models.config
import de.welt.contentapi.core.models.config.{Channel, ChannelData, ChannelId, Env}
import de.welt.contentapi.client.services.contentapi.LegacySectionService
import de.welt.contentapi.client.services.s3.S3
import de.welt.contentapi.core.traits.Loggable
import play.api.cache.CacheApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.{Environment, Mode}

import scala.concurrent.duration._

trait SectionConfigurationService {

  def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel]

}

@Singleton
class SectionConfigurationServiceImpl @Inject()(funkConfig: ContentClientConfig,
                                                s3: S3,
                                                environment: Environment,
                                                legacySectionService: LegacySectionService,
                                                cache: CacheApi)
  extends SectionConfigurationService with Loggable {

  override def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel] = {
    root.findByPath(id.path)
  }

  private def objectKeyForEnv(env: Env) = environment.mode match {
    case Mode.Prod ? s"janus2/prod/${env.toString}/config.json"
    case _ ? s"janus2/dev/${env.toString}/config.json"
  }

  private[configuration] def root(implicit env: Env): Channel = cache.getOrElse(env.toString, 10.minutes) {
    import config.WithChildrenReads._

    val maybeData: Option[String] = s3.get(funkConfig.aws.s3.janus.bucket, objectKeyForEnv(env))

    maybeData
      .map { data ? Json.parse(data).validate[Channel] }
      .flatMap {
        case JsSuccess(v, _) ?
          Some(v)
        case [email protected](_) ?
          log.warn(err.toString)
          None
      }.getOrElse {
      log.warn("No data found in s3 bucket.")
      throw new IllegalStateException("no channel data")
    }

  }
} 
开发者ID:WeltN24-public,项目名称:WeltContentApiClient,代码行数:59,代码来源:SectionConfigurationService.scala


示例18: channelByPath

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

import javax.inject.{Inject, Singleton}

import de.welt.models.config
import de.welt.models.config.{Channel, ChannelData, ChannelId, Env}
import de.welt.services.contentapi.LegacySectionService
import de.welt.services.s3.S3
import de.welt.traits.Loggable
import play.api.cache.CacheApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.{Environment, Mode}

import scala.concurrent.duration._

trait SectionConfigurationService {

  def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel]

}

@Singleton
class SectionConfigurationServiceImpl @Inject()(funkConfig: ContentClientConfig,
                                                s3: S3,
                                                environment: Environment,
                                                legacySectionService: LegacySectionService,
                                                cache: CacheApi)
  extends SectionConfigurationService with Loggable {

  override def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel] = {
    root.findByPath(id.path)
  }

  private def objectKeyForEnv(env: Env) = environment.mode match {
    case Mode.Prod ? s"janus2/prod/${env.toString}/config.json"
    case _ ? s"janus2/dev/${env.toString}/config.json"
  }

  private[configuration] def root(implicit env: Env): Channel = cache.getOrElse(env.toString, 10.minutes) {
    import config.WithChildrenReads._

    val maybeData: Option[String] = s3.get(funkConfig.aws.s3.janus.bucket, objectKeyForEnv(env))

    maybeData
      .map { data ? Json.parse(data).validate[Channel] }
      .flatMap {
        case JsSuccess(v, _) ?
          Some(v)
        case [email protected](_) ?
          log.warn(err.toString)
          None
      }.getOrElse {
      log.warn("No data found in s3 bucket.")
      throw new IllegalStateException("no channel data")
    }

  }
} 
开发者ID:WeltN24-public,项目名称:WeltContentApiClient,代码行数:59,代码来源:SectionConfigurationService.scala


示例19: CachecoolApi

//设置package包名称以及导入依赖的类
package de.zalando.cachecool.playmodule

import javax.inject.{Inject, Singleton}

import de.zalando.cachecool.Cache
import play.api.cache.CacheApi

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.reflect.ClassTag


@Singleton
class CachecoolApi @Inject()(val namespace: String, timeout: Duration, cache: Cache) extends CacheApi {
  override def set(key: String, value: Any, expiration: Duration): Unit = Await.ready(cache.put(key, value, Option(expiration)), timeout)

  override def get[T: ClassTag](key: String): Option[T] = Await.result(cache.get[T](key), timeout)

  def getOrElse[A: ClassTag](key: String, expiration: Duration = Duration.Inf)(orElse: => A): A = {
    val result: A = orElse
    Await.result(cache.getOrElse[A](key, Option(expiration))(Future {
      Option(result)
    }), timeout)
    result
  }

  override def remove(key: String): Unit = Await.ready(cache.remove(key), timeout)
} 
开发者ID:psycho-ir,项目名称:cachecool,代码行数:29,代码来源:CachecoolApi.scala


示例20: LoadDataServiceSpec

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

import models._
import org.specs2.mock.Mockito
import play.api.cache.CacheApi
import play.api.test.PlaySpecification
import utils.ReadHelper

import scala.concurrent.Future

class LoadDataServiceSpec extends PlaySpecification with Mockito {

  val cache: CacheApi = mock[CacheApi]
  val readerUtility: ReadHelper = mock[ReadHelper]

  val loadDataService = new LoadDataService(cache, readerUtility)

  val runways = List(Runway(1L, 1L, "ident", "len", "width", "surface", "ident"))
  val airports = List(Airport(1L, "h1", "airType", "name", "iso", "region", runways))
  val countryData = List(Country(1L, "aus", "australia", airports))
  val airportRunways = List(CountryRunway("aus", List("type")))
  val runwayIndents = List(RunwayIdent("ident", 1))

  val runwayStr = List("""246281,27232,"FV76",3704,50,"ASP",0,0,"08",-19.0119,30.0199,,78,,"26",-19.0098,30.0304,,258,""", """246281,27232,"FV76",3704,50,"ASP",0,0,"08",-19.0119,30.0199,,78,,"26",-19.0098,30.0304,,258,""")
  val airportStr = List("""27232,"FV76","small_airport","Kwekwe East Airport",-19.010799407958984,30.02519989013672,4025,"AF","ZW","ZW-MI",,"no","FV76",,"FV76",,,""", """27232,"FV76","small_airport","Kwekwe East Airport",-19.010799407958984,30.02519989013672,4025,"AF","ZW","ZW-MI",,"no","FV76",,"FV76",,,""")
  val countriesStr = List("""302612,"ZW","Zimbabwe","AF","http://en.wikipedia.org/wiki/Zimbabwe",""", """302612,"ZW","Zimbabwe","AF","http://en.wikipedia.org/wiki/Zimbabwe",""")


  "LoadDataServiceSpec" should {
    "be able to get data" in {
      readerUtility.loadData("runways", "./app/resources/runways.csv") returns Future.successful(runwayStr)
      readerUtility.loadData("airports", "./app/resources/airports.csv") returns Future.successful(airportStr)
      readerUtility.loadData("countries", "./app/resources/countries.csv") returns Future.successful(countriesStr)
      val result = await(loadDataService.storeData)
      result.head.name must beEqualTo("Zimbabwe")
    }
  }
} 
开发者ID:arpitkulria,项目名称:luna,代码行数:39,代码来源:LoadDataServiceSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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