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

Scala Configuration类代码示例

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

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



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


示例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)
      }
    }
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:37,代码来源:CustomApplicationLoader.scala


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


示例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
                      )
} 
开发者ID:rajat965ng,项目名称:storyBoard,代码行数:53,代码来源:StoryController.scala


示例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)))
  }
} 
开发者ID:lunatech-labs,项目名称:lunatech-lunch-planner,代码行数:46,代码来源:Application.scala


示例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))
      }
    }
  }
} 
开发者ID:RichyHBM,项目名称:Dux,代码行数:57,代码来源:PermissionController.scala


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


示例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]]
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:24,代码来源:PullRequestClientModule.scala


示例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)
  }
} 
开发者ID:snackCake,项目名称:TweetStreamChallenge,代码行数:34,代码来源:TweetCometController.scala


示例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
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:32,代码来源:Tweet.scala


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

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


示例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")
    }
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:30,代码来源:IntegrationSpec.scala


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

} 
开发者ID:toolsplus,项目名称:atlassian-connect-play-slick,代码行数:21,代码来源:TestData.scala


示例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)
      }
    })
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:34,代码来源:BaseAuthController.scala


示例16: PasswordSettingsData

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

import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.user.UserService
import models.user.Roles._
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.Controller
import scala.concurrent.{ ExecutionContext, Future }

case class PasswordSettingsData(currentPassword: String, newPassword: String, verifyPassword: String)

class PasswordSettingsController @Inject() (
    val config: Configuration,
    val users: UserService,
    val messagesApi: MessagesApi,
    implicit val ctx: ExecutionContext
  ) extends Controller with AuthElement with HasConfig with HasUserService with Security with I18nSupport {

  private val matchingPasswords: Constraint[PasswordSettingsData] = Constraint("constraints.valid"){ d =>
    if (d.newPassword == d.verifyPassword) Valid else Invalid("Passwords must match")
  }

  val passwordSettingsForm = Form(
    mapping(
      "current" -> nonEmptyText,
      "new" -> nonEmptyText,
      "verify" -> nonEmptyText
    )(PasswordSettingsData.apply)(PasswordSettingsData.unapply).verifying(matchingPasswords)
  )

  def index() = StackAction(AuthorityKey -> Normal) { implicit request =>
    Ok(views.html.my.settings.password(passwordSettingsForm, loggedIn.user))
  }

  def updatePassword() = AsyncStack(AuthorityKey -> Normal) { implicit request =>
    passwordSettingsForm.bindFromRequest.fold(
      formWithErrors =>
        Future.successful(BadRequest(views.html.my.settings.password(formWithErrors, loggedIn.user))),

      f => {
        users.updatePassword(loggedIn.user.getUsername, f.currentPassword, f.newPassword)
          .map { _ match {
            case Right(_) =>
              Redirect(routes.PasswordSettingsController.index).flashing("success" -> "Your password has been updated.")
            case Left(errorMessage) =>
              Redirect(routes.PasswordSettingsController.index).flashing("error" -> errorMessage)
          }}.recover { case t:Throwable => {
            t.printStackTrace()
            Redirect(routes.PasswordSettingsController.index).flashing("error" -> "There was an error while updating your password.")
          }}
      }
    )
  }

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


示例17: PlaceAPIController

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

import com.vividsolutions.jts.geom.Coordinate
import controllers.{ BaseOptAuthController, HasPrettyPrintJSON }
import javax.inject.{ Inject, Singleton }
import models.document.DocumentService
import models.place.PlaceService
import models.user.UserService
import models.user.Roles._
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc.Action
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Try, Success, Failure }

@Singleton
class PlaceAPIController @Inject() (
    val config: Configuration,
    val documents: DocumentService,
    val users: UserService,
    val places: PlaceService,
    implicit val ctx: ExecutionContext
  ) extends BaseOptAuthController(config, documents, users) with HasPrettyPrintJSON {
    
  
  def searchPlacesInDocument(query: String, docId: String, offset: Int, size: Int) = AsyncStack { implicit request =>
    documentResponse(docId, loggedIn.map(_.user), { case (metadata, accesslevel) =>
      if (accesslevel.canRead)
        places.searchPlacesInDocument(query, docId, offset, size).map { results =>
          jsonOk(Json.toJson(results.map(_._1)))
        }
      else
        Future.successful(ForbiddenPage)
    })
  }
 
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:38,代码来源:PlaceAPIController.scala


示例18: LoginData

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

import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.{ Inject, Singleton }
import jp.t2v.lab.play2.auth.{ AuthElement, LoginLogout }
import models.document.DocumentService
import models.user.UserService
import play.api.Configuration
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, Future }

case class LoginData(usernameOrPassword: String, password: String)

@Singleton
class LoginLogoutController @Inject() (    
    val config: Configuration,
    val users: UserService,
    implicit val ctx: ExecutionContext,
    val messagesApi: MessagesApi
  ) extends Controller with AuthElement with HasConfig with HasUserService with Security with LoginLogout with I18nSupport {

  private val MESSAGE = "message"

  private val INVALID_LOGIN = "Invalid Username or Password"

  val loginForm = Form(
    mapping(
      "username" -> nonEmptyText,
      "password" -> nonEmptyText
    )(LoginData.apply)(LoginData.unapply)
  )

  def showLoginForm(destination: Option[String]) = Action { implicit request =>
    destination match {
      case None => Ok(views.html.landing.login(loginForm))
      case Some(dest) => Ok(views.html.landing.login(loginForm)).withSession("access_uri" -> dest)
    }
  }

  def processLogin = Action.async { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors =>
        Future(BadRequest(views.html.landing.login(formWithErrors))),

      loginData =>
        users.validateUser(loginData.usernameOrPassword, loginData.password).flatMap {
          case Some(validUser) => gotoLoginSucceeded(validUser.getUsername)
          case None => Future(Redirect(routes.LoginLogoutController.showLoginForm()).flashing(MESSAGE -> INVALID_LOGIN))
        }
    )
  }

  def logout = Action.async { implicit request =>
    gotoLogoutSucceeded
  }

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


示例19: StatsController

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

import controllers.{ BaseAuthController, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.document.DocumentService
import models.user.UserService
import models.user.Roles._
import play.api.Configuration
import scala.concurrent.ExecutionContext

@Singleton
class StatsController @Inject() (
    val config: Configuration,
    val documents: DocumentService,
    val users: UserService,
    implicit val webjars: WebJarAssets,
    implicit val ctx: ExecutionContext
  ) extends BaseAuthController(config, documents, users) {

  
  def showDocumentStats(documentId: String) = AsyncStack(AuthorityKey -> Normal) { implicit request =>
    documentResponse(documentId, loggedIn.user,{ case (doc, accesslevel) => 
      Ok(views.html.document.stats.index(doc, Some(loggedIn.user), accesslevel)) })
  }

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


示例20: DiscussionController

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

import controllers.{ BaseAuthController, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.document.DocumentService
import models.user.UserService
import models.user.Roles._
import play.api.Configuration
import scala.concurrent.ExecutionContext

@Singleton
class DiscussionController @Inject() (
    val config: Configuration,
    documents: DocumentService,
    val users: UserService,
    implicit val webjars: WebJarAssets,
    implicit val ctx: ExecutionContext
  ) extends BaseAuthController(config, documents, users) {

  def showDiscussionBoard(documentId: String) = AsyncStack(AuthorityKey -> Normal) { implicit request =>
    documentResponse(documentId, loggedIn.user, { case (doc, accesslevel) =>
      Ok(views.html.document.discussion.index(doc, Some(loggedIn.user), accesslevel)) })
  }

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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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