本文整理汇总了Scala中play.api.Configuration类的典型用法代码示例。如果您正苦于以下问题:Scala Configuration类的具体用法?Scala Configuration怎么用?Scala Configuration使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Configuration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CustomObjectMapperModule
//设置package包名称以及导入依赖的类
package modules
import javax.inject.{Inject, Provider, Singleton}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.inject.{ApplicationLifecycle, Module}
import play.api.{Configuration, Environment}
import play.libs.Json
import scala.concurrent.Future
class CustomObjectMapperModule extends Module {
def bindings(environment: Environment, configuration: Configuration) = Seq(
bind[ObjectMapper].toProvider[ObjectMapperProvider].eagerly()
)
}
@Singleton
class ObjectMapperProvider @Inject() (lifecycle: ApplicationLifecycle) extends Provider[ObjectMapper] {
lazy val get : ObjectMapper = {
val objectMapper = Json.newDefaultMapper()
objectMapper.registerModule(DefaultScalaModule)
Json.setObjectMapper(objectMapper)
lifecycle.addStopHook { () =>
Future.successful(Json.setObjectMapper(null))
}
objectMapper
}
}
示例2: CustomApplicationLoader
//设置package包名称以及导入依赖的类
package modules
import play.api.ApplicationLoader
import play.api.Configuration
import play.api.inject._
import play.api.inject.guice._
import play.api.ApplicationLoader.Context
import com.typesafe.config.ConfigFactory
import play.api.Mode._
import play.Logger
class CustomApplicationLoader extends GuiceApplicationLoader {
override protected def builder(context: Context): GuiceApplicationBuilder = {
val builder = initialBuilder.in(context.environment).overrides(overrides(context): _*)
context.environment.mode match {
case Prod => {
// start mode
val prodConf = Configuration(ConfigFactory.load("prod.conf"))
builder.loadConfig(prodConf ++ context.initialConfiguration)
}
case Dev => {
Logger.error("*** Custom Loader DEV****")
// run mode
val devConf = Configuration(ConfigFactory.load("dev.conf"))
builder.loadConfig(devConf ++ context.initialConfiguration)
}
case Test => {
Logger.error("*** Custom Loader TEST ****")
// test mode
val testConf = Configuration(ConfigFactory.load("test.conf"))
builder.loadConfig(testConf ++ context.initialConfiguration)
}
}
}
}
示例3: AuthentationController
//设置package包名称以及导入依赖的类
package controllers.rest.auth
import javax.inject._
import scala.concurrent.Future
import play.api.mvc._
import play.api.libs.json._
import play.api.i18n._
import play.api.Configuration
import akka.actor.ActorSystem
import jsmessages.JsMessagesFactory
import org.webjars.play.RequireJS
import utils.ExecutionContexts
import business.auth._
import utils.AsyncEnabled
import controllers._
class AuthentationController @Inject() (webJarAssets: WebJarAssets, requireJS: RequireJS, val messagesApi: MessagesApi,
jsMessagesFactory: JsMessagesFactory, authCheker: SecuredChecker[JsValue],
authService: AuthenticationService, configuration: Configuration,
system: ActorSystem, ec: ExecutionContexts)
extends AsyncEnabled(ec) with Controller with I18nSupport {
implicit val threadpool = ec.services
case class LoginForm(userEmail: String, password: String)
implicit val JSON_LOGIN_READER = Json.reads[LoginForm]
def login = SimpleAction(configuration, system) { Action.async(parse.json) { request =>
request.body.validate[LoginForm].map { form =>
authService.authenticate(form.userEmail, form.password) map { sessionId =>
Ok( Json.obj("session" -> sessionId))
} recover {
case ex: AuthenticationException => BadRequest(ex.getMessage)
case ex: Throwable => BadRequest(ex.getMessage)
}
} recoverTotal { case error => Future.successful(BadRequest(error.toString())) }
} }
def logout = SecuredAction(configuration, system, authCheker) { Action.async(parse.json) { request =>
authCheker.getUserIdent(request) map { userEmail =>
authService.disconect(userEmail) map { sessionCount =>
Ok( Json.obj("sessions" -> sessionCount))
} recover {
case ex: AuthenticationException => BadRequest(ex.getMessage)
case ex: Throwable => BadRequest(ex.getMessage)
}
// should never get here, but...
} getOrElse { Future.successful(Results.Unauthorized) }
} }
}
示例4: StoryController
//设置package包名称以及导入依赖的类
package controllers
import controllers.StoryModel.StoryData
import javax.inject.Inject
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import model.StoryDao
import model.DataModel.Story
import scala.collection.mutable.ListBuffer
class StoryController @Inject()(implicit storyDao:StoryDao,config:Configuration) extends Controller{
def index = Action {
val result = storyDao.create();
Ok(views.html.story("Welcome to StoryBoard !!",listStory))
}
def createStory = Action { implicit Request =>
var result = storyDao.insert(new Story(storyForm.bindFromRequest().get.title,storyForm.bindFromRequest().get.description))
Ok(views.html.story("Story Created:" + "(" + storyForm.bindFromRequest().get.title + "," + storyForm.bindFromRequest().get.description + ")",listStory))
}
def listStory:List[StoryData] = {
val stories:List[Story] = storyDao.list
var storiesData = new ListBuffer[StoryData]
for(s <- stories){
storiesData += (new StoryData(s.title,s.description))
}
storiesData.toList
}
val storyForm = Form(
mapping(
"title" -> text,
"description" -> text
)(StoryData.apply)(StoryData.unapply)
)
}
object StoryModel{
case class StoryData(
title:String,
description:String
)
}
示例5: Application
//设置package包名称以及导入依赖的类
package lunatech.lunchplanner.controllers
import com.google.inject.Inject
import lunatech.lunchplanner.common.DBConnection
import lunatech.lunchplanner.models.User
import lunatech.lunchplanner.services.{ MenuPerDayPerPersonService, UserService }
import lunatech.lunchplanner.viewModels.MenuPerDayPerPersonForm
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Controller, Flash }
import play.api.{ Configuration, Environment }
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class Application @Inject() (
userService: UserService,
menuPerDayPerPersonService: MenuPerDayPerPersonService,
val connection: DBConnection,
val environment: Environment,
val messagesApi: MessagesApi,
val configuration: Configuration)
extends Controller with Secured with I18nSupport {
def index = IsAuthenticatedAsync { username =>
implicit request =>
userService.getByEmailAddress(username).flatMap(currentUser =>
getIndex(currentUser))
}
private def getIndex(normalUser: Option[User])(implicit flash: Flash) =
normalUser match {
case Some(user) => getMenuPerDayPerPerson(user)
case None => Future.successful(Unauthorized)
}
private def getMenuPerDayPerPerson(user: User)(implicit flash: Flash) = {
val userIsAdmin = userService.isAdminUser(user.emailAddress)
menuPerDayPerPersonService.getAllMenuWithNamePerDayWithDishesPerPerson(user.uuid).map(_.toArray)
.map(menusPerDayPerPerson =>
Ok(views.html.menuPerDayPerPerson(
user.copy(isAdmin = userIsAdmin),
menusPerDayPerPerson,
MenuPerDayPerPersonForm.menuPerDayPerPersonForm)))
}
}
示例6: PlayWithFoodWithTestComponents
//设置package包名称以及导入依赖的类
package testhelpers
import config.ExampleComponents
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.components.OneServerPerTestWithComponents
import play.api.db.evolutions.Evolutions
import play.api.http.Status
import play.api.libs.ws.WSClient
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, Helpers, TestServer}
import play.api.{Application, Configuration}
import slick.dbio.DBIO
trait PlayWithFoodWithServerBaseTest extends PlaySpec
with OneServerPerTestWithComponents
with DefaultFutureDuration
with DefaultExecutionContext
with Status
with DefaultAwaitTimeout
with FutureAwaits
with BeforeAndAfterEach {
class PlayWithFoodWithTestComponents extends ExampleComponents(context) {
override def configuration: Configuration = {
val testConfig = Configuration.from(TestUtils.config)
val config = super.configuration
val testConfigMerged = config ++ testConfig
config.toString
testConfigMerged
}
implicit lazy val testWsClient: WSClient = wsClient
}
override def components: PlayWithFoodWithTestComponents = new PlayWithFoodWithTestComponents
private def runServerAndCleanUpInMemDb(c: PlayWithFoodWithTestComponents) = {
runServerAndExecute(c.application) {
val dbapi = c.dbApi
Evolutions.cleanupEvolutions(dbapi.database("default"))
}
}
override protected def afterEach(): Unit = {
runServerAndCleanUpInMemDb(components)
}
protected def runServerAndExecute[T](app: Application)(blockWithComponents: => T): T = {
Helpers.running(TestServer(port, app))(blockWithComponents)
}
def runAndAwaitResult[T](action: DBIO[T])(implicit components: ExampleComponents): T = {
TestUtils.runAndAwaitResult(action)(components.actionRunner, duration)
}
}
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:58,代码来源:PlayWithFoodWithServerBaseTest.scala
示例7: PermissionController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import database._
import interfaces.IAuthenticationCache
import models.view
import play.api.{Configuration, Logger}
import play.api.cache.CacheApi
import play.api.libs.json.Json
import play.api.mvc.Controller
import auth.scala._
import utilities.RequestParser
import scala.concurrent.ExecutionContext.Implicits.global
class PermissionController @Inject()(cacheApi: CacheApi, authCache: IAuthenticationCache, configuration: Configuration) extends Controller with AuthenticatedActionBuilder {
val authType = auth.AuthenticationType.None
def cache = cacheApi
def config = configuration
def getAllPermissions = AuthenticatedAction(authType).async {
Permissions.listAll().map(l => {
Ok(Json.toJson(l.map(p => view.ViewPermission(p.Id, p.Name, p.Description)).toList))
})
}
def newPermission = AuthenticatedAction(authType).async(parse.json) { request =>
RequestParser.parseViewPermission(request) {
viewPermission => {
Permissions.add(new Permission(viewPermission.Name, viewPermission.Description)).map(i => Ok(i.toString))
}
}
}
def editPermission = AuthenticatedAction(authType).async(parse.json) { request =>
RequestParser.parseViewPermission(request) {
viewPermission => {
Permissions.edit(viewPermission.Id, viewPermission.Name, viewPermission.Description).map(i => Ok(i.toString))
}
}
}
def deletePermission = AuthenticatedAction(authType).async(parse.json) { request =>
RequestParser.parseViewPermission(request) {
viewPermission => {
Logger.info("Deleting permission %d: '%s' with description: %s".format(
viewPermission.Id,
viewPermission.Name,
viewPermission.Description))
Permissions.delete(viewPermission.Id).map(i => Ok(i.toString))
}
}
}
}
示例8: CloudinaryStorageServiceImpl
//设置package包名称以及导入依赖的类
package io.soheila.cms.services.media.cloudinary
import cloudinary.model.CloudinaryResourceBuilder
import com.cloudinary.Cloudinary
import com.google.inject.Inject
import io.soheila.cms.services.media.ImageStorageService
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
class CloudinaryStorageServiceImpl @Inject() (val cloudinaryResourceBuilder: CloudinaryResourceBuilder, configuration: Configuration) extends ImageStorageService {
implicit val cloudinaryClient: Cloudinary = cloudinaryResourceBuilder.cld
private val config = configuration.underlying
override def generateSignature(paramsToSign: Map[String, _]): String = {
val secret = config.as[String]("cloudinary.api_secret")
val params = paramsToSign.toList.sortBy(_._1) collect {
case (k, v: Iterable[_]) => s"$k=${v.mkString(",")}"
case (k, v) if v != null && v.toString != "" =>
val value = v.toString.replace("\"", "")
s"$k=$value"
}
Cloudinary.sign(params.mkString("&"), secret).map("%02X" format _).mkString
}
}
示例9: PullRequestClientModule
//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client
import de.stema.pullrequests.dto.ProjectDTO
import play.api.inject.{Binding, Module}
import play.api.{Configuration, Environment}
import scala.concurrent.Future
class PullRequestClientModule extends Module {
def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
Seq(
if(configuration.getBoolean("offline").getOrElse(false)) {
bind[PullRequestClient].to[PullRequestSampleClient]
} else {
bind[PullRequestClient].to[PullRequestGitHubClient]
})
}
}
abstract class PullRequestClient {
def getPullRequests(configuration: String): Seq[Future[ProjectDTO]]
}
示例10: TweetCometController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import akka.stream.Materializer
import play.api.Configuration
import play.api.http.ContentTypes
import play.api.libs.Comet
import play.api.libs.json._
import play.api.mvc._
import repositories.TweetRepository
import services.{PersistenceService, TweetService}
class TweetCometController @Inject()(materializer: Materializer,
config: Configuration,
tweetRepository: TweetRepository,
tweetService: TweetService,
persistenceService: PersistenceService) extends Controller {
private lazy val searchTerms = config.getStringSeq("tweet.tags").getOrElse(Seq(""))
def tweetComet = Action {
implicit val mat = materializer
def content = tweetService
.createSearchSource(searchTerms)
.map { s => Option(s.getText).getOrElse("") }
.via(persistenceService.stringPersister(tweetRepository.insert))
.map { s => JsString(s) }
.via(Comet.json("parent.cometMessage"))
Ok.chunked(content).as(ContentTypes.HTML)
}
}
示例11: Tweet
//设置package包名称以及导入依赖的类
package model.spread
import com.typesafe.config.ConfigFactory
import model.news.NewsEntry
import controllers._
import play.api.{Configuration, Logger}
object Tweet {
val config = Configuration(ConfigFactory.load())
lazy val hostUrl =config.getString("spirit.host").getOrElse("http://localhost:9000")
implicit def newsToTweet(newsEntry: NewsEntry):Tweet = {
Tweet(newsEntry.title, hostUrl + routes.NewsPageController.newsEntry(newsEntry.number).url, newsEntry.tags.map("#" + _).mkString(" "))
}
}
case class Tweet(subject: String, url: String, tags: String) {
def mkTweet() = {
val tailWithoutSemester = " " + url
val tailSemester = tailWithoutSemester + " " + tags
val tail =
if (tailSemester.length > 130) tailWithoutSemester
else tailSemester
val maxlen = 140 - tail.length
val shortSubject =
if (subject.length <= maxlen) subject
else subject.slice(0, maxlen-3)+"..."
shortSubject + tail
}
}
示例12: NewsReaderActor
//设置package包名称以及导入依赖的类
package logic.actors.rss
import javax.inject._
import akka.actor._
import helpers.SpiritHelper
import play.api.libs.ws.WSClient
import play.api.{Configuration, Logger}
import scala.concurrent.Await
import scala.concurrent.duration._
@Singleton
class NewsReaderActor @Inject()(configuration: Configuration, ws: WSClient,
@Named("rssParser") rssParserActor: ActorRef) extends Actor with SpiritHelper {
import NewsReaderActor._
import RSSParseActor._
val feedUrl = configuration.underlying.getString("rss.uri")
override def receive: Receive = {
case ReadNews =>
Logger.debug("Reading news")
val response = Await.result(ws.url(feedUrl).get(), 10 seconds)
//Logger.debug(response.statusText)
if (response.status != 200) {
Logger.error("error while news reading " + response.statusText)
} else {
// val responseString = response.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString)
val responseString = response.body
val cachedValue = sessionCache.getOrElse("feedcontent")("")
if(!responseString.equals(cachedValue)) {
sessionCache.set("feedcontent", responseString, Duration.Inf)
rssParserActor ! RSSFeed(responseString)
}
}
case PoisonPill =>
}
}
object NewsReaderActor {
def props = Props[NewsReaderActor]
case object ReadNews
}
示例13: 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")
}
}
}
示例14: TestData
//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.connect.play.slick
import play.api.Configuration
object TestData {
val configuration: Configuration = Configuration.from(
Map(
"slick.dbs.default.profile" -> "slick.jdbc.H2Profile$",
"slick.dbs.default.db.driver" -> "org.h2.Driver",
"slick.dbs.default.db.url" -> "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE",
"play.evolutions.db.default.enabled" -> true
)
)
val configurationWithoutEvolutions
: Configuration = configuration ++ Configuration(
"play.evolutions.db.default.enabled" -> false)
}
示例15: BaseAuthController
//设置package包名称以及导入依赖的类
package controllers
import jp.t2v.lab.play2.auth.AuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.Result
import scala.concurrent.ExecutionContext
abstract class BaseAuthController(
config: Configuration,
documents: DocumentService,
users: UserService
) extends BaseController(config, users) with AuthElement {
protected def documentPartResponse(
docId: String,
partNo: Int,
user: UserRecord,
response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Result
)(implicit ctx: ExecutionContext) = {
documentResponse(docId, user, { case (doc, accesslevel) =>
doc.fileparts.find(_.getSequenceNo == partNo) match {
case None => NotFoundPage
case Some(part) => response(doc, part, accesslevel)
}
})
}
}