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

Scala I18nSupport类代码示例

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

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



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

示例1: TimeCostInput

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

import javax.inject.Inject

import com.shouldioptimize.model.{Ec2Pricing, PreTaxHourlyTimeCostModel}
import play.api.cache.Cached
import play.api.data.Forms._
import play.api.data._
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationResult}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._

case class TimeCostInput(programmerHourCost: BigDecimal, instanceType: String)

class Application @Inject()(val messagesApi: MessagesApi, cached: Cached) extends Controller with I18nSupport {
  val validInstanceType = Constraint[String] ({
    case it if Ec2Pricing.all.contains(it) => Valid
    case _ => Invalid("invalid instance type")
  }: PartialFunction[String,ValidationResult])

  val TimeCostInputForm = Form(
    mapping(
      "programmerHourCost" -> bigDecimal,
      "instanceType" -> text.verifying(validInstanceType)
    )(TimeCostInput.apply)(TimeCostInput.unapply))

  private val DefaultProgrammerHourCost = BigDecimal("42.88")
  private val DefaultInstanceType = "t2.large"
  private val DefaultForm = TimeCostInputForm.fill(TimeCostInput(BigDecimal("42.88"), DefaultInstanceType))

  def index = cached.status(_ => "/index", OK, 60) {
    Action {
      Ok(views.html.results(new PreTaxHourlyTimeCostModel(BigDecimal("42.88")).calculate.values, DefaultForm))
    }
  }

  def results = Action { request =>
    val form = TimeCostInputForm.bind(request.queryString.mapValues(_.head))
    form.fold(
      formWithErrors => BadRequest(views.html.results(new PreTaxHourlyTimeCostModel(DefaultProgrammerHourCost).calculate.values, formWithErrors)),
      timeCostInput => Ok(views.html.results(new PreTaxHourlyTimeCostModel(timeCostInput.programmerHourCost).calculate.values, form))
    )
  }

  def why = cached.status(_ => "/why", OK, 60) {
    Action {
      Ok(views.html.why())
    }
  }

} 
开发者ID:ostewart,项目名称:shouldioptimize,代码行数:52,代码来源:Application.scala


示例2: SignupController

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

import javax.inject.{Inject, Singleton}

import com.mohiva.play.silhouette.api.Silhouette
import forms.SignupForm
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.{Action, Controller, Flash}
import utils.auth.DefaultEnv


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

  def createUser = Action { implicit request =>
    println("trying to create!")
    SignupForm.form.bindFromRequest.fold(
      hasErrors = { form =>
        Redirect(routes.SignupController.registerPage())
          .flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
      },
      success = { signupData =>
        println(s"creating a new user $signupData")
        Redirect(routes.BookmarkController.list())
      }
    )
  }

  
  def registerPage = silhouette.UnsecuredAction { implicit request =>
    Ok(views.html.users.register(SignupForm.form))
  }
} 
开发者ID:lostMohican,项目名称:bookmaarket,代码行数:38,代码来源:SignupController.scala


示例3: ChangePasswordController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future

class ChangePasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  credentialsProvider: CredentialsProvider,
  authInfoRepository: AuthInfoRepository,
  passwordHasherRegistry: PasswordHasherRegistry
)
  extends Controller with I18nSupport {

  def view = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)) { implicit request =>
    Ok(views.html.changePassword(new myform.MyChangePasswordForm(), request.identity))
  }

  def submit = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    new myform.MyChangePasswordForm().bindFromRequest match {
      case form: myform.MyChangePasswordForm => Future.successful(BadRequest(views.html.changePassword(form, request.identity)))
      case data: myform.MyChangePasswordFormData => {
        val (currentPassword, newPassword) = (data.currentPassword, data.newPassword)
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:51,代码来源:ChangePasswordController.scala


示例4: ResetPasswordController

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

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future

class ResetPasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  authInfoRepository: AuthInfoRepository,
  passwordHasherRegistry: PasswordHasherRegistry,
  authTokenService: AuthTokenService
)
  extends Controller with I18nSupport {

  def view(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).map {
      case Some(authToken) => Ok(views.html.resetPassword(new myform.MyResetPasswordForm(), token))
      case None => Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link"))
    }
  }

  def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        new myform.MyResetPasswordForm().bindFromRequest match {
          case form: myform.MyResetPasswordForm => Future.successful(BadRequest(views.html.resetPassword(form, token)))
          case data: myform.MyResetPasswordFormData => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(data.password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        }
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:53,代码来源:ResetPasswordController.scala


示例5: ForgotPasswordController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import models.daos._
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future

class ForgotPasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  authTokenService: AuthTokenService,
  mailerClient: MailerClient,
  envDAO: EnvDAO
)
  extends Controller with I18nSupport {

  def view = silhouette.UnsecuredAction.async { implicit request =>
    Future.successful(Ok(views.html.forgotPassword(new myform.MyForgotPasswordForm())))
  }

  def submit = silhouette.UnsecuredAction.async { implicit request =>
    new myform.MyForgotPasswordForm().bindFromRequest match {
      case form: myform.MyForgotPasswordForm => Future.successful(BadRequest(views.html.forgotPassword(form)))
      case data: myform.MyForgotPasswordFormData => {
        val email = data.email
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = routes.ResetPasswordController.view(authToken.id).absoluteURL()
              println("url " + url)
              if (envDAO.getDosendmail) mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:58,代码来源:ForgotPasswordController.scala


示例6: BaseController

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

import java.util.UUID

import org.joda.time.LocalDateTime
import play.api.i18n.I18nSupport
import services.user.AuthenticationEnvironment
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import models.user.{ Role, User }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{ AnyContent, Result }

import scala.concurrent.Future

abstract class BaseController() extends Silhouette[User, CookieAuthenticator] with I18nSupport {
  def env: AuthenticationEnvironment

  def withAdminSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = SecuredAction.async { implicit request =>
    if (request.identity.roles.contains(Role.Admin)) {
      block(request)
    } else {
      Future.successful(NotFound("404 Not Found"))
    }
  }

  def withSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = UserAwareAction.async { implicit request =>
    val response = request.identity match {
      case Some(user) =>
        val secured = SecuredRequest(user, request.authenticator.getOrElse(throw new IllegalStateException()), request)
        block(secured).map { r =>
          r
        }
      case None =>
        val user = User(
          id = UUID.randomUUID(),
          username = None,
          profiles = Nil,
          created = new LocalDateTime()
        )

        for {
          user <- env.userService.save(user)
          authenticator <- env.authenticatorService.create(LoginInfo("anonymous", user.id.toString))
          value <- env.authenticatorService.init(authenticator)
          result <- block(SecuredRequest(user, authenticator, request))
          authedResponse <- env.authenticatorService.embed(value, result)
        } yield {
          env.eventBus.publish(SignUpEvent(user, request, request2Messages))
          env.eventBus.publish(LoginEvent(user, request, request2Messages))
          authedResponse
        }
    }
    response
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:57,代码来源:BaseController.scala


示例7: ApplicationController

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

import javax.inject._
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import javax.inject.Inject
// Play needs these to generate form messages
import play.api.i18n.I18nSupport
import play.api.i18n.MessagesApi
import views._
import model.{PropertySearchForm}


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

  val searchForm = Form(
    "Address" -> nonEmptyText
  )

  def index = Action {
    Ok(views.html.index("Enter an Address", searchForm, ""))
  }

  def searchProperty() = Action { implicit request =>

    PropertySearchForm.form.bindFromRequest.fold(
      // if any error in submitted data
      errors => BadRequest(views.html.index("Enter an Address", searchForm, "Error ocurred")),
      data => {
        Ok(views.html.index("Enter an Address", searchForm, data.address))
      })
  }

} 
开发者ID:jordac67,项目名称:real_estate_prices,代码行数:38,代码来源:ApplicationController.scala


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


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


示例10: Application

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

import javax.inject.Inject

import scala.concurrent.Future
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.impl.providers.SocialProviderRegistry
import play.api.mvc._
import play.api.i18n.{I18nSupport, MessagesApi}
import utils.auth.CookieEnv

class Application @Inject() (
                              val messagesApi: MessagesApi,
                              silhouette: Silhouette[CookieEnv],
                              socialProviderRegistry: SocialProviderRegistry,
                              implicit val webJarAssets: WebJarAssets) extends Controller with I18nSupport {

  import silhouette._

  def index = UserAwareAction.async { implicit request =>
    Future.successful(Ok(views.html.index(request.identity, request.authenticator.map(_.loginInfo))))
  }

  def profile = SecuredAction { implicit request =>
    Ok(views.html.profile(request.identity, request.authenticator.loginInfo, socialProviderRegistry))
  }
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:28,代码来源:Application.scala


示例11: RestApi

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

import javax.inject.Inject

import scala.concurrent.Future
import com.mohiva.play.silhouette.api.Silhouette
import play.api.libs.json._
import play.api.mvc._
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import models.User
import User._
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import utils.auth.CookieEnv

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

  import silhouette._

  def profile = SecuredAction.async { implicit request =>
    val json = Json.toJson(request.identity.profileFor(request.authenticator.loginInfo).get)
    val prunedJson = json.transform(
      (__ \ 'loginInfo).json.prune andThen
        (__ \ 'passordInfo).json.prune andThen
        (__ \ 'oauth1Info).json.prune)
    prunedJson.fold(
      _ => Future.successful(InternalServerError(Json.obj("error" -> Messages("error.profileError")))),
      js => Future.successful(Ok(js))
    )
  }

  val errorHandler = new SecuredErrorHandler {
    override def onNotAuthenticated(implicit request: RequestHeader) = {
      Future.successful(Unauthorized(Json.obj("error" -> Messages("error.profileUnauth"))))
    }
    override def onNotAuthorized(implicit request: RequestHeader) = {
      Future.successful(Forbidden("local.not.authorized"))
    }
  }
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:42,代码来源:RestApi.scala


示例12: ErrorHandler

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

import javax.inject.{Inject, Provider}

import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import play.api.http.DefaultHttpErrorHandler
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, OptionalSourceMapper}

import scala.concurrent.Future
import controllers.{WebJarAssets, routes}

class ErrorHandler @Inject() (
                               val messagesApi: MessagesApi,
                               env: play.api.Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: javax.inject.Provider[Router],
                               p: Provider[WebJarAssets])
  extends DefaultHttpErrorHandler(env, config, sourceMapper, router)
    with SecuredErrorHandler with I18nSupport {

  // https://www.playframework.com/documentation/2.5.x/Migration25#Handling-legacy-components
  implicit lazy val webJarAssets = p.get()

  override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] =
    Future.successful(Redirect(routes.Auth.signIn()))

  override def onNotAuthorized(implicit request: RequestHeader): Future[Result] =
    Future.successful(Redirect(routes.Auth.signIn()).flashing("error" -> Messages("error.accessDenied")))

  override def onNotFound(request: RequestHeader, message: String): Future[Result] =
    Future.successful(Ok(views.html.errors.notFound(request)))

  override def onServerError(request:RequestHeader, exception:Throwable):Future[Result] =
    Future.successful(Ok(views.html.errors.serverError(request, exception)))
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:41,代码来源:ErrorHandler.scala


示例13: HttpsOnlyFilter

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

import javax.inject.Inject

import scala.concurrent.Future
import play.api._
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc._
import Results.Ok
import akka.stream.Materializer
import play.api.http.HttpFilters
import play.filters.csrf.CSRFFilter
import controllers.routes

// If we configure play.http.forwarded.trustedProxies correctly, we don't need this filter... right? right!?

class HttpsOnlyFilter @Inject() (implicit val mat:Materializer, val messagesApi:MessagesApi) extends Filter with I18nSupport {
  def apply(nextFilter:RequestHeader => Future[Result])(request:RequestHeader):Future[Result] = {
    implicit val r = request
    request.headers.get("X-Forwarded-Proto").map {
      case "https" => nextFilter(request)
      case _ => Future.successful(Ok(views.html.errors.onlyHttpsAllowed()))
    }.getOrElse(nextFilter(request))
  }
}

class Filters @Inject() (
                          configuration:Configuration,
                          csrfFilter:CSRFFilter,
                          httpsOnlyFilter:HttpsOnlyFilter) extends HttpFilters {

  val map = Map("application.proxy.httpsOnly" -> httpsOnlyFilter)
  override def filters = csrfFilter +: map.foldRight[Seq[EssentialFilter]](Seq.empty) { case ((k,f),filters) =>
    configuration.getBoolean(k) collect {
      case true => f +: filters
    } getOrElse filters
  }
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:39,代码来源:Filters.scala


示例14: FormController

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

import javax.inject._
import models.UserData
import play.api._
import play.api.mvc._
import play.api.http.HttpEntity
import play.api.data._
import play.api.data.Forms._
import play.api.i18n.{MessagesApi, I18nSupport}


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

  val userForm: Form[UserData] = Form(
    mapping(
      "name" -> nonEmptyText(minLength = 1, maxLength = 60),
      "age" -> number(min = 0, max = 100)
    )(UserData.apply)(UserData.unapply)
  )

  def createUser = Action {
    Ok(views.html.createUser(userForm))
  }

  def saveUser = Action { implicit request =>
    val userData: UserData = userForm.bindFromRequest.get
    val name: String = userData.name
    val age: Long = userData.age
    Ok(s"saved a user with name $name and of age $age")
  }
} 
开发者ID:bradkarels,项目名称:strange-symbols,代码行数:34,代码来源:FormController.scala


示例15: ApartmentController

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

import com.google.inject.Inject
import models.{Apartment, ApartmentForm}
import play.api.i18n.{Messages, I18nSupport, MessagesApi}
import play.api.mvc.{Action, Controller}
import services.ApartmentService

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._


class ApartmentController @Inject()(apartmentService: ApartmentService, val messagesApi: MessagesApi) extends Controller with I18nSupport with Secured {

  def dashboard = IsAuthenticated {
  username =>
     implicit request =>
      apartmentService.listAllApartments map {
        apartments => Ok(views.html.apartment(ApartmentForm.form, apartments))
      }
  }

  def addApartment() = Action.async { implicit request =>
    ApartmentForm.form.bindFromRequest.fold(
      errorForm => Future.successful(Ok(views.html.apartment(errorForm, Seq.empty[Apartment]))),
      data => {
        val newApartment = Apartment(0, data.name, data.rooms, data.area)
        apartmentService.addApartment(newApartment).map(res =>
          Redirect(routes.ApartmentController.dashboard()).flashing(Messages("flash.success") -> res)
        )
      })

  }

  def deleteApartment(id: Long) = Action.async { implicit request =>
    apartmentService.deleteApartment(id) map { res =>
      Redirect(routes.ApartmentController.dashboard())

    }

  }
} 
开发者ID:kunalherkal,项目名称:rental-manager,代码行数:43,代码来源:ApartmentController.scala


示例16: AuthenticationController

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

import com.google.inject.Inject
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Controller, Action}
import services.{AdminService}
import views.html



class AuthenticationController @Inject()(adminService: AdminService, val messagesApi: MessagesApi) extends Controller with I18nSupport {

  val loginForm = Form(
    tuple(
      "email" -> text,
      "password" -> text
    ) verifying ("Invalid email or password", result => result match {
      case (email, password) => adminService.authenticate(email, password).isDefined
      case _ => false
    })
  )

  def login = Action { implicit request =>
    Ok(html.login(loginForm))
  }

  def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.login(formWithErrors)),
      user => Redirect(routes.ApartmentController.dashboard).withSession("email" -> user._1))
  }

  def logout = Action {
    Redirect(routes.AuthenticationController.login).withNewSession.flashing(
      "success" -> "You've been logged out")
  }
} 
开发者ID:kunalherkal,项目名称:rental-manager,代码行数:40,代码来源:AuthenticationController.scala


示例17: TenantController

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

import com.google.inject.Inject
import models.{Tenant, TenantForm}
import play.api.i18n.{Messages, I18nSupport, MessagesApi}
import play.api.mvc.{Action, Controller}
import services.TenantService
import play.api.libs.concurrent.Execution.Implicits._

import scala.concurrent.Future


class TenantController @Inject()(tenantService: TenantService, val messagesApi: MessagesApi) extends Controller with I18nSupport with Secured {

  def dashboard = IsAuthenticated {
    username =>
     implicit request =>
      tenantService.listAllTenants map {
      tenants => Ok(views.html.tenant(TenantForm.form, tenants))
    }
  }

  def addTenant() = Action.async { implicit request =>
    TenantForm.form.bindFromRequest.fold(
      errorForm => Future.successful(Ok(views.html.tenant(errorForm, Seq.empty[Tenant]))),
      data => {
        val newTenant = Tenant(0, data.firstName, data.lastName, data.mobile, data.email)
        tenantService.addTenant(newTenant).map(res =>
          Redirect(routes.TenantController.dashboard()).flashing(Messages("flash.success") -> res)
        )
    })
  }

  def deleteTenant(id: Long) = Action.async { implicit request =>
    tenantService.deleteTenant(id) map { res =>
      Redirect(routes.TenantController.dashboard())

    }

  }

} 
开发者ID:kunalherkal,项目名称:rental-manager,代码行数:43,代码来源:TenantController.scala


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


示例19: Products

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

import play.api.mvc.{Action, Controller}
import models.Product
import javax.inject.Inject
import play.api.i18n.{I18nSupport, Messages, MessagesApi}


class Products @Inject()(val messagesApi: MessagesApi, implicit val configuration:play.api.Configuration) extends Controller with I18nSupport{
	def list = Action {request => 
		val products = Product.findAll
		Ok(views.html.products.list(products, Messages("application.name")))
	}

	def show(ean:Long) = Action{implicit request => 
		Product.findByEan(ean).map{ product => 
			Ok(views.html.products.details(product))
			}.getOrElse(NotFound)
	}
} 
开发者ID:WackStr,项目名称:PlayProducts,代码行数:21,代码来源:Products.scala


示例20: TextController

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

import javax.inject.Inject

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

import scala.xml.{Node, Text}


class TextController @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {
  def index() = Action {
    implicit request => val xml : UserXML = xmlForm.bindFromRequest().get
    val p = scala.xml.XML.loadString(xml.xml)
    val pageId = (p \ "state" \ "page-id").text
    val title = (p \ "header" \ "title").text
    val texts = p \ "text"
    var text = texts
    for (e <- texts){
      if ((e \ "@page-id").text == pageId){
        text = e
      }
    }
    val header1 = (text \ "header1").text
    val header2 = (text \ "header2").text
    val tag = (text \ "@tag").text
    val default = (text \ "@default").text
    val accept = "> " + (text \ "@accept").text
    val nextPage = (text \ "next").text

    Ok(views.html.main(title)(content = views.html.text(header1, header2, tag, default, accept, nextPage, xml.xml)))
  }

  def attributeEquals(name: String, value: Text)(node: Node) = node.attributes.exists(_ == value)

  val xmlForm = Form(
    mapping(
      "xml" -> nonEmptyText
    )(UserXML.apply)(UserXML.unapply)
  )
} 
开发者ID:Peantab,项目名称:paragraph-framework,代码行数:44,代码来源:TextController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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