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

Scala HeaderNames类代码示例

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

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



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

示例1: myPublicAddress

//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec

import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }

trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
  def myPublicAddress(): String
  implicit val portNumber: PortNumber

  def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
    implicit val wSClient = app.injector.instanceOf[WSClient]
    val callbackURL = s"http://${myPublicAddress()}/callback"
    whenReady(
      wsUrl(testPaymentGatewayURL)
        .withQueryStringParameters("callbackURL" -> callbackURL)
        .withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
        .get(),
      Interval(Span(10, Seconds))
    ) { result =>
        result
      }
  }
} 
开发者ID:zalando-incubator,项目名称:hutmann,代码行数:29,代码来源:PlayUnitSpec.scala


示例2: CustomCORSFilter

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

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result}
import play.filters.cors.CORSFilter

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class CustomCORSFilter @Inject()(corsFilter: CORSFilter)
                                (implicit override val mat: Materializer,
                                 exec: ExecutionContext) extends Filter {

  override def apply(nextFilter: RequestHeader => Future[Result])
                    (requestHeader: RequestHeader): Future[Result] = {
    requestHeader.headers.get(HeaderNames.ORIGIN) match {
      case (Some("null")) =>
        val newHeaders = requestHeader.headers
          .remove(HeaderNames.ORIGIN)
          .add(HeaderNames.ORIGIN -> "http://file.url.local.null")
        val mappedOrigin = requestHeader.copy(headers = newHeaders)
        corsFilter(nextFilter)(mappedOrigin)
          .map { result =>
            result.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "null")
          }
      case _ => corsFilter(nextFilter)(requestHeader)
    }
  }
} 
开发者ID:umbc-cmcs447-grp,项目名称:rest-api,代码行数:34,代码来源:CustomCORSFilter.scala


示例3: PlaySpecApplication

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

import org.scalatestplus.play.PlaySpec
import play.api.http.{ HeaderNames, HttpProtocol, HttpVerbs, Status }
import play.api.test._

class PlaySpecApplication extends PlaySpec
    with PlayRunners
    with HeaderNames
    with Status
    with HttpProtocol
    with DefaultAwaitTimeout
    with ResultExtractors
    with Writeables
    with RouteInvokers
    with FutureAwaits
    with HttpVerbs 
开发者ID:cm-wada-yusuke,项目名称:ecn-news,代码行数:18,代码来源:PlaySpecApplication.scala


示例4: MultipartFormDataWritable

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

import java.nio.file.{ Files, Paths }

import akka.util.ByteString
import play.api.http.{ HeaderNames, Writeable }
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{ Codec, MultipartFormData }


object MultipartFormDataWritable {

  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]): ByteString = {
    val dataParts = data.flatMap {
      case (key, values) =>
        values.map { value =>
          val name = s""""$key""""
          s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
        }
    }.mkString("")
    val bytes: ByteString = Codec.utf_8.encode(dataParts)
    bytes
  }

  def filePartHeader(file: FilePart[TemporaryFile]): ByteString = {
    val name = s""""${file.key}""""
    val filename = s""""${file.filename}""""
    val contentType = file.contentType.map { ct =>
      s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
    }.getOrElse("")
    Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
  }

  val singleton = Writeable[MultipartFormData[TemporaryFile]](
    transform = { form: MultipartFormData[TemporaryFile] =>
    formatDataParts(form.dataParts) ++
      form.files.flatMap { file =>
        val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
        filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
      } ++
      Codec.utf_8.encode(s"--$boundary--")
  },
    contentType = Some(s"multipart/form-data; boundary=$boundary")
  )
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:49,代码来源:MultipartFormDataWritable.scala


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


示例6: ControllerTest

//设置package包名称以及导入依赖的类
package play.api.mvc.hal

import org.scalatest.{ FunSuite, Matchers }
import play.api.http.{ HeaderNames, Status }
import play.api.libs.json.Json
import play.api.mvc.{ Controller, Result }
import play.api.test.{ DefaultAwaitTimeout, FakeRequest, ResultExtractors }

import scala.concurrent.Future

class ControllerTest extends FunSuite with Matchers with ResultExtractors with HeaderNames with Status with DefaultAwaitTimeout {

  class TestController() extends Controller with HalWriteController

  test("A HAL Resource should be writeable") {
    val controller = new TestController()
    val result: Future[Result] = controller.hal().apply(FakeRequest())
    val bodyText: String = contentAsString(result)
    contentType(result) should equal(Some("application/hal+json"))
    (Json.parse(bodyText) \ "foo").as[String] should equal("bar")
  }

