本文整理汇总了Scala中play.api.i18n.Messages类的典型用法代码示例。如果您正苦于以下问题:Scala Messages类的具体用法?Scala Messages怎么用?Scala Messages使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Messages类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ContactController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import models.{ContactDB, MongoConnector}
import play.api._
import play.api.i18n.Messages
import play.api.mvc._
import play.api.mvc.{Action, Controller, Flash, Request}
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.Forms.{mapping, nonEmptyText}
import play.api.data.Forms.{longNumber, mapping, nonEmptyText}
import play.api.i18n.Messages.Implicits._
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class ContactController @Inject() extends Controller{
val contactForm = Form(tuple(
"Name" -> text,
"Email" -> text,
"Message" -> text
))
def saveContact = Action {
implicit request =>
val newContactForm = contactForm.bindFromRequest()
newContactForm.fold(success = {
newContact =>
//Create a contact object using form data
val newContactID = ContactDB.findNextID()
print(newContactID)
println(newContact._2)
val newContactRequest = new ContactDB(newContactID, newContact._1, newContact._2, newContact._3)
//Insert into contact collection
MongoConnector.collectionContact.insert(newContactRequest)
Ok(views.html.home())
}, hasErrors = {
form =>
Redirect(routes.ContactController.contact()).flashing(Flash(form.data) + ("error" -> Messages("contact.validation.errors")))
})
}
def contact = Action {
implicit request =>
val form = if (request2flash.get("error").isDefined)
contactForm.bind(request2flash.data)
else
contactForm
Ok(views.html.contact(form))
}
}
示例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))
}
}
示例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"))
}
}
}
}
}
示例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")))
}
}
}
示例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)
}
}
}
}
}
示例6: RichJsError
//设置package包名称以及导入依赖的类
package play.api.libs.json
import play.api.data.validation.ValidationError
import play.api.i18n.Messages
object RichJsError {
def toI18NJson(e: JsError)(messages: Messages): JsObject = toI18NJson(e.errors)(messages)
private def toI18NJson(errors: Seq[(JsPath, Seq[ValidationError])])(messages: Messages): JsObject = {
val argsWrite = Writes.traversableWrites[Any](Writes.anyWrites)
errors.foldLeft(Json.obj()) { (obj, error) =>
obj ++ Json.obj(error._1.toJsonString -> error._2.foldLeft(Json.arr()) { (arr, err) =>
arr :+ JsString( play.api.i18n.Messages(err.messages, err.args)(messages) )
})
}
}
}
示例7: Products
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc._
import javax.inject.Inject
import play.api.i18n.{Messages, MessagesApi, I18nSupport}
import play.api.data.Form
import play.api.data.Forms.{mapping, longNumber, nonEmptyText}
import models.Product
class Products @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def list = Action { implicit request =>
val products = Product.findAll
Ok(views.html.products.list(products))
}
def show(ean: Long) = Action {
implicit request => Product.findByEan(ean).map {
// rendering product details
product => Ok(views.html.products.details(product))
}.getOrElse(NotFound) // return page 404
}
private val productForm: Form[Product] = Form(
mapping(
"ean" -> longNumber.verifying("validation.ean.duplicate", Product.findByEan(_).isEmpty), // form? field? ????
"name" -> nonEmptyText,
"description" -> nonEmptyText
)(Product.apply)(Product.unapply) // form? model ?? mapping
)
def save = Action {
implicit request => val newProductForm = productForm.bindFromRequest()
newProductForm.fold(
hasErrors = {
form => Redirect(routes.Products.newProduct()).
flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
},
success = {
newProduct => Product.add(newProduct)
val message = Messages("products.new.success", newProduct.name)
Redirect(routes.Products.show(newProduct.ean)).flashing("success" -> message)
}
)
}
def newProduct = Action {
implicit request => val form = if (request2flash.get("error").isDefined)
productForm.bind(request2flash.data)
else
productForm
Ok(views.html.products.editProduct(form))
}
}
示例8: 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"))
}
}
}
示例9: Mailer
//设置package包名称以及导入依赖的类
package utils
import javax.inject.Inject
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps
import play.api.Configuration
import play.api.libs.concurrent.Execution.Implicits._
import play.api.i18n.Messages
import play.api.libs.mailer._
import models.Profile
class Mailer @Inject() (configuration:Configuration, mailer:MailerClient) {
val from = configuration.getString("mail.from").get
val replyTo = configuration.getString("mail.reply")
def sendEmailAsync(recipients:String*)(subject:String, bodyHtml:Option[String], bodyText:Option[String]) = {
Future {
sendEmail(recipients:_*)(subject, bodyHtml, bodyText)
} recover {
case e => play.api.Logger.error("error sending email", e)
}
}
def sendEmail(recipients:String*)(subject:String, bodyHtml:Option[String], bodyText:Option[String]) {
val email = Email(subject = subject, from = from, to = recipients, bodyHtml = bodyHtml, bodyText = bodyText, replyTo = replyTo)
mailer.send(email)
()
}
def welcome(profile:Profile, link:String)(implicit messages:Messages) = {
sendEmailAsync(profile.email.get)(
subject = Messages("mail.welcome.subject"),
bodyHtml = Some(views.html.mails.welcome(profile.firstName.get, link).toString),
bodyText = Some(views.html.mails.welcomeText(profile.firstName.get, link).toString)
)
}
def resetPassword(email:String, link:String)(implicit messages:Messages) = {
sendEmailAsync(email)(
subject = Messages("mail.reset.subject"),
bodyHtml = Some(views.html.mails.resetPassword(email, link).toString),
bodyText = Some(views.html.mails.resetPasswordText(email, link).toString)
)
}
}
示例10: 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)))
}
示例11: 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
}
}
示例12: CommentsAction
//设置package包名称以及导入依赖的类
package v1.news
import javax.inject.Inject
import play.api.http.HttpVerbs
import play.api.i18n.{Messages, MessagesApi}
import play.api.mvc._
import play.api.http.HeaderNames
import scala.concurrent.{ExecutionContext, Future}
class CommentsAction @Inject()(messagesApi: MessagesApi)(
implicit ec: ExecutionContext)
extends ActionBuilder[CommentsRequest]
with HttpVerbs {
type CommentsRequestBlock[A] = CommentsRequest[A] => Future[Result]
private val logger = org.slf4j.LoggerFactory.getLogger(this.getClass)
override def invokeBlock[A](request: Request[A],
block: CommentsRequestBlock[A]): Future[Result] = {
if (logger.isTraceEnabled()) {
logger.trace(s"invokeBlock: request = $request")
}
val messages = messagesApi.preferred(request)
val future = block(new CommentsRequest(request, messages))
future.map { result =>
request.method match {
case GET | HEAD =>
result.withHeaders("Cache-Control" -> s"max-age: 100")
case other =>
result
}
}
}
}
示例13: PostAction
//设置package包名称以及导入依赖的类
package v1.post
import javax.inject.Inject
import play.api.http.HttpVerbs
import play.api.i18n.{Messages, MessagesApi}
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
class PostAction @Inject()(messagesApi: MessagesApi)(
implicit ec: ExecutionContext)
extends ActionBuilder[PostRequest]
with HttpVerbs {
type PostRequestBlock[A] = PostRequest[A] => Future[Result]
private val logger = org.slf4j.LoggerFactory.getLogger(this.getClass)
override def invokeBlock[A](request: Request[A],
block: PostRequestBlock[A]): Future[Result] = {
if (logger.isTraceEnabled()) {
logger.trace(s"invokeBlock: request = $request")
}
val messages = messagesApi.preferred(request)
val future = block(new PostRequest(request, messages))
future.map { result =>
request.method match {
case GET | HEAD =>
result.withHeaders("Cache-Control" -> s"max-age: 100")
case other =>
result
}
}
}
}
示例14: 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())
}
}
}
示例15: 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())
}
}
}