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

Scala Results类代码示例

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

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



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


示例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()) }
  }
} 
开发者ID:kapit4n,项目名称:hi-stock,代码行数:34,代码来源:MyDeadboltHandler.scala


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


} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:35,代码来源:DBErrors.scala


示例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))
} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:56,代码来源:GeneralErrors.scala


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

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


示例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)
    }
  }
} 
开发者ID:ysihaoy,项目名称:scala-play-slick,代码行数:27,代码来源:PersonControllerSpec.scala


示例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)
      }
    }
  }
} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:51,代码来源:SettingSpec.scala


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


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


示例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] = ???
} 
开发者ID:luissalda1995,项目名称:generador-vistas,代码行数:49,代码来源:NegociosFunctionalTest.scala


示例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."))
  }
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:35,代码来源:ChirpDeadboltHandler.scala


示例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()
    }
  }
} 
开发者ID:shexiaogui,项目名称:car-adverts,代码行数:22,代码来源:CarAdvertControllerTest.scala


示例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()
} 
开发者ID:tm-sukehiro,项目名称:play2-sandbox,代码行数:62,代码来源:AuthConfigImpl.scala


示例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)
    )
  }
} 
开发者ID:xiren,项目名称:Apollo,代码行数:25,代码来源:ErrorHandler.scala


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

  }

} 
开发者ID:knoldus,项目名称:activator-play-elasticsearch-autocomplete.g8,代码行数:38,代码来源:ApplicationSpec.scala


示例16: WithSession

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

import java.security.SecureRandom

import models.{Session, SessionId}
import play.api.mvc.{Request, Result, Results}
import scalikejdbc._

import scala.util.Try

object WithSession {
  val SessionName = "key"
  val random = new SecureRandom()

  def apply[T](f: Session => Result)(implicit db: DBSession, request: Request[T]): Result = {
    val session = getSession().getOrElse(newSession())
    f(session).withSession(SessionName -> session.id.toString)
  }

  def check[T](f: Session => Result)(implicit db: DBSession, request: Request[T]): Result = {
    getSession().fold(Results.Unauthorized("Session failed")) { session =>
      f(session).withSession(SessionName -> session.id.toString)
    }
  }

  def getSession[T]()(implicit db: DBSession, request: Request[T]): Option[Session] = {
    val id = request.session.get(SessionName).flatMap { it => Try { SessionId(it.toLong) }.toOption }
    id.flatMap(Session.findById)
  }

  def newSession()(implicit db: DBSession): Session = {
    val session = Session(SessionId(random.nextLong()), System.currentTimeMillis())
    session.save()
    session
  }
} 
开发者ID:ponkotuy,项目名称:ponkotuy-travel,代码行数:37,代码来源:WithSession.scala


示例17: ProxyResponse

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

import java.util.concurrent.TimeUnit

import play.api.http.HeaderNames
import play.api.libs.iteratee.Iteratee
import play.api.mvc.{Result, Results}

import scala.concurrent.Await
import scala.concurrent.duration.Duration

object ProxyResponse {

  def apply(result: Result): ProxyResponse = {

    val body = new String(contentAsBytes(result))
    val httpMessage = HttpMessage(result.header.headers.mapValues(_.split(",").toList), Some( body))
    new ProxyResponse(result.header.status, httpMessage)
  }

  private def contentAsBytes(result: Result): Array[Byte] = {
    val eBytes = result.header.headers.get(HeaderNames.TRANSFER_ENCODING) match {
      case Some("chunked") => result.body &> Results.dechunk
      case _ => result.body
    }
      Await.result(eBytes |>>> Iteratee.consume[Array[Byte]](), Duration(1, TimeUnit.SECONDS))
  }
}

case class ProxyResponse(status: Int = 200, httpMessage: HttpMessage = HttpMessage(Map.empty, None)) {

  def simpleHeaderMap: Map[String, String] = {
    httpMessage.headers.map {
      case (k, v) => (k, v.mkString(","))
    }
  }
} 
开发者ID:innoq,项目名称:docster,代码行数:38,代码来源:ProxyResponse.scala


示例18: Http

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support

import play.api.Play.current
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import play.api.mvc.Results
import uk.gov.hmrc.play.http.ws.WSHttpResponse
import uk.gov.hmrc.play.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