  test("A Resource can be retrived as JSON") {
    val controller = new TestController()
    val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/json"))
    contentType(result) should equal(Some("application/json"))
  }

  test("A Resource can be retrived as HAL") {
    val controller = new TestController()
    val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/hal+json"))
    contentType(result) should equal(Some("application/hal+json"))
  }

} 
开发者ID:hmrc,项目名称:play-hal,代码行数:36,代码来源:ControllerTest.scala


示例7: RouteService

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

import javax.inject.Inject

import models.{Route, Vehicle}
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.http.HeaderNames
import play.api.http.ContentTypes

import scala.concurrent.{ExecutionContext, Future}

class RouteService @Inject() (ws: WSClient) {
  private val BASE_URL = "http://m.cdsvyatka.com/tratata.php"
  private val ROUTE_PARAM_NAME = "marsh"
  private val REFERER = "http://m.cdsvyatka.com/mobile_map.php"


  private def parseResponse(res: WSResponse): Seq[Vehicle] = {
    res.json.validate[Map[String, Vehicle]].fold(_ => Seq.empty, _.values.toSeq)
  }

  def routeVehicles(route: Route)(implicit ec: ExecutionContext): Future[Seq[Vehicle]] = {
    ws.url(BASE_URL)
      .withQueryString(ROUTE_PARAM_NAME -> route.id.toString)
      .withHeaders(HeaderNames.ACCEPT -> ContentTypes.JSON, HeaderNames.REFERER -> REFERER)
      .get()
      .map(parseResponse)
  }
} 
开发者ID:watchbus,项目名称:play-watchbus,代码行数:30,代码来源:RouteService.scala


示例8: asResult

//设置package包名称以及导入依赖的类
package microtools.hateoas

import play.api.http.HeaderNames
import play.api.libs.json.{Json, Writes}
import play.api.mvc.{Result, Results}

trait BusinessResult {
  def asResult: Result
}

object BusinessResult {
  def ok[D](data: D, allowesActions: Seq[BusinessAction] = Seq.empty, etag: Option[String] = None)(
      implicit linkBuilder: LinkBuilder,
      writes: Writes[D]
  ): BusinessResult =
    new BusinessResult {
      override def asResult: Result = {
        val headers = etag.map(HeaderNames.ETAG -> _).toSeq
        Results
          .Ok(JsonTransformers.addHAL(Json.toJson(data), allowesActions))
          .withHeaders(headers: _*)
      }
    }

  def created(selfAction: BusinessAction)(implicit linkBuilder: LinkBuilder): BusinessResult =
    new BusinessResult {
      override def asResult: Result = {
        val headers = Seq(HeaderNames.LOCATION -> linkBuilder.actionLink(selfAction).href)
        Results.Created.withHeaders(headers: _*)
      }
    }

  def created[D](
      selfAction: BusinessAction,
      data: D,
      allowesActions: Seq[BusinessAction] = Seq.empty
  )(
      implicit linkBuilder: LinkBuilder,
      writes: Writes[D]
  ): BusinessResult =
    new BusinessResult {
      override def asResult: Result = {
        val headers = Seq(HeaderNames.LOCATION -> linkBuilder.actionLink(selfAction).href)
        Results
          .Created(JsonTransformers.addHAL(Json.toJson(data), allowesActions))
          .withHeaders(headers: _*)
      }
    }

  def deleted(): BusinessResult =
    new BusinessResult {
      override def asResult: Result = Results.NoContent
    }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:55,代码来源:BusinessResult.scala


示例9: WSClientWithFlow

//设置package包名称以及导入依赖的类
package microtools.ws

import microtools.models.{AuthRequestContext, ExtraHeaders, RequestContext, ServiceName}
import play.api.http.HeaderNames
import play.api.libs.ws.{WSClient, WSRequest}

class WSClientWithFlow(val underlying: WSClient) {
  private[this] object ForwardProto extends Enumeration {
    type Type = Value

    val HTTP  = Value("http")
    val HTTPS = Value("https")
  }

  def url(rawUrl: String)(implicit ctx: RequestContext): WSRequest = {
    val (url, forwardProto): (String, ForwardProto.Type) =
      if (rawUrl.startsWith("https:"))
        s"http:${rawUrl.drop(6)}" -> ForwardProto.HTTPS
      else rawUrl                 -> ForwardProto.HTTP

    underlying
      .url(url)
      .withHeaders(ExtraHeaders.FLOW_ID_HEADER   -> ctx.flowId,
                   HeaderNames.X_FORWARDED_PROTO -> forwardProto.toString)
  }

