本文整理汇总了Scala中play.api.mvc.Results类的典型用法代码示例。如果您正苦于以下问题:Scala Results类的具体用法?Scala Results怎么用?Scala Results使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Results类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: TokenChecker
//设置package包名称以及导入依赖的类
package controllers.composition
import play.api.mvc.{ActionBuilder, Request, Result, Results}
import play.mvc.Http.Status
import services.cryptography.{JwtTokenGenerator, JwtTokenGeneratorServices}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object TokenChecker extends ActionBuilder[Request] {
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
val token : Option[String] = request.headers.get("token")
if(token.isDefined) {
val jwt : JwtTokenGeneratorServices = new JwtTokenGenerator
val verify = jwt.verifyToken(token.get)
block(request)
}
else {
Future{ Results.Status(Status.UNAUTHORIZED) }
}
}
}
示例2: MyDeadboltHandler
//设置package包名称以及导入依赖的类
package security
import be.objectify.deadbolt.scala.{ DynamicResourceHandler, DeadboltHandler }
import play.api.mvc.{ Request, Result, Results }
import be.objectify.deadbolt.core.models.Subject
import scala.concurrent.{ Future, Await }
import models.UserSecurity
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import dal._
import javax.inject._
import models._
class MyDeadboltHandler(dynamicResourceHandler: Option[DynamicResourceHandler] = None, var rolesListParam: List[SecurityRole] = List()) extends DeadboltHandler {
def beforeAuthCheck[A](request: Request[A]) = Future(None)
override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] = {
Future(dynamicResourceHandler.orElse(Some(new MyDynamicResourceHandler())))
}
override def getSubject[A](request: Request[A]): Future[Option[Subject]] = {
var rol: String = request.session.get("role").get
var user1 = new UserSecurity("steve", rol, rolesListParam)
Future(Some(user1))
}
def onAuthFailure[A](request: Request[A]): Future[Result] = {
Future { Results.Forbidden(views.html.accessFailed()) }
}
}
示例3: DBErrors
//设置package包名称以及导入依赖的类
package models.errors
import play.api.mvc.Results
object DBErrors {
case class BucketClosedError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.ServiceUnavailable(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.BUCKET_CLOSED_ERROR_CODE, devMsg, class_name)
).toJson))
case class CouchbaseError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.ServiceUnavailable(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.COUCHBASE_ERROR_CODE, devMsg, class_name)
).toJson))
case class GeneralServerError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.InternalServerError(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
}
示例4: GeneralErrors
//设置package包名称以及导入依赖的类
package models.errors
import play.api.mvc.Results
object GeneralErrors {
case class AskTimeoutError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.RequestTimeout(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
case class BadJSONError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.BadRequest(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
case class NotFoundError(msg: String, devMsg: String, class_name: String) extends
Error(
Results.NotFound(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
case class CouldNotParseJSON(msg: String, devMsg: String, class_name: String) extends
Error(
Results.InternalServerError(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
case class Forbidden(msg: String, devMsg: String, class_name: String) extends
Error(
Results.Forbidden(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
case class AlreadyExists(msg: String, devMsg: String, class_name: String) extends
Error(
Results.Conflict(
ErrorMsg(
msg, DevMsg(
ErrorsCodes.GENERAL_SERVER_ERROR_CODE, devMsg, class_name)
).toJson))
}
示例5: Tag
//设置package包名称以及导入依赖的类
package controllers
import jp.t2v.lab.play2.auth.{ AsyncIdContainer, AuthConfig, CookieTokenAccessor, CookieIdContainer }
import models.user.Roles._
import models.user.{ UserService, UserWithRoles }
import models.generated.tables.records.{ UserRecord, UserRoleRecord }
import scala.concurrent.{ ExecutionContext, Future }
import scala.reflect.{ ClassTag, classTag }
import play.api.Play
import play.api.cache.CacheApi
import play.api.mvc.{ Result, Results, RequestHeader }
import javax.inject.Inject
trait Security extends AuthConfig { self: HasConfig with HasUserService =>
private val NO_PERMISSION = "No permission"
type Id = String
type User = UserWithRoles
type Authority = Role
val idTag: ClassTag[Id] = classTag[Id]
val sessionTimeoutInSeconds: Int = 3600
def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] =
self.users.findByUsername(id)
def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] = {
val destination = request.session.get("access_uri").getOrElse(my.routes.MyRecogitoController.my.toString)
Future.successful(Results.Redirect(destination).withSession(request.session - "access_uri"))
}
def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
Future.successful(Results.Redirect(landing.routes.LandingController.index))
def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
Future.successful(Results.Redirect(landing.routes.LoginLogoutController.showLoginForm(None)).withSession("access_uri" -> request.uri))
override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] =
Future.successful(Results.Forbidden(NO_PERMISSION))
def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext): Future[Boolean] = Future.successful {
authority match {
case Normal => true
case role: Role => user.hasRole(role)
}
}
override lazy val tokenAccessor = new CookieTokenAccessor(
cookieSecureOption = config.getBoolean("auth.cookie.secure").getOrElse(false),
cookieMaxAge = Some(sessionTimeoutInSeconds)
)
override lazy val idContainer: AsyncIdContainer[Id] = AsyncIdContainer(new CookieIdContainer[Id])
}
示例6: PersonControllerSpec
//设置package包名称以及导入依赖的类
package controllers
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec}
import play.api.mvc.Results
import play.api.test.FakeRequest
import play.api.test.Helpers._
class PersonControllerSpec extends FunSpec with BeforeAndAfter with Results with MockitoSugar {
var controller: PersonController = _
before {
controller = new PersonController
}
describe("#index") {
it("should return OK with 200") {
val request = FakeRequest("GET", "/person/1")
val response = call(controller.get(1), request)
assert(status(response) === OK)
}
}
}
示例7: SettingSpec
//设置package包名称以及导入依赖的类
package httpmock
import play.api.mvc.{RequestHeader, Result, Results}
class SettingSpec extends TestHelper {
describe("Setting()") {
it("can start http service on some port") {
val setting = Setting()
start(setting) { server =>
assert(server.port > 0)
}
}
}
describe("Setting(methods = Set(GET))") {
val setting = Setting(methods = Set(GET))
it("accepts GET [200]") {
start(setting) { server =>
assert(get(server.url).getStatusCode === 200)
}
}
it("rejects POST [404]") {
start(setting) { server =>
assert(post(server.url, "body").getStatusCode === 404)
}
}
}
describe("Setting(handler = ???") {
val handler: PartialFunction[RequestHeader, Result] = {
case h: RequestHeader if h.method == "POST" => Results.Unauthorized
case h: RequestHeader if h.uri.contains("rerorero") => Results.InternalServerError
}
it("responses matched handler results") {
start(Setting(methods = Set(GET, POST), handler = handler)) { server =>
assert(post(server.url, "body").getStatusCode === 401)
assert(get(server.url + "rerorero").getStatusCode === 500)
}
}
it("responses according to methods property if not matched") {
start(Setting(methods = Set(GET), handler = handler)) { server =>
assert(post(server.url, "body").getStatusCode === 404)
assert(get(server.url + "rorerore").getStatusCode === 200)
}
}
}
}
示例8: ApiSpecServer
//设置package包名称以及导入依赖的类
package global
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatestplus.play._
import play.api.GlobalSettings
import play.api.mvc.Results
import play.api.test._
abstract class ApiSpecServer extends PlaySpec with OneServerPerTest with Results with ScalaFutures with IntegrationPatience {
val currentVersion = 1
protected def getFakeApp(global: GlobalSettings): FakeApplication = {
FakeApplication(
additionalConfiguration = Map(
"slick.dbs.default.driver" -> "slick.driver.H2Driver$",
"slick.dbs.default.db.driver" -> "org.h2.Driver",
"slick.dbs.default.db.url" -> "jdbc:h2:mem:play;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE",
"slick.dbs.default.db.user" -> "sa",
"slick.dbs.default.db.password" -> "",
"slick.dbs.default.db.connectionPool" -> "disabled",
"slick.dbs.default.db.keepAliveConnection" -> "true",
"play.evolutions.enabled" -> "false",
"play.evolutions.autoApply" -> "false",
"play.evolutions.autocommit" -> "false"
),
withGlobal = Some(global)
)
}
}
示例9: getToken
//设置package包名称以及导入依赖的类
package services.impl
import java.util.UUID
import com.typesafe.config.Config
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.WSClient
import play.api.mvc.Results
import scala.concurrent.{ ExecutionContext, Future }
def getToken(code: String): Future[String] = {
val tokenResponse = ws.url("https://github.com/login/oauth/access_token").
withQueryString(
"client_id" -> githubClientId,
"client_secret" -> githubClientSecret,
"code" -> code
).
withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON).
post(Results.EmptyContent())
tokenResponse.flatMap { response =>
(response.json \ "access_token").asOpt[String].fold(Future.failed[String](
new IllegalStateException("Sod off!")
)) { accessToken =>
Future.successful(accessToken)
}
}
}
}
示例10: NegociosFunctionalTest
//设置package包名称以及导入依赖的类
package controllers
import org.scalamock.scalatest.MockFactory
import org.scalatest._
import org.scalatest.concurrent.IntegrationPatience
import org.scalatestplus.play._
import play.api.mvc.Results
class NegociosFunctionalTest extends FlatSpec with Matchers with OptionValues
with WsScalaTestClient with BeforeAndAfterEach with BeforeAndAfterAll with Results
with MockFactory with OneServerPerSuite with HtmlUnitFactory with AllBrowsersPerSuite with IntegrationPatience {
override lazy val browsers = Vector(
ChromeInfo,
FirefoxInfo(firefoxProfile),
InternetExplorerInfo
)
override def afterAll(): Unit = {
}
val host = s"http://localhost:$port"
def sharedTests(browser: BrowserInfo) = {
"Index" should s"mostrar los negocios en el listado y cargar la configuracion ${browser.name}" in {
go to s"$host/"
pageTitle shouldBe "Hello MV - Configurador"
click on find(name("configuracion")).value
eventually(currentUrl shouldBe s"$host/negocios/avanza_seguro/configuracion")
}
it should s"cargar un negocio ${browser.name}" in {
go to s"$host/"
pageTitle shouldBe "Hello MV - Configurador"
click on find(name("negocios")).value
eventually(currentUrl shouldBe s"$host/negocios/avanza_seguro")
}
}
override def convertToLegacyEqualizer[T](left: T): LegacyEqualizer[T] = ???
override def convertToLegacyCheckingEqualizer[T](left: T): LegacyCheckingEqualizer[T] = ???
}
示例11: ChirpDeadboltHandler
//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.auth.handlers
import be.objectify.deadbolt.scala.models.Subject
import be.objectify.deadbolt.scala.{AuthenticatedRequest, DeadboltHandler, DynamicResourceHandler}
import com.github.aselab.activerecord.dsl._
import com.google.inject.Inject
import org.birdfeed.chirp.database.models.AccessToken
import org.birdfeed.chirp.errors.JsonError
import play.api.mvc.{Request, Result, Results}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class ChirpDeadboltHandler @Inject() extends DeadboltHandler with JsonError {
// TODO: Do we need these?
override def beforeAuthCheck[A](request: Request[A]): Future[Option[Result]] = Future {None}
override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] = Future {None}
override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] = Future {
for {
headerToken <- request.headers.get("Chirp-Access-Token")
databaseToken <- AccessToken.findBy("token", headerToken)
if databaseToken.stillAlive
} yield databaseToken.user.get
}
// TODO: Permissions error?! NOPE! DEAD ACCESS TOKEN
// fix this and stop giving this error for everything
override def onAuthFailure[A](request: AuthenticatedRequest[A]): Future[Result] = getSubject(request).map {
case Some(subject) => Results.Unauthorized(jsonError("Your access token is expired, please refresh authorization."))
case _ => Results.BadRequest(jsonError("Your access token is invalid."))
}
}
示例12: CarAdvertControllerTest
//设置package包名称以及导入依赖的类
import org.scalatestplus.play._
import play.api.mvc.Results
import controllers.CarAdvertController
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.test.FakeRequest
import repository.DBResource
import scala.concurrent.ExecutionContext
class CarAdvertControllerTest extends PlaySpec with Results with GuiceOneAppPerSuite{
"test create" should {
"should create a new car advert" in {
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
val dbResouce = app.injector.instanceOf[DBResource]
val controller = new CarAdvertController(dbResouce)
val body = controller.create().apply(FakeRequest())
controller.list()
}
}
}
示例13: Tag
//设置package包名称以及导入依赖的类
package controllers.api.auth
import com.github.sample.utils.Loggable
import jp.t2v.lab.play2.auth._
import play.api.mvc.Results.Forbidden
import play.api.mvc.{RequestHeader, Result, Results}
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.{ClassTag, classTag}
trait AuthConfigImpl extends AuthConfig with Loggable{
override type Id = String
override type User = MyUser
override val idTag: ClassTag[Id] = classTag[Id]
override def sessionTimeoutInSeconds: Int = 3600 // 1??
override def resolveUser(id: Id)(implicit context: ExecutionContext): Future[Option[User]] = {
Future.successful(AuthService.userOfId(id))
}
override def loginSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/"))
}
override def logoutSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/login?logout=true"))
}
override def authenticationFailed(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
if(request.acceptedTypes.map(_.toString()).contains("text/html")){
Future.successful(Results.Redirect("/login?failed=true"))
}else{
Future.successful(Results.Unauthorized("Unauthorized"))
}
}
override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Forbidden("No permission"))
}
override def authorize(user: User, authority: Authority)(implicit context: ExecutionContext): Future[Boolean] = Future.successful {
(user.role, authority) match {
case (Administrator, _) => true // Admin?????Action????????
case (NormalUser, NormalUser) => true // ????NormalUser??Action?NormalUser?????????Action?Admin????????????
case _ => false
}
}
override lazy val idContainer: AsyncIdContainer[Id] = AsyncIdContainer(new SessionHandler[Id](CacheImpl.tokenMap, CacheImpl.tokenMap2))
}
object CacheImpl{
val tokenMap: mutable.Map[String, AuthenticityToken] = mutable.Map()
val tokenMap2: mutable.Map[AuthenticityToken, String] = mutable.Map()
}
示例14: ErrorHandler
//设置package包名称以及导入依赖的类
package util
import javax.inject.Singleton
import play.api.http.HttpErrorHandler
import play.api.mvc.{RequestHeader, Result, Results}
import scala.concurrent.Future
@Singleton
class ErrorHandler extends HttpErrorHandler{
override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
Future.successful(
Results.Status(statusCode)("A client error occurred: " + message)
)
}
override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
Future.successful(
Results.InternalServerError("A server error occurred: " + exception.getMessage)
)
}
}
示例15: ApplicationSpec
//设置package包名称以及导入依赖的类
package controllers
import com.knoldus.search.AutoCompleteProcessor
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import play.api.mvc.Results
import play.api.test.{FakeRequest, PlaySpecification, WithApplication}
import org.specs2.mock.Mockito
@RunWith(classOf[JUnitRunner])
class ApplicationSpec extends PlaySpecification with Results with Mockito {
val mockedProcessor = mock[AutoCompleteProcessor]
val mockedJars = mock[WebJarAssets]
val testController = new Application(mockedJars, mockedProcessor)
"Application" should {
"search suggestion" in new WithApplication {
mockedProcessor.getMatches("java") returns List("java", "javascript", "jQuery")
val result = testController.searchText("java").apply(FakeRequest("GET", "/search_text"))
val resultAsString = contentAsString(result)
resultAsString === """["java","javascript","jQuery"]"""
status(result) must be equalTo 200
}
"search movies" in new WithApplication {
mockedProcessor.getMovies("Batman v Superman: Dawn of Justice") returns List("""{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","Released":"25 Mar 2016","Genre":"Action, Adventure, Sci-Fi","Director":"Zack Snyder","Plot":"steel.","Poster":"http://ia.media-imdb.com/images/M/[email protected]_V1_SX300.jpg","imdbRating":"7.0"}""")
val result = testController.searchMovie("Batman v Superman: Dawn of Justice").apply(FakeRequest("GET", "/search_content"))
status(result) must be equalTo 200
}
}
}