object Http {

  def get(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
    request.get()
  }

  def post(url: String, body: String, headers: Seq[(String, String)] = Seq.empty)
          (implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
    request.withHeaders(headers: _*).post(body)
  }

  def postEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
    import play.api.http.Writeable._
    request.post(Results.EmptyContent())
  }

  def putEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
    import play.api.http.Writeable._
    request.put(Results.EmptyContent())
  }

  def delete(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
    request.delete()
  }

  private def perform(url: String)(fun: WSRequest => Future[WSResponse])(implicit hc: HeaderCarrier): WSHttpResponse =
    await(fun(WS.url(url).withHeaders(hc.headers: _*).withRequestTimeout(20000 milliseconds)).map(new WSHttpResponse(_)))

  private def await[A](future: Future[A]) = Await.result(future, Duration(10, SECONDS))
}

class Resource(path: String, port: Int) {
  private def url() = s"http://localhost:$port$path"

  def get()(implicit hc: HeaderCarrier = HeaderCarrier()) = Http.get(url)(hc)

  def postAsJson(body: String)(implicit hc: HeaderCarrier = HeaderCarrier()) =
    Http.post(url, body, Seq(HeaderNames.CONTENT_TYPE -> MimeTypes.JSON))(hc)

  def postEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
    Http.postEmpty(url)(hc)

  def putEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
    Http.putEmpty(url)(hc)
} 
开发者ID:hmrc,项目名称:agent-invitations,代码行数:59,代码来源:Http.scala


示例19: DeadboltHandlerImpl

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

import javax.inject.{ Inject, Singleton }

import be.objectify.deadbolt.scala.models.Subject
import be.objectify.deadbolt.scala.{ AuthenticatedRequest, DeadboltHandler, DynamicResourceHandler }
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.util.ExtractableRequest
import models.services.UserService
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Request, Result, Results }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


@Singleton
class DeadboltHandlerImpl @Inject() (val messagesApi: MessagesApi, silhouette: Silhouette[DefaultEnv], userService: UserService)
  extends DeadboltHandler with I18nSupport {

  override def beforeAuthCheck[A](request: Request[A]): Future[Option[Result]] = Future.successful(None)

  override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] = {
    implicit val extractableRequest = new ExtractableRequest(request)
    silhouette.env.authenticatorService.retrieve.flatMap {
      case Some(authenticator) =>
        userService.retrieve(authenticator.loginInfo)
      case None => Future.successful(None)
    }
  }

  override def onAuthFailure[A](request: AuthenticatedRequest[A]): Future[Result] = {
    println("Deadbolt: onAuthFailure triggered!")
    Future.successful(Results.Unauthorized) // todo or does this need to accept?
  }

  override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] =
    Future.successful(None)
} 
开发者ID:dexmo007,项目名称:play-sil-seed-exp,代码行数:41,代码来源:DeadboltHandlerImpl.scala


示例20: Auth

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

import javax.inject.{Inject, Singleton}

import be.objectify.deadbolt.scala.DeadboltActions
import com.mohiva.play.silhouette.api.Silhouette
import models.Roles
import play.api.mvc.{BodyParser, BodyParsers, Result, Results}
import utils.auth.DefaultEnv

import scala.concurrent.Future


@Singleton
class Auth @Inject()(deadboltActions: DeadboltActions, silhouette: Silhouette[DefaultEnv])
  extends Results with BodyParsers {

  def SubjectPresent[B](parser: BodyParser[B] = parse.anyContent)(block: SecureRequest[B] => Future[Result]) =
    silhouette.SecuredAction.async(parser) { implicit req =>
      deadboltActions.SubjectPresent()(parser)(block.compose(_ => new SecureRequest(req)))(req)
    }

  def Restrict[B](parser: BodyParser[B] = parse.anyContent)(role: Roles.Role)(block: SecureRequest[B] => Future[Result]) =
    silhouette.SecuredAction.async(parser) { implicit request =>
      deadboltActions.Restrict(role.group)(parser)(block.compose(_ => new SecureRequest(request)))(request)
    }

} 
开发者ID:dexmo007,项目名称:play-sil-seed-exp,代码行数:29,代码来源:Auth.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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