本文整理汇总了Scala中play.api.mvc.Action类的典型用法代码示例。如果您正苦于以下问题:Scala Action类的具体用法?Scala Action怎么用?Scala Action使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Action类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: VersionController
//设置package包名称以及导入依赖的类
package controllers
import git.GitInfo
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
class VersionController extends Controller {
def index = Action {
Ok(
Json.obj(
"lastCommit" -> Json.obj(
"branch" -> GitInfo.currentBranch(),
"message" -> GitInfo.lastRevCommitMessage(),
"author" -> GitInfo.lastRevCommitAuthor(),
"hash" -> GitInfo.lastRevCommitName(),
"date" -> GitInfo.lastRevCommitTime()
))
)
}
}
示例2: EventsController
//设置package包名称以及导入依赖的类
package controllers.api
import javax.inject.{Inject, Singleton}
import models.ZWayEvent
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.mvc.Action
import scala.concurrent.Future
@Singleton
class EventsController @Inject()(
val messagesApi: MessagesApi
) extends ApiController {
var events:List[ZWayEvent] = List.empty
def home() = Action {
Ok("RPi Play Framework ZWay demo")
}
def all() = Action {
Ok(Json.toJson(events))
}
def create() = Action.async(apiJson[ZWayEvent]) { req =>
val event = req.body
logger.debug("postEvent: " + event)
events = events :+ event
Future.successful(Ok(Json.obj()))
}
}
示例3: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import models.{ProjectRepo, TaskRepo}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{Action, Controller}
class Application @Inject()( projectRepo: ProjectRepo, taskRepo: TaskRepo)
extends Controller {
def addTaskToProject(color: String, projectId: Long) = Action.async { implicit rs =>
projectRepo.addTask(color, projectId)
.map{ _ => Redirect(routes.Application.projects(projectId)) }
}
def modifyTask(taskId: Long, color: Option[String]) = Action.async { implicit rs =>
taskRepo.partialUpdate(taskId, color, None, None).map(i =>
Ok(s"Rows affected : $i"))
}
def createProject(name: String)= Action.async { implicit rs =>
projectRepo.create(name)
.map(id => Ok(s"project $id created") )
}
def listProjects = Action.async { implicit rs =>
projectRepo.all
.map(projects => Ok(views.html.projects(projects)))
}
def projects(id: Long) = Action.async { implicit rs =>
for {
Some(project) <- projectRepo.findById(id)
tasks <- taskRepo.findByProjectId(id)
} yield Ok(views.html.project(project, tasks))
}
def delete(name: String) = Action.async { implicit rs =>
projectRepo.delete(name).map(num => Ok(s"$num projects deleted"))
}
}
示例4: UsersController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import database.UsersCollection
import models.User
import play.api.libs.json.JsValue
import play.api.mvc.{Action, BaseController, ControllerComponents}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class UsersController @Inject()(
val controllerComponents: ControllerComponents,
users: UsersCollection
)(implicit ec: ExecutionContext) extends BaseController {
def create: Action[JsValue] = Action.async(parse.json) { request =>
request.body.asOpt[User] match {
case Some(user) => users.insert(user).map(if(_) Created else InternalServerError)
case None => Future.successful(BadRequest)
}
}
def read(id: String) = Action {
users.find(id)
Ok
}
}
示例5: authenticate
//设置package包名称以及导入依赖的类
package controllers.auth
import javax.inject.Inject
import services.user.UserService
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.impl.providers._
import controllers.WebJarAssets
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, Controller }
import utils.auth.DefaultEnv
import scala.concurrent.Future
def authenticate(provider: String) = Action.async { implicit request =>
(socialProviderRegistry.get[SocialProvider](provider) match {
case Some(p: SocialProvider with CommonSocialProfileBuilder) =>
p.authenticate().flatMap {
case Left(result) => Future.successful(result)
case Right(authInfo) => for {
profile <- p.retrieveProfile(authInfo)
user <- userService.save(profile)
authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
value <- silhouette.env.authenticatorService.init(authenticator)
result <- silhouette.env.authenticatorService.embed(value, Redirect(controllers.profile.routes.CustomerProfileController.edit()))
} yield {
silhouette.env.eventBus.publish(LoginEvent(user, request))
result
}
}
case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
case e: ProviderException =>
logger.error("Unexpected provider error", e)
Redirect(routes.SignInController.view()).flashing("error" -> Messages("could.not.authenticate"))
}
}
}
示例6: ContactUsController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import model.ContactFormTemplate
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.Play.current
import play.api.data.validation._
import play.api.i18n.Messages.Implicits._
import services._
import scala.concurrent.Future
class ContactUsController @Inject()(validator: Validation) extends Controller {
val contactUsForm: Form[ContactFormTemplate] = Form(
mapping(
"name" -> nonEmptyText(maxLength = 20),
"email" -> nonEmptyText(maxLength = 30).verifying(validator.emailCheckConstraint),
"description" -> nonEmptyText(maxLength = 50)
)(ContactFormTemplate.apply)(ContactFormTemplate.unapply)
)
def entry = Action {
Ok(views.html.contact(contactUsForm))
}
def postForm = Action.async { implicit request =>
println(request.body)
contactUsForm.bindFromRequest.fold(
formWithErrors => {
Future.successful(BadRequest(views.html.contact(formWithErrors)))
},
UserData => {
Future.successful(Redirect(routes.ContactUsController.success(UserData.name, UserData.email, UserData.description)))
}
)
}
def success(name: String, email: String, description: String) = Action {
Ok(views.html.contactFormConfirmation(name, email, description))
}
}
示例7: ItemController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.github.tototoshi.play2.json4s.native.Json4s
import models.{Item, ItemDetail}
import org.json4s.{DefaultFormats, Extraction}
import parsers.ItemParser
import play.api.mvc.{Action, Controller}
import requests.UploadZipItemForm
import scalikejdbc.DB
class ItemController @Inject()(json4s: Json4s) extends Controller {
import json4s._
import Responses._
import models.PersistItem.getItemId
implicit val formats = DefaultFormats
def list() = Action {
import models.Aliases.i
val items = Item.findAll(i.name :: Nil)
Ok(Extraction.decompose(items))
}
def show(itemId: Long) = Action {
Item.findById(itemId).fold(notFound(s"itemId = ${itemId}")) { item =>
Ok(Extraction.decompose(item))
}
}
def upload() = Action(parse.multipartFormData){ implicit req =>
UploadZipItemForm.fromReq(req).fold(BadRequest("Form error")){ form =>
DB localTx { implicit session =>
ZipUtil.inputStreams(form.file.ref.file).foreach{ is =>
ItemParser.parse(is).foreach{ item =>
val itemId = getItemId(item.name)
ItemDetail.deleteById(itemId)
ItemDetail.create(item.detail(itemId))
}
}
}
Redirect(routes.MyAssets.at("uploader.html"))
}
}
}
示例8: ReportsController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import play.api.libs.functional.syntax._
import play.api.libs.json._
import play.api.mvc.{Action, AnyContent, Controller}
import repository.ReportRepository
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class ReportsController @Inject()(reportRepository: ReportRepository) extends Controller {
def getCountriesWithHigestAirports: Action[AnyContent] = Action.async { implicit request =>
reportRepository.findCountriesWithHighestNoOfAirports.map { report => {
Ok(views.html.reports.countries.airports("Countries with highest no of airports", Json.toJson(report)))
}
}
}
def getCountriesWithLowestAirports: Action[AnyContent] = Action.async { implicit request =>
reportRepository.findCountriesWithLowestNoOfAirports.map { report =>
Ok(views.html.reports.countries.airports("Countries with lowest no of airports", Json.toJson(report)))
}
}
def getSurfacesPerCountry: Action[AnyContent] = Action.async { implicit request =>
reportRepository.findSurfacesPerCountry.map {
report => Ok(views.html.reports.countries.surfaces("Countries and runway surfaces", Json.toJson((report))))
}
}
def getCommonRunwayIdentifications: Action[AnyContent] = Action.async { implicit request =>
reportRepository.findCommonRunwayIdentifications.map {
report => Ok(views.html.reports.commonIdents("Most common runway identifications", Json.toJson((report))))
}
}
}
示例9: CompanyController
//设置package包名称以及导入依赖的类
package controllers
import config.DBSchema
import models.{Company, User}
import org.squeryl.PrimitiveTypeMode._
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
object CompanyController extends Controller{
def companyList = Action {
implicit val barWrites = Json.writes[Company]
implicit val barWrites2 = Json.writes[User]
val json = inTransaction {
val companys = from(DBSchema.companyTable)(
companyTable => select(companyTable)
)
for(i <- companys.toList){
val user = i.userList.toList
val temp = "chang"
}
Json.toJson(companys)
}
Ok(json)
}
}
示例10: cached
//设置package包名称以及导入依赖的类
package helpers
import javax.inject.{Inject, Singleton}
import play.api.cache.{CacheApi, _}
import play.api.mvc.{Action, AnyContent}
import scala.concurrent.duration._
import scala.reflect.ClassTag
def cached(key: String, expiration: Duration = 4 hours)(response: => Action[AnyContent]) = {
getOrElse(key) {
val result = response()
set(key, result, expiration)
result
}
}
}
@Singleton
class SemesterModeCache @Inject()(@NamedCache("semester-mode-cache") semesterModeCache: CacheApi) extends CacheHelper {
cache = semesterModeCache
}
@Singleton
class SessionCache @Inject()(@NamedCache("session-cache") sessionCache: CacheApi) extends CacheHelper {
cache = sessionCache
}
示例11: Barcodes
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc.{Action, Controller}
class Barcodes extends Controller {
val ImageResolution = 144
// png? ???? Action
def barcode(ean: Long) = Action {
import java.lang.IllegalArgumentException
val MimeType = "image/png"
try {
val imageData = ean13BarCode(ean, MimeType)
Ok(imageData).as(MimeType)
}
catch {
case e: IllegalArgumentException =>
BadRequest("Couldn't generate bar code. Error: " + e.getMessage)
}
}
def ean13BarCode(ean: Long, mimeType: String): Array[Byte] = {
import java.io.ByteArrayOutputStream
import java.awt.image.BufferedImage
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
import org.krysalis.barcode4j.impl.upcean.EAN13Bean
val output: ByteArrayOutputStream = new ByteArrayOutputStream
val canvas: BitmapCanvasProvider = new BitmapCanvasProvider(
output, mimeType, ImageResolution, BufferedImage.TYPE_BYTE_BINARY, false, 0)
val barcode = new EAN13Bean()
barcode.generateBarcode(canvas, String valueOf ean)
canvas.finish
output.toByteArray
}
}
示例12: UsersController
//设置package包名称以及导入依赖的类
package controllers
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{Action, Controller}
import models.{User, Users}
class UsersController(userServices: Users) extends Controller {
implicit val userWrites: Writes[User] = Json.writes[User]
implicit val userReads: Reads[User] = (
Reads.pure(0L) and
(JsPath \ "name").read[String] and
(JsPath \ "isActive").read[Boolean]
)(User.apply _)
def get(id: Long) = Action { request =>
userServices.find(id) match {
case None => NotFound
case Some(user) => Ok(Json.toJson(user))
}
}
def create = Action(parse.json) { request =>
Json.fromJson[User](request.body).fold(
invalid => BadRequest,
user => {
val userCreated = userServices.create(user)
Created.withHeaders(LOCATION -> s"/users/${userCreated.id}")
}
)
}
def delete(id: Long) = Action { request =>
userServices.find(id) match {
case None => NotFound
case Some(user) =>
userServices.delete(user)
NoContent
}
}
def update(id: Long) = Action(parse.json) { request =>
Json.fromJson[User](request.body).fold(
invalid => BadRequest,
user => {
userServices.update(user.copy(id = id))
NoContent
}
)
}
}
示例13: StashController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc
import play.api.mvc.{Action, AnyContent, Controller, Result}
import services.{Constants, JsonConverter, Stash, StashStore}
import scala.concurrent.Future
@Singleton
class StashController @Inject()(stashStore: StashStore, jsonConverter: JsonConverter) extends Controller {
def addStash = Action.async(request => {
validateStashAndRespond(request, (stash) => stashStore.addStash(stash).map(addedStash => Ok(Json.toJson[Stash](addedStash))))
})
def index = Action.async(request => {
stashStore.getStashes().map(stashes => Ok(Json.toJson(stashes)))
})
def getStash(id: String) = Action.async(request =>
stashStore.getStash(id).map {
case Some(retrievedStash) => Ok(Json.toJson[Stash](retrievedStash))
case None => NotFound
}
)
def updateStash = Action.async(request => {
validateStashAndRespond(request, (stash) => stashStore.updateStash(stash).map(updatedStash => Ok(Json.toJson[Stash](updatedStash))))
})
private def validateStashAndRespond(request: mvc.Request[AnyContent], responseAction: (Stash) => Future[Result]): Future[Result] = {
request.body.asJson match {
case None => Future.successful(BadRequest(Constants.noValidJsonMessage))
case Some(json) =>
val stash = jsonConverter.getStashFromRequestBody(json)
stash match {
case Some(value) => responseAction(value)
case None => Future.successful(BadRequest(json))
}
}
}
}
示例14: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.mvc.{ Action, Controller }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
import models._
import models.JsonFormats._
class Application @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents {
def getHotels = Action.async {
db.collection("hotels").find(Json.obj()).cursor[Hotel]()
.collect[List]().map {hotels => Ok(Json.toJson(hotels))}
}
def findByCityName(cityName : String) = Action.async {
db.collection("hotels").find(Json.obj("city" -> cityName)).cursor[Hotel]()
.collect[List]().map (hotels => Ok(Json.toJson(hotels)))
}
}
示例15: HelpController
//设置package包名称以及导入依赖的类
package controllers.help
import controllers.{ HasVisitLogging, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.visit.VisitService
import play.api.mvc.{ Action, Controller, RequestHeader }
import play.twirl.api.HtmlFormat
@Singleton
class HelpController @Inject() (
implicit val visits: VisitService,
implicit val webjars: WebJarAssets
) extends Controller with HasVisitLogging {
private def result(template: HtmlFormat.Appendable)(implicit request: RequestHeader) = {
logPageView()
Ok(template)
}
def index = Action { Redirect(routes.HelpController.showTutorial()) }
def showTutorial = Action { implicit request => result(views.html.help.tutorial()) }
def showLocalizedTutorial(lang: String) = Action { implicit request =>
lang.toUpperCase match {
case "DE" => result(views.html.help.tutorial_de())
case "ES" => result(views.html.help.tutorial_es())
case "IT" => result(views.html.help.tutorial_it())
case _ => NotFound(views.html.error404())
}
}
def showFAQ = Action { implicit request => result(views.html.help.faq()) }
def showAbout = Action { implicit request => result(views.html.help.about()) }
}