本文整理汇总了Scala中com.twitter.finagle.http.Status类的典型用法代码示例。如果您正苦于以下问题:Scala Status类的具体用法?Scala Status怎么用?Scala Status使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Status类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: apiErrorHandler
//设置package包名称以及导入依赖的类
package app.v1.handler
import com.twitter.finagle.http.{ Request, Response, Status, Version }
import com.twitter.logging.Logger
import com.twitter.util.Future
import io.finch.Error.{ NotParsed, NotPresent, NotValid }
import io.finch._
trait ErrorHandler {
private val log = Logger.get(getClass)
def apiErrorHandler: PartialFunction[Throwable, Output[Nothing]] = {
case e: NotPresent => BadRequest(e)
case e: NotParsed => BadRequest(e)
case e: NotValid => BadRequest(e)
case e: Exception => InternalServerError(e)
}
def topLevelErrorHandler[REQUEST <: Request](request: REQUEST, encoder: Encode[Throwable]): PartialFunction[Throwable, Future[Response]] = {
case t: Throwable => unhandledException(request, t, encoder)
}
private def unhandledException[REQUEST <: Request](request: REQUEST, t: Throwable, encoder: Encode[Throwable]): Future[Response] = {
try {
log.info(s"Unhandled exception on URI ${request.uri} with message $t")
Future.value(Response(Version.Http11, Status.InternalServerError))
} catch {
case e: Throwable => {
log.error(s"Unable to log unhandled exception: $e")
throw e
}
}
}
}
示例2: RefusedByRateLimiterErrorSpec
//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter
import com.twitter.finagle.http.{Request, Status}
import org.specs2.{Specification, ScalaCheck}
import io.circe.syntax._
import io.circe.jawn._
import com.lookout.ratelimitingfilter.models._
class RefusedByRateLimiterErrorSpec extends Specification with ScalaCheck with Arbitraries {
def is = s2"""
RefusedByRateLimiterError object
it should not lose data on roundtrips to JSON $dataIntegrity
it should contain a `message` field $messageField
it should create a response with 429 status $statusCode
"""
def fields(error: RefusedByRateLimiterError): Seq[String] =
error.asJson.asObject.toList.flatMap(_.fields)
def dataIntegrity = prop {
(error: RefusedByRateLimiterError) => {
(decode[RefusedByRateLimiterError](error.asJson.noSpaces)) must_== Right(error)
}
}
def messageField = prop {
(error: RefusedByRateLimiterError) => {
fields(error) must contain("message")
}
}
def statusCode = prop {
(error: RefusedByRateLimiterError) => {
error.toResponse.status must_== Status.TooManyRequests
}
}
}
示例3: RedirectionSpec
//设置package包名称以及导入依赖的类
package com.kurz
import com.kurz.services.RedisConnectionPool
import com.twitter.finagle.http.Status
import io.finch.Input
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
class RedirectionSpec extends FunSpec with Matchers with BeforeAndAfter {
import com.kurz.Server.redirection
before {
RedisConnectionPool.instance.getResource().del("mb")
RedisConnectionPool.instance.getResource().set("mb", "http://marceloboeira.com")
}
describe ("redirection") {
describe("when the slug exists") {
it("returns with the temporary redirection status") {
redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.TemporaryRedirect)
}
it("returns with the proper header for Location") {
redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.headers) shouldBe Some(Map("Location" -> "http://marceloboeira.com"))
}
}
describe("when the slug does not exist") {
it("returns with the not found status") {
redirection(Input.get("/invalid")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.NotFound)
}
}
}
}
示例4: DefaultNoteApi
//设置package包名称以及导入依赖的类
package app.v1.api
import java.util.UUID
import app.v1.model.Note
import app.v1.service.ServiceComponent
import com.twitter.finagle.http.Status
import com.twitter.logging.Logger
import io.circe.generic.auto._
import io.finch.circe._
import io.finch.{ Endpoint, _ }
trait NoteApi {
self: ServiceComponent =>
private val basePath = "api" :: "v1" :: "notes"
private val log = Logger.get(getClass)
val noteApi: DefaultNoteApi = new DefaultNoteApi
class DefaultNoteApi {
def endpoints = (getNotes :+: getNoteById :+: createNote :+: deleteNote :+: patchNote)
def getNotes: Endpoint[List[Note]] = get(basePath) {
log.info("Calling getNotes endpoint... ")
Ok(noteService.getNotes)
}
def getNoteById: Endpoint[Note] = get(basePath :: uuid) { uuid: UUID =>
log.info("Calling getNoteById endpoint... ")
Ok(noteService.getNoteById(uuid))
}
def createNote: Endpoint[Note] = post(basePath :: jsonBody[UUID => Note]) {
(noteGen: UUID => Note) =>
{
log.info("Calling createNote endpoint... ")
Created(noteService.createNote(noteGen))
}
}
def deleteNote: Endpoint[Unit] = delete(basePath :: uuid) { uuid: UUID =>
log.info("Calling deleteNote endpoint... ")
noteService.deleteNote(uuid)
NoContent[Unit].withStatus(Status.Ok)
}
def patchNote: Endpoint[Note] = patch(basePath :: uuid :: jsonBody[Note]) { (uuid: UUID, note: Note) =>
log.info("Calling patchNote endpoint... ")
noteService.patchNote(uuid, note)
Ok(note)
}
}
}
示例5: RefusedByRateLimiterError
//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter
import com.twitter.finagle.http.{Response, Status}
import com.twitter.finagle.RefusedByRateLimiter
import com.twitter.io.Buf
import com.twitter.logging.Logger
import io.circe.{Decoder, Encoder}
import io.circe.syntax._
final case class RefusedByRateLimiterError(
message: String
) extends Exception(message) {
def toResponse: Response = RefusedByRateLimiterError.toResponse(this)
}
object RefusedByRateLimiterError {
val LOG = Logger.get(getClass)
implicit val errorEncoder: Encoder[RefusedByRateLimiterError] =
Encoder.forProduct1("message") { err => err.message }
implicit val errorDecoder: Decoder[RefusedByRateLimiterError] =
Decoder.forProduct1[String, RefusedByRateLimiterError]("message") {
case (message: String) => RefusedByRateLimiterError(message)
}
def toResponse(error: RefusedByRateLimiterError): Response = {
val response = Response(Status.TooManyRequests)
val content = error.asJson.noSpaces
LOG.info(content)
response.content = Buf.Utf8(content)
response.contentType = "application/json"
response
}
}
示例6: ClientArtifactsTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import java.nio.file.{Files, Paths}
import com.twitter.finagle.http.Status
class ClientArtifactsTests extends TestBase {
"Client Artifacts" should {
"upload an artifact without a path" in {
val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
whenReady( client.uploadArtifact(bytes, "marathon.jpg") ) { result =>
result._1 shouldBe(Status.Created)
result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/marathon.jpg" ) )
}
}
"upload an artifact with a path" in {
val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
whenReady( client.uploadArtifact(bytes, "marathon.jpg", Some("this/is/a/path/marathon.jpg")) ) { result =>
result._1 shouldBe(Status.Created)
result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/this/is/a/path/marathon.jpg" ) )
}
}
"get an uploaded artifact" in {
whenReady( client.getArtifact("marathon.jpg") ) { data =>
val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
bytes shouldBe( data )
}
whenReady( client.getArtifact("this/is/a/path/marathon.jpg") ) { data =>
val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
bytes shouldBe( data )
}
}
"delete an artifact" in {
whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg") ) { status =>
status shouldBe( Status.Ok )
whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg").failed ) { ex =>
ex shouldBe a[MarathonClientException]
ex.asInstanceOf[MarathonClientException].status shouldBe (Status.NotFound)
}
}
}
}
}
示例7: MiscEndpointTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import uk.co.appministry.scathon.models.v2.GetInfoResponse
import com.twitter.finagle.http.Status
import play.api.libs.json.JsValue
class MiscEndpointTests extends TestBase {
"Misc Endpoints" should {
"receive JsValue for metrics endpoint" in {
whenReady( client.metrics() ) { value =>
value shouldBe a[JsValue]
}
}
"receive Ok for ping endpoint" in {
whenReady( client.ping() ) { status =>
status shouldBe( Status.Ok )
}
}
"receive server info from getInfo endpoint" in {
whenReady( client.getInfo() ) { response =>
response shouldBe a[GetInfoResponse]
}
}
}
}
示例8: PluginsTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import uk.co.appministry.scathon.testServer.plugins.TestPlugin
import com.twitter.finagle.http.{Method, Status}
class PluginsTests extends TestBase {
"Plugins Tests" should {
"retrieve a list of plugins" in {
val testPlugin = new TestPlugin
whenReady( client.getPlugins() ) { plugins =>
plugins.length shouldBe(1)
inside( plugins(0) ) {
case plugin =>
plugin.id shouldBe(testPlugin.info.id)
plugin.implementation shouldBe(testPlugin.info.implementation)
}
}
}
"send a request and get a response from a plugin" in {
whenReady( client.pluginExecuteRequest(Method.Get, "test-plugin", Some("/the/path/does/not/matter/here")) ) { response =>
response.status shouldBe(Status.Ok)
response.contentString shouldBe("GET")
}
}
"receive an error for an unsupported method" in {
whenReady(client.pluginExecuteRequest(Method.Head, "test-plugin", Some("/the/path/does/not/matter/here")).failed) { ex =>
ex shouldBe a[NotAllowed]
inside(ex.asInstanceOf[NotAllowed]) {
case e =>
e.status shouldBe(Status.MethodNotAllowed)
}
}
}
}
}
示例9: LeaderTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import com.twitter.finagle.http.Status
class LeaderTests extends TestBase {
"Leader Tests" should {
"get leader info from the server" in {
whenReady( client.getLeader() ) { data =>
data should matchPattern { case Some(_) => }
}
}
"receive Ok when removing a leader" in {
whenReady( client.deleteLeader() ) { status =>
status shouldBe(Status.Ok)
}
}
"receive NotFound when removing a leader (leader not there)" in {
whenReady( client.deleteLeader().failed ) { ex =>
ex shouldBe a[NotFound]
}
}
}
}
示例10: EventSubscriptionTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import java.net.URI
import uk.co.appministry.scathon.models.v2.EventSubscriptionSubscribeEvent
import com.twitter.finagle.http.Status
class EventSubscriptionTests extends TestBase {
"Event subscriptions operations" should {
val callbackUri = "http://callback-uri.com/some-path"
"create a subscription when requested" in {
whenReady( client.createEventSubscription(new URI(callbackUri)) ) { event =>
event shouldBe a[EventSubscriptionSubscribeEvent]
}
}
"get a subscription list when requested" in {
whenReady( client.getEventSubscriptions() ) { items =>
items shouldBe( List(callbackUri) )
}
}
"delete a subscription when requested" in {
whenReady( client.deleteEventSubscription(new URI(callbackUri)) ) { status =>
status shouldBe(Status.Ok)
whenReady( client.getEventSubscriptions() ) { items =>
items shouldBe( List.empty[String] )
}
}
}
}
}
示例11: CaseClassExceptionMapper
//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.exceptions.json
import javax.inject.Inject
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
import com.twitter.finatra.json.internal.caseclass.exceptions.CaseClassMappingException
import me.kamkor.yaas.http.responses.ErrorResponse
class CaseClassExceptionMapper @Inject()(
response: ResponseBuilder
) extends ExceptionMapper[CaseClassMappingException] {
override def toResponse(request: Request, e: CaseClassMappingException): Response = {
// FIXME, do it properly
val errorMessage = e.errors map (_.getMessage) mkString ("\n")
val errorResponse =
ErrorResponse(
status = Status.BadRequest.code,
message = errorMessage
)
response.badRequest.json(errorResponse)
}
}
示例12: WishListsFeatureTest
//设置package包名称以及导入依赖的类
package me.kamkor.wishlists
import com.twitter.finagle.http.Status
import com.twitter.finatra.http.test.{EmbeddedHttpServer, HttpTest}
import com.twitter.inject.Mockito
import com.twitter.inject.server.FeatureTest
object WishListsFeatureTest {
val TestTenant = "TestTenant"
val Headers = Map("hybris-tenant" -> TestTenant)
}
class WishListsFeatureTest extends FeatureTest with Mockito with HttpTest {
import WishListsFeatureTest._
override val server = new EmbeddedHttpServer(new WishListsServer)
"A WishLists endpoint" should {
"GET wishlist" in {
//mock document repository client
//server.httpGet(path = s"/$TestTenant/wishlists/1", headers = Headers, andExpect = Status.Ok)
}
"GET NotFound" in {
}
"PUT wishlist" in {
server.httpPut(
path = s"/$TestTenant/wishlists/1",
headers = Headers,
putBody =
"""
|{
| "owner":"kamil",
| "title":"food list",
| "description":"Food for the weekend"
|}
""".stripMargin,
andExpect = Status.NoContent
)
}
"DELETE wishlist" in {
server.httpDelete(path = s"/$TestTenant/wishlists/1", headers = Headers, andExpect = Status.NoContent)
}
}
}
示例13: UserFilter
//设置package包名称以及导入依赖的类
package com.example
import com.example.db.DB
import com.google.inject.Inject
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Filter, Service, SimpleFilter}
import com.twitter.util.Future
class UserFilter @Inject() extends SimpleFilter[Request, Response] {
override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
val token = request.cookies.get("auth_token")
DB.isValidToken(token.map(x => x.value).getOrElse("")) flatMap {
case true => service(request)
case false => redirectToLoginPage
}
}
def redirectToLoginPage = Future {
val response = Response(Status.TemporaryRedirect)
response.location = "/loginform"
response
}
}
示例14: RootApiSpec
//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot.controllers
import com.twitter.finagle.http.Status
import io.finch._
import org.scalatest.prop.Checkers
import org.scalatest.{FlatSpec, Matchers}
class RootApiSpec extends FlatSpec with Matchers with Checkers {
behavior of "root endpoint"
it should "return 'ok'" in {
val input = Input.get("/")
val res = RootCtrl.root(input)
res.output.map(_.status) === Some(Status.Ok)
res.value.isDefined === true
res.value.get shouldBe "ok"
}
}
示例15: HelloControllerFeatureTest
//设置package包名称以及导入依赖的类
import com.twitter.finagle.http.Status
import com.twitter.finatra.http.test.EmbeddedHttpServer
import com.twitter.inject.server.FeatureTest
class HelloControllerFeatureTest extends FeatureTest {
override val server: EmbeddedHttpServer = new EmbeddedHttpServer(
twitterServer = new FitmanServer)
"Say Hello" in {
server.httpGet(
path = "/hello",
andExpect = Status.Ok,
withBody = "Fitman says hello"
)
}
}