  def urlWithAuthFromContext(rawUrl: String)(implicit ctx: AuthRequestContext): WSRequest = {
    url(rawUrl)
      .withHeaders(HeaderNames.AUTHORIZATION -> s"Bearer ${ctx.token}")
  }

  def urlWithServiceAuth(rawUrl: String)(implicit serviceName: ServiceName,
                                         ctx: RequestContext): WSRequest = {
    url(rawUrl)
      .withHeaders(
        ExtraHeaders.AUTH_SUBJECT_HEADER -> s"service/$serviceName"
      )
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:40,代码来源:WSClientWithFlow.scala


示例10: basic644

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

import com.google.common.base.Charsets
import com.google.common.io.BaseEncoding
import org.scalatest.Suite
import play.api.http.HeaderNames
import play.api.libs.ws.WSResponse
import play.utils.UriEncoding
import uk.gov.hmrc.fileupload.{EnvelopeId, FileId, FileRefId}

trait FileActions extends ActionsSupport {
  this: Suite =>

  def basic644(s:String): String = {
    BaseEncoding.base64().encode(s.getBytes(Charsets.UTF_8))
  }

  def urlEncode(fileId: FileId) = UriEncoding.encodePathSegment(fileId.value, "UTF-8")


  def upload(data: Array[Byte], envelopeId: EnvelopeId, fileId: FileId, fileRefId: FileRefId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/$fileRefId")
      .withHeaders("Content-Type" -> "application/octet-stream")
      .put(data)
      .futureValue

  def delete(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}")
      .delete()
      .futureValue

  def download(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/content").withHeaders(HeaderNames.AUTHORIZATION -> ("Basic " + basic644("yuan:yaunspassword")))
      .get()
      .futureValue

  def getFileMetadataFor(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/metadata")
      .get()
      .futureValue

  def downloadEnvelope(envelopeId: EnvelopeId): WSResponse =
    client
      .url(s"$fileTransferUrl/envelopes/$envelopeId")
      .get()
      .futureValue
} 
开发者ID:hmrc,项目名称:file-upload,代码行数:52,代码来源:FileActions.scala


示例11: Mobile

//设置package包名称以及导入依赖的类
package lila.api

import org.joda.time.DateTime
import play.api.http.HeaderNames
import play.api.mvc.RequestHeader

import lila.common.ApiVersion

object Mobile {

  object Api {

    case class Old(
      version: ApiVersion,
      // date when a newer version was released
      deprecatedAt: DateTime,
      // date when the server stops accepting requests
      unsupportedAt: DateTime
    )

    val currentVersion = ApiVersion(2)

    val acceptedVersions: Set[ApiVersion] = Set(1, 2) map ApiVersion.apply

    val oldVersions: List[Old] = List(
      Old( // chat messages are html escaped
        version = ApiVersion(1),
        deprecatedAt = new DateTime("2016-08-13"),
        unsupportedAt = new DateTime("2016-11-13")
      )
    )

    private val PathPattern = """^.+/socket/v(\d+)$""".r

    def requestVersion(req: RequestHeader): Option[ApiVersion] = {
      val accepts = ~req.headers.get(HeaderNames.ACCEPT)
      if (accepts contains "application/vnd.lichess.v2+json") Some(ApiVersion(2))
      else if (accepts contains "application/vnd.lichess.v1+json") Some(ApiVersion(1))
      else req.path match {
        case PathPattern(version) => parseIntOption(version) map ApiVersion.apply
        case _ => None
      }
    } filter acceptedVersions.contains

    def requested(req: RequestHeader) = requestVersion(req).isDefined
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:48,代码来源:Mobile.scala


示例12: fetch

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

import com.google.inject.Inject
import play.api.Logger
import play.api.http.HeaderNames
import play.api.i18n.Lang
import play.api.libs.json.{JsError, JsSuccess, Json, Reads}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.{Cookie, Cookies}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.control.NonFatal


trait WsConsumer {
  def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang): Future[T]
}

class WsConsumerImpl @Inject()(ws: WSClient) extends WsConsumer {
  val log = Logger("WsConsumer")

  override def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang) =
    ws.url(url).
      withCookies(Cookie("PLAY_LANG", lang.language)).
      withRequestTimeout(timeout).
      get().flatMap { result =>
      Json.fromJson(result.json) match {
        case JsSuccess(s, _) =>
          Future.successful(s)
        case JsError(e) =>
          val errors = JsError.toJson(e).fields.foldLeft("")((acc, next) => acc + next + "\n")
          Future.failed(new RuntimeException(s"Failed to unmarshal:\n $errors"))
      }
    }.recoverWith {
      case NonFatal(t) =>
        log.warn(s"Failed to fetch '$url'")
        Future.failed(new RuntimeException(t))
    }

  implicit class WithCookiesOps(requestHolder: WSRequest) {
    def withCookies(cookies: Cookie*): WSRequest = {
      val encoded = Cookies.encodeSetCookieHeader(cookies.toSeq)
      requestHolder.withHttpHeaders(HeaderNames.COOKIE -> encoded)
    }
  }

} 
开发者ID:splink,项目名称:pagelets-seed,代码行数:49,代码来源:WsConsumer.scala


示例13: TestComponents

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

import com.malliina.play.http.{PlayUtils, Proxies}
import play.api.ApplicationLoader.Context
import play.api.http.{HeaderNames, Writeable}
import play.api.libs.json.Json
import play.api.mvc._
import play.api.routing.Router
import play.api.test.FakeRequest
import play.api.{BuiltInComponentsFromContext, Configuration}

class TestComponents(ctx: Context) extends BuiltInComponentsFromContext(ctx) {

  import play.api.routing.sird._

  override lazy val configuration: Configuration = ctx.initialConfiguration ++ Configuration(
    "play.http.forwarded.version" -> "x-forwarded",
    "play.http.forwarded.trustedProxies" -> List("0.0.0.0/0", "::/0")
  )

  override def router: Router = Router.from {
    case GET(p"/") => securityCheck(_.secure)
    case GET(p"/mod") => securityCheck(Proxies.isSecure)
  }

  def securityCheck(isSecure: RequestHeader => Boolean) = Action { req =>
    Results.Ok(Json.obj(
      "secure" -> isSecure(req),
      "headers" -> PlayUtils.headersString(req))
    )
  }
}

class SiloTest extends AppSuite(new TestComponents(_)) {

  import play.api.test.Helpers._

  test("play says secure is false despite https in trusted proxy") {
    assert(!makeReq("/"))
  }

  test("Proxies.isSecure says https") {
    assert(makeReq("/mod"))
  }

  def makeReq(url: String) = {
    val reqHeaders = Headers(
      HeaderNames.X_FORWARDED_PROTO -> "https",
      HeaderNames.X_FORWARDED_FOR -> "10.0.0.1"
    )
    val res = makeRequest(FakeRequest(GET, url, reqHeaders, AnyContentAsEmpty))
    assert(res.header.status === 200)
    val json = contentAsJson(fut(res))
    (json \ "secure").as[Boolean]
  }

  def makeRequest[T: Writeable](req: Request[T]): Result =
    await(route(app, req).get)
} 
开发者ID:malliina,项目名称:pics,代码行数:60,代码来源:SiloTest.scala


示例14: sendFile

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

import java.io.File
import java.nio.file.{Files, Path}

import akka.stream.scaladsl.FileIO
import play.api.http.{HeaderNames, HttpEntity, HttpProtocol, MimeTypes}
import play.api.mvc.{Request, ResponseHeader, Result, Results}


trait FileUploadingService {

  def sendFile(name: String, filePath: Path)(implicit request: Request[_]): Result = {
    val file = new File(filePath.toString)

    if (file.exists()) {
      val source = FileIO.fromPath(file.toPath)
      val contentType = Option(Files.probeContentType(filePath)).getOrElse(MimeTypes.BINARY)

      val headers = Seq(
        HeaderNames.CONTENT_DISPOSITION -> s"attachment; filename=$name",
        HeaderNames.CONTENT_TYPE -> contentType
      )

      request.version match {
        case HttpProtocol.HTTP_1_0 =>
          val size = file.length()
          val httpEntity = HttpEntity.Streamed(source, Some(size), Some(contentType))

          Result(
            header = ResponseHeader(200, Map(HeaderNames.CONTENT_LENGTH -> size.toString) ++ headers.toMap),
            body = httpEntity
          )
        case HttpProtocol.HTTP_1_1 =>
          Results.Ok.chunked(source).withHeaders(headers: _*)
      }
    } else {
      Results.NotFound
    }
  }

} 
开发者ID:yarosman,项目名称:captchanator,代码行数:43,代码来源:FileUploadingService.scala


示例15: ApiClient

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

import javax.inject.{Inject, Singleton}

import domain.{Post, User}
import play.api.http.HeaderNames
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.JsSuccess
import play.api.libs.ws.WSClient

import scala.concurrent.Future

@Singleton
class ApiClient @Inject() (wsClient: WSClient) {

  val endpoint = "http://jsonplaceholder.typicode.com"

  def getUser(userId: String): Future[Option[User]] = {

    wsClient.url(s"$endpoint/users/$userId").withHeaders(HeaderNames.CONTENT_TYPE -> "application/json").get() map {
      response =>
        response.json.validate[User] match {
          case result: JsSuccess[User] => {
            result.asOpt
          }
          case _ => None
        }
    }
  }

  def getPosts(userId: String): Future[Option[Seq[Post]]] = {

    wsClient.url(s"$endpoint/posts").withQueryString(("userId", userId)).withHeaders(HeaderNames.CONTENT_TYPE -> "application/json").get() map {
      response => response.json.validate[Seq[Post]] match {
        case result: JsSuccess[Seq[Post]] => {
          result.asOpt
        }
        case _ => None
      }
    }
  }
} 
开发者ID:criedel,项目名称:play-api-gateway,代码行数:43,代码来源:ApiClient.scala


示例16: HealthCheckResourceTest

//设置package包名称以及导入依赖的类
package cjp.catalogue.resource

import java.util.concurrent.TimeUnit

import akka.util.Timeout
import cjp.catalogue.util.BuildInfo
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
import play.api.http.{HeaderNames, Status}
import play.api.test._

import scala.concurrent.Future

class HealthCheckResourceTest extends WordSpec with BeforeAndAfter with PlayRunners with ResultExtractors with HeaderNames with Status with Matchers with MockitoSugar {

  implicit val timeout = Timeout(10L, TimeUnit.SECONDS)

  private val buildInfo: Some[BuildInfo] = Some(BuildInfo(1, "lst-commit"))


  "calling GET /healthcheck" should {

    def healthcheck(reportHealth:Boolean) = {
      val mongoHealthCheck = mock[MongoHealthCheck]
      when(mongoHealthCheck.ping()).thenReturn(Future successful reportHealth)
      val resource = new HealthCheckResource(mongoHealthCheck, buildInfo)
      resource.healthCheck()(FakeRequest())
    }

    "show build info and the string 'healthy' when mongo reports healthy" in {

      val result = healthcheck(reportHealth = true)
      status(result) should be(200)
      contentAsString(result) should be("healthy!\nbuild-number: 1")
    }

    "show build info and the string 'Unhealthy' when mongo reports unhealthy" in {

      val result = healthcheck(reportHealth = false)
      status(result) should be(500)
      contentAsString(result) should be("unhealthy! Mongo reported a negative response to ping!\nbuild-number: 1")
    }
  }

  "calling GET /ping" should {

    "reports pong" in {

      val resource = new HealthCheckResource(null, buildInfo)
      val result = resource.ping()(FakeRequest())
      status(result) should be(200)
      contentAsString(result) should be("pong")
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:57,代码来源:HealthCheckResourceTest.scala


示例17: SubdomainKiller

//设置package包名称以及导入依赖的类
package lila.i18n

import play.api.http.HeaderNames
import play.api.mvc._
import play.api.mvc.Results.MovedPermanently

import lila.common.HTTPRequest

final class SubdomainKiller(domain: String) {

  def apply(req: RequestHeader): Option[Handler] =
    if (appliesTo(req) && !allowMobileEn(req))
      Some(Action(MovedPermanently {
        val protocol = s"http${if (req.secure) "s" else ""}"
        s"$protocol://$domain${req.uri}"
      }))
    else None

  private def appliesTo(req: RequestHeader) =
    req.host.lift(2).has('.') &&
      req.host.drop(3) == domain &&
      HTTPRequest.isRedirectable(req) &&
      !excludePath(req.path)

  private def allowMobileEn(req: RequestHeader) =
    req.host.startsWith("en.") &&
      req.headers.get(HeaderNames.ACCEPT).exists(_ startsWith "application/vnd.lichess.v")

  private def excludePath(path: String) =
    path.contains("/embed/") || path.startsWith("/api/")
} 
开发者ID:Thiediev,项目名称:lilylichessmod,代码行数:32,代码来源:SubdomainKiller.scala


示例18: BooksController

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

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

import dao.{AuthorDAO, BooksDAO, GenreDAO}
import models.{Book, ErrorMessage}
import play.api.http.HeaderNames
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, Controller}

import scala.concurrent.{ExecutionContext, Future}

class BooksController @Inject()(authorDao: AuthorDAO,
                                genresDao: GenreDAO,
                                booksDao: BooksDAO)(implicit executionContext: ExecutionContext) extends Controller {
  def listAll(offset: Int, limit: Int) = Action.async {
    request =>
      booksDao.all(offset, limit).map {
        booksPage =>
          Ok(Json.toJson(booksPage))
      }
  }

  def create = Action.async(parse.json) {
    implicit request =>
      request.body.validate[Book] match {
        case JsSuccess(book, _) =>
          booksDao.insert(book).map {
            _ => Created.withHeaders(HeaderNames.LOCATION -> routes.BooksController.findById(book.id).absoluteURL)
          }
        case JsError(errors) =>
          Future.successful(BadRequest(Json.toJson(ErrorMessage(400, "Invalid json").withJsErrors(errors))))
      }
  }

  def findById(id: UUID) = Action.async {
    request =>
      booksDao.findById(id).map {
        case Some(book) => Ok(Json.toJson(book))
        case None => NotFound(Json.toJson(ErrorMessage(404, s"No book with id $id")))
      }
  }

  def delete(id: UUID) = Action.async {
    request =>
      booksDao.delete(id).map {
        _ => NoContent
      }
  }
} 
开发者ID:leanovate,项目名称:book-db-sample,代码行数:52,代码来源:BooksController.scala


示例19: AuthorsController

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

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

import dao.AuthorDAO
import models.{Author, ErrorMessage}
import play.api.http.HeaderNames
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, Controller}

import scala.concurrent.{ExecutionContext, Future}

class AuthorsController @Inject()(authorDao: AuthorDAO)(implicit executionContext: ExecutionContext) extends Controller {
  def listAll(offset: Int, limit: Int) = Action.async {
    request =>
      authorDao.all(offset, limit).map {
        authorPage =>
          Ok(Json.toJson(authorPage))
      }
  }

  def create = Action.async(parse.json) {
    implicit request =>
      request.body.validate[Author] match {
        case JsSuccess(author, _) =>
          authorDao.insert(author).map {
            _ => Created.withHeaders(HeaderNames.LOCATION -> routes.AuthorsController.findById(author.id).absoluteURL)
          }
        case JsError(errors) =>
          Future.successful(BadRequest(Json.toJson(ErrorMessage(400, "Invalid json").withJsErrors(errors))))
      }
  }

  def findById(id: UUID) = Action.async {
    request =>
      authorDao.findById(id).map {
        case Some(author) => Ok(Json.toJson(author))
        case None => NotFound(Json.toJson(ErrorMessage(404, s"No author with id $id")))
      }
  }

  def delete(id: UUID) = Action.async {
    request =>
      authorDao.delete(id).map {
        _ => NoContent
      }
  }
} 
开发者ID:leanovate,项目名称:book-db-sample,代码行数:50,代码来源:AuthorsController.scala


示例20: GenresController

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

import javax.inject.Inject

import dao.GenreDAO
import models.{ErrorMessage, Genre}
import play.api.http.HeaderNames
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, Controller}

import scala.concurrent.{ExecutionContext, Future}

class GenresController @Inject()(genreDao: GenreDAO)(implicit executionContext: ExecutionContext) extends Controller {
  def listAll(offset: Int, limit: Int) = Action.async {
    request =>
      genreDao.all(offset, limit).map {
        genrePage =>
          Ok(Json.toJson(genrePage))
      }
  }

  def create = Action.async(parse.json) {
    implicit request =>
      request.body.validate[Genre] match {
        case JsSuccess(genre, _) =>
          genreDao.insert(genre).map {
            _ =>
              Created.withHeaders(HeaderNames.LOCATION -> routes.GenresController.findById(genre.name).absoluteURL)
          }
        case JsError(errors) =>
          Future.successful(BadRequest(Json.toJson(ErrorMessage(400, "Invalid json").withJsErrors(errors))))
      }
  }

  def findById(name: String) = Action.async {
    request =>
      genreDao.findById(name).map {
        case Some(genre) => Ok(Json.toJson(genre))
        case None => NotFound(Json.toJson(ErrorMessage(404, s"No genre with name $name")))
      }
  }

  def delete(name: String) = Action.async {
    request =>
      genreDao.delete(name).map {
        _ => NoContent
      }
  }
} 
开发者ID:leanovate,项目名称:book-db-sample,代码行数:50,代码来源:GenresController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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