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

Scala OK类代码示例

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

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



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

示例1: status

//设置package包名称以及导入依赖的类
package im.actor.server.webhooks.http.routes

import akka.http.scaladsl.model.StatusCodes.{ Gone, OK }
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.PathMatchers.Segment
import akka.http.scaladsl.server.Route
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport
import im.actor.server.api.http.json.{ Errors, JsonFormatters, Status }

trait TokenStatus extends PlayJsonSupport {
  self: WebhooksHttpHandler ?

  import JsonFormatters._

  def status: Route = {
    path(Segment / "status") { token ?
      onSuccess(integrationTokensKV.getGroupId(token)) {
        case Some(_) ? complete(OK ? Status("Ok"))
        case None    ? complete(Gone ? Errors("This token no longer exists(or never existed)"))
      }
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:25,代码来源:TokenStatus.scala


示例2: AboutHttpHandler

//设置package包名称以及导入依赖的类
package im.actor.server.api.http.info

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import de.heikoseeberger.akkahttpcirce.CirceSupport
import im.actor.config.ActorConfig
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonEncoders, ServerInfo }

import scala.collection.JavaConversions._

private[http] final class AboutHttpHandler()(implicit system: ActorSystem) extends HttpHandler
  with CirceSupport
  with JsonEncoders {

  private lazy val about = getServerInfo

  def routes: Route = path("about") {
    get {
      complete(OK ? about)
    }
  }

  private def getServerInfo: ServerInfo =
    ServerInfo(
      projectName = ActorConfig.projectName,
      endpoints = ActorConfig.load().getStringList("public-endpoints").toList
    )

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:33,代码来源:AboutHttpHandler.scala


示例3: DiscussionGroupsHttpHandler

//设置package包名称以及导入依赖的类
package im.actor.server.api.http.rest.groups

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import im.actor.server.db.DbExtension
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonFormatters, DiscussionGroupInfo }
import im.actor.server.persist.DiscussionGroupRepo
import im.actor.server.api.http.rest.util.SecurityManager

/**
 * Created by User on 2016/10/8.
 */
private[http] final class DiscussionGroupsHttpHandler()(implicit system: ActorSystem) extends HttpHandler with PlayJsonSupport {

  import JsonFormatters._

  private lazy val db = DbExtension(system).db
  private lazy val config = system.settings.config

  override def routes: Route =
    defaultVersion {
      pathPrefix("dangchat-discussionGroups") {
        pathEnd {
          post {
            complete("The post http request is not processed!")
          }
        } ~
          get {
            //??request?? request =>
            path(Segment) { discussionGroupId ?
              //???????ctx.uri.query.get("apiPwd")
              parameters('apiPassword) { apiPassword ?
                if (SecurityManager.checkApiPassword(apiPassword, config)) {
                  //?????Id?????
                  val optDiscussionGroup = scala.concurrent.Await.result(
                    db.run(DiscussionGroupRepo.findById(discussionGroupId)), scala.concurrent.duration.Duration.Inf
                  )
                  optDiscussionGroup match {
                    case Some(discussionGroup) ? complete(OK ? DiscussionGroupInfo(discussionGroup.id, discussionGroup.groupId))
                    case None                  ? complete(OK ? DiscussionGroupInfo("", 0))
                  }
                } else {
                  complete("Api password???")
                }
              }
            }
          } ~
          put {
            complete("The put http request is not processed!")
          } ~
          delete {
            complete("The delete http request is not processed!")
          }
      }
    }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:62,代码来源:DiscussionGroupsHttpHandler.scala


示例4: CovarianceInput

//设置package包名称以及导入依赖的类
package org.openalgo.analytics

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives.{as, complete, decodeRequest, entity, path, post}
import akka.stream.ActorMaterializer
import argonaut.Argonaut.casecodec2
import com.typesafe.config.ConfigFactory
import de.heikoseeberger.akkahttpargonaut.ArgonautSupport

import scala.collection.JavaConverters._
import scala.collection.mutable

case class CovarianceInput(series1: mutable.Buffer[java.lang.Double], series2: mutable.Buffer[java.lang.Double])

object AppMain extends App with ArgonautSupport {
  val config = ConfigFactory.load()

  implicit def PersonCodecJson =
    casecodec2(CovarianceInput.apply, CovarianceInput.unapply)("series1", "series2")

  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  val route =
    path("covariance") {
      post {
        decodeRequest {
          entity(as[CovarianceInput]) { json: CovarianceInput =>
            complete(OK, CovarianceCall.getCovariance(json.series1.asJava, json.series2.asJava))
          }
        }
      }
    }

  val bindingFuture = Http().bindAndHandle(route, config.getString("http.interface"), config.getInt("http.port"))

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  Console.readLine() // for the future transformations
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ ? system.terminate()) // and shutdown when done
} 
开发者ID:openalgo,项目名称:analytics,代码行数:46,代码来源:AppMain.scala


示例5: omdbApiRequest

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

import java.io.IOException

import scala.concurrent.Future

import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ HttpResponse, HttpRequest }
import akka.http.scaladsl.model.StatusCodes.{ OK, BadRequest }
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.unmarshalling.Unmarshal

import spray.json._

import org.yashsriv.helpers.Worker
import org.yashsriv.json.MovieSupport
import org.yashsriv.models.MovieQuery
import org.yashsriv.models.MovieResult

trait Movie extends Directives with Worker with MovieSupport with SprayJsonSupport {

  def omdbApiRequest(request: HttpRequest): Future[HttpResponse] = Http().singleRequest(request)

  def movieApi(implicit requestUri: Uri): Route = pathPrefix("movie") {
    (post & entity(as[MovieQuery])) { movieQuery ?
      complete {
        fetchMovieInfo(movieQuery).map[ToResponseMarshallable] {
          case Right(movieInfo) => movieInfo
          case Left(errorMessage) => BadRequest ? errorMessage
        }
      }
    }
  }

  def fetchMovieInfo(mq: MovieQuery)(implicit requestUri: Uri): Future[Either[String, MovieResult]] = {
    omdbApiRequest(RequestBuilding.Get(requestUri withQuery convertToQuery(mq))).flatMap { response =>
      response.status match {
        case OK         ? Unmarshal(response.entity).to[MovieResult].map(Right(_))
        case BadRequest ? Future.successful(Left(s"${mq.toJson.prettyPrint} \nIncorrect Movie Format"))
        case _          ? Unmarshal(response.entity).to[String].flatMap { entity ?
          val error = s"Omdb request failed with status code ${response.status} and entity $entity"
          Future.failed(new IOException(error))
        }
      }
    }
  }

} 
开发者ID:yashsriv,项目名称:akka-http-batch-api,代码行数:54,代码来源:Movie.scala


示例6: LogReceiverSpec

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

import akka.actor.ActorRef
import akka.http.scaladsl.model.StatusCodes.{Accepted, MethodNotAllowed, NotFound, OK}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import performanceanalysis.base.SpecBase
import performanceanalysis.server.messages.AdministratorMessages._
import performanceanalysis.server.messages.LogMessages._

class LogReceiverSpec extends SpecBase with ScalatestRouteTest {
  class LogReceiverProbe extends LogReceiver {
    val logMessage: Log = Log("some log line")
    val probe = TestProbe("test-log-receiver")

    override val logReceiverActor: ActorRef = probe.ref
  }
  "The log receiver" must {
    val componentId = "someCompId"

    "handle a GET on / response with status code 405" in new LogReceiver {
      Get() ~> Route.seal(routes) ~> check {
        status shouldBe MethodNotAllowed
      }
    }

    "handle a GET on /components response with status code 200" in new LogReceiver {
      Get("/components") ~> Route.seal(routes) ~> check {
        status shouldBe OK
      }
    }

    "handle a POST on /components/<existing-compId>/logs respond with status code 202" in new LogReceiverProbe() {
      val results = Post(s"/components/$componentId/logs", logMessage) ~> routes

      probe.expectMsg(SubmitLogs(componentId, logMessage.logLines))
      probe.reply(LogsSubmitted)

      results ~> check {
        response.status shouldBe Accepted
      }
    }

    "handle a POST on /components/<non-existing-compId>/logs respond with status code 404" in new LogReceiverProbe() {
      val testResult = Post(s"/components/$componentId/logs", logMessage) ~> routes

      probe.expectMsg(SubmitLogs(componentId, logMessage.logLines))
      probe.reply(LogParserNotFound(componentId))

      testResult ~> check {
        response.status shouldBe NotFound
      }
    }
  }
} 
开发者ID:scala-academy,项目名称:performance-analysis,代码行数:57,代码来源:LogReceiverSpec.scala


示例7: ServerSpec

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



import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.testkit.{ScalatestRouteTest, WSProbe}
import org.scalatest.{FlatSpec, Matchers, _}
import szymonbaranczyk.boot.{ClosingHandle, Server}

class ServerSpec extends FlatSpec with BeforeAndAfterAll with ScalatestRouteTest with Matchers {
  var stopHandlers: Option[ClosingHandle] = None

  "Server" should "serve the index page on /" in {
    Get("/") ~> Server.route ~> check {
      status shouldBe OK
    }
  }

  "it" should "serve the index page on resources/html/index.html" in {
    Get("/resources/html/index.html") ~> Server.route ~> check {
      status shouldBe OK
    }
  }

  "it" should "expose Websocket" in {
    val wsClient = WSProbe()

    // WS creates a WebSocket request for testing
    WS("/greeter/lol", wsClient.flow) ~> Server.route ~>
      check {
        // check response for WS Upgrade headers
        isWebSocketUpgrade shouldEqual true

      }
  }

  override def beforeAll: Unit = {
    stopHandlers = Some(Server.startServer())
  }

  override def afterAll: Unit = {
    Server.stopServer(stopHandlers.getOrElse(fail()))
  }


} 
开发者ID:szymonbaranczyk,项目名称:webmmo,代码行数:47,代码来源:ServerSpec.scala


示例8: handle

//设置package包名称以及导入依赖的类
package ch.becompany.http

import java.io.IOException

import akka.http.scaladsl.model.StatusCodes.{NotModified, OK}
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.EntityTag
import akka.http.scaladsl.unmarshalling.Unmarshal

import scala.concurrent.{ExecutionContext, Future}
import scalacache._
import scalacache.caffeine._

trait CachingSupport extends HttpClient {

  type Cached[A] = (EntityTag, A)
  implicit val etagCache = ScalaCache(CaffeineCache())

  override def handle[A](handler: HttpHandler[A], request: HttpRequest, response: HttpResponse)
                        (implicit ec: ExecutionContext): Future[A] =
    response.status match {
      case OK =>
        for {
          body <- super.handle(handler, request, response)
          cached <- addToCache(request.uri, response, body)
        } yield body
      case NotModified => readFromCache(request.uri)
      case _ => super.handle(handler, request, response)
    }

  abstract override def additionalHeaders(req: HttpRequest)(implicit ec: ExecutionContext): Future[Seq[HttpHeader]] =
    get[Cached[_], NoSerialization](req.uri) map {
      case Some((etag, _)) => scala.collection.immutable.Seq(headers.`If-None-Match`(etag))
      case None => Nil
    }

  private def addToCache[A](uri: Uri, response: HttpResponse, body: A)(implicit ec: ExecutionContext): Future[Unit] =
    response.header[headers.ETag].map(_.etag).map { etag =>
      put(uri)((etag, body))
    } getOrElse Future()

  private def addToCacheAndRead(uri: Uri, response: HttpResponse)(implicit ec: ExecutionContext): Future[ResponseEntity] =
    response.header[headers.ETag].map(_.etag).map { etag =>
      Unmarshal(response.entity).to[String].
        flatMap(content => put(uri)((etag, content))).
        flatMap(_ => readFromCache(uri))
    } getOrElse Future(response.entity)

  private def readFromCache[A](uri: Uri)(implicit ec: ExecutionContext): Future[A] = {
    get[Cached[A], NoSerialization](uri) flatMap {
      case Some((etag, content)) => Future(content)
      case None => Future.failed(new IOException("Cache entry not found"))
    }
  }

} 
开发者ID:becompany,项目名称:akka-social-stream,代码行数:57,代码来源:CachingSupport.scala


示例9: handle

//设置package包名称以及导入依赖的类
package ch.becompany.http

import java.io.IOException

import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, ResponseEntity}
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import akka.stream.ActorMaterializer
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.{ExecutionContext, Future}

trait HttpHandler[A] {
  def handle(request: HttpRequest, response: HttpResponse)(implicit ec: ExecutionContext): Future[A]
}

class UnmarshallingHttpHandler[A](implicit materializer: ActorMaterializer, unmarshaller: Unmarshaller[ResponseEntity, A])
  extends HttpHandler[A] with LazyLogging{

  def handle(request: HttpRequest, response: HttpResponse)(implicit ec: ExecutionContext): Future[A] =
    response.status match {
      case OK => Unmarshal(response.entity).to[A]
      case _ => handleError(response)
    }

  def handleError(response: HttpResponse)(implicit ec: ExecutionContext): Future[A] = {
    Unmarshal(response.entity).to[String].flatMap { entity =>
      val error = s"HTTP error ${response.status}: $entity"
      logger.error(error)
      Future.failed(new IOException(error))
    }
  }

} 
开发者ID:becompany,项目名称:akka-social-stream,代码行数:35,代码来源:HttpHandler.scala


示例10: ExpiresDirectiveSpec

//设置package包名称以及导入依赖的类
package com.lonelyplanet.akka.http.extensions.directives

import akka.http.scaladsl.model.DateTime
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}
import akka.http.scaladsl.server.Directives._
import ExpiresDirective._
import akka.http.scaladsl.model.StatusCodes.OK

class ExpiresDirectiveSpec extends FlatSpec with Matchers with ScalatestRouteTest {
  private val expirationDate = DateTime.now

  private val route = path("test") {
    expires(expirationDate) {
      complete {
        "OK"
      }
    }
  }

  "ExpiresDirective" should "set `Expires` header correctly" in {
    Get("/test") ~> route ~> check {
      status shouldBe OK
      responseAs[String] shouldBe "OK"
      header("Expires").get.value shouldBe expirationDate.toRfc1123DateTimeString
    }
  }
} 
开发者ID:lonelyplanet,项目名称:akka-http-extensions,代码行数:29,代码来源:ExpiresDirectiveSpec.scala


示例11: ViewerApiSpec

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

import java.util.Date

import akka.actor.{Actor, Props}
import akka.http.scaladsl.model.StatusCodes.{NoContent, OK}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import audit.Api
import audit.viewer.Viewer.{History, HistoryDetails}
import audit.viewer.ViewerActor.{ViewById, ViewLast}
import org.scalatest.WordSpec

class ViewerApiSpec extends WordSpec with ScalatestRouteTest with ViewerApi with Api {
  override implicit val executionContext = executor

  val history = List(History("eid-01", "s-01", "msg-01", "desc-01", "state-01", new Date()))
  val historyDetails = HistoryDetails("msg-01", "desc-01", "state-01", new Date(), "user-01")

  override val viewer = system.actorOf(Props(new Actor {
    override def receive = {
      case ViewLast(_, _) => sender() ! history
      case ViewById("system-02", _) => sender() ! None
      case ViewById(_, _) => sender() ! Option(historyDetails)
    }
  }))

  "ViewerApi" should {
    "provide last events" in {
      Get("/view/user/user-01/last?limit=10") ~> viewerRoute ~> check {
        status === OK

        responseAs[List[History]] === history
      }
    }

    "provide specific event by 'system' and 'external id'" in {
      Get("/view/details/system/system-01/id/eid-01") ~> viewerRoute ~> check {
        status === OK

        responseAs[HistoryDetails] === historyDetails
      }
    }

    "not provide event if it does not exist" in {
      Get("/view/details/system/system-02/id/eid-01") ~> viewerRoute ~> check {
        status === NoContent
      }
    }
  }

} 
开发者ID:grzesiekw,项目名称:audit,代码行数:52,代码来源:ViewerApiSpec.scala


示例12: CollectorApiSpec

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

import java.util.Date

import akka.actor.{Actor, Props}
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.testkit.ScalatestRouteTest
import audit.Api
import audit.collector.Collector.Event
import audit.collector.CollectorActor.Stored
import org.scalatest.WordSpec

class CollectorApiSpec extends WordSpec with ScalatestRouteTest with CollectorApi with Api {
  override implicit val executionContext = executor

  val event = Event("system-01", "eid-01", "user-01", new Date(), "msg-01", "desc-01", "state-01")

  override val collector = system.actorOf(Props(new Actor {
    override def receive = {
      case _ => sender() ! Stored
    }
  }))

  "CollectionApi" should {
    "store event" in {
      Post("/collect", event) ~> collectorRoute ~> check {
        status === OK
      }
    }
  }

} 
开发者ID:grzesiekw,项目名称:audit,代码行数:33,代码来源:CollectorApiSpec.scala


示例13: Server

//设置package包名称以及导入依赖的类
import akka.http.scaladsl.server.{ Directives, PathMatchers }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.headers.Connection
import akka.http.scaladsl.model.StatusCodes.{ MovedPermanently, OK }
import akka.http.scaladsl.model.HttpRequest
import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import scala.util.{ Failure, Success }
import scala.concurrent.duration._
import scala.concurrent.{ Await, ExecutionContext }

class Server(implicit system: ActorSystem, materializer: Materializer, ec: ExecutionContext) extends Directives with PathMatchers {
  val route = path("redirect" / IntNumber) { i =>
    redirect("/nowhere", MovedPermanently)
  } ~ path("success" / IntNumber) { i =>
    post {
      entity(as[String]) { e =>
        complete(OK)
      }
    }
  }

  def bindingFuture = Http().bindAndHandle(handler = route, interface = "0.0.0.0", port = 50001)
}

object Server extends App {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  val server = new Server

  server.bindingFuture.onComplete {
    case Success(_) =>
      println(s"Server listening on port: 50001")
    case Failure(reason) =>
      println(s"Server failed to bind to port 50001.", reason)
      system.terminate()
  }
} 
开发者ID:derekwyatt,项目名称:redirect-and-continue,代码行数:41,代码来源:Server.scala


示例14: HttpClientFutureExtensions

//设置package包名称以及导入依赖的类
package uk.co.telegraph.utils.client.http.scaladsl

import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshal}
import akka.stream.Materializer
import uk.co.telegraph.utils.client.http.exceptions.{HttpInvalidStatusException, HttpRawDataException, HttpUnmarshallingException}
import uk.co.telegraph.utils.client.http.scaladsl.HttpClientFutureExtensions._

import scala.concurrent.Future.{failed, successful}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

private [scaladsl] case class HttpClientFutureExtensions(left:Future[HttpContext])(implicit ec:ExecutionContext, mat:Materializer){

  
  def ignorePayload:Future[HttpContext] = {
    for{
      ctx <- left
      _ <- Try{ctx.response.entity.discardBytes().future()} getOrElse EmptyFuture
    } yield ctx
  }
}

object HttpClientFutureExtensions{
  val EmptyFuture  : Future[Unit]    = successful(())
  val DefaultStatus: Seq[StatusCode] = Seq(OK)
} 
开发者ID:telegraph,项目名称:tmg-utils,代码行数:30,代码来源:HttpClientFutureExtensions.scala


示例15: toString

//设置package包名称以及导入依赖的类
package uk.co.telegraph.utils.server.model

import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.StatusCodes.OK
import org.json4s.Formats
import org.json4s.Extraction.decompose
import org.json4s.jackson.JsonMethods._
import uk.co.telegraph.utils.server.serializers.{ErrorCodeSerializer, StatusCodeSerializer}

sealed trait ResponseMsg{
  type Type
  val statusCode:StatusCode
  val data:Type

  def toString()(implicit formats:Formats): String = {
    compact(render(decompose(data)(formats + StatusCodeSerializer + ErrorCodeSerializer)))
  }
}

object ResponseMsg{

  def apply(error:Throwable):ResponseMsg = {
    FailurePayload(error)
  }

  def apply[U](outgoingMsg:U, status: StatusCode = OK):ResponseMsg = {
    outgoingMsg match {
      case err:Throwable => ResponseMsg(err)
      case _             => new ResponseMsg {
        type Type      = U
        val data       = outgoingMsg
        val statusCode = status
      }
    }
  }
} 
开发者ID:telegraph,项目名称:tmg-utils,代码行数:37,代码来源:ResponseMsg.scala


示例16: StatusCodeSerializerTest

//设置package包名称以及导入依赖的类
package uk.co.telegraph.utils.server.serializers

import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.StatusCodes.OK
import org.json4s.{DefaultFormats, Formats, MappingException, jackson}
import org.scalatest.{FunSpec, Matchers}

class StatusCodeSerializerTest extends FunSpec with Matchers {

  import StatusCodeSerializerTest._

  implicit val format:Formats = DefaultFormats + StatusCodeSerializer

  describe("Given 'StatusCodeSerializer', "){
    it("I should get an error when unmarshalling an invalid statusCode"){
      val result = intercept[MappingException]{
        jackson.Serialization.read[Report](SampleReportInvalid)
      }

      result.getMessage shouldBe
        "No usable value for statusCode\nCan't convert JString(200) to 'StatusCode'"
          .stripMargin
    }

    it("I should be able to unmarshal a status Code"){
      val result = jackson.Serialization.read[Report](SampleReport)

      result shouldBe SampleReportObj
    }

    it("I should be able to marshal a statusCode"){
      val result = jackson.Serialization.write(SampleReportObj)
      result shouldBe SampleReport
    }
  }
}

object StatusCodeSerializerTest{

  case class Report(statusCode: StatusCode)

  val SampleReportInvalid = """{"statusCode":"200"}"""
  val SampleReport = """{"statusCode":200}"""

  val SampleReportObj = Report(OK)
} 
开发者ID:telegraph,项目名称:tmg-utils,代码行数:47,代码来源:StatusCodeSerializerTest.scala


示例17: Order

//设置package包名称以及导入依赖的类
package com.mkuzdowicz.akkahttp.rest

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import reactivemongo.bson.BSONDocument
import spray.json.DefaultJsonProtocol
import play.api.libs.json._
import play.modules.reactivemongo.json.BSONFormats
import scala.concurrent.ExecutionContext.Implicits.global

final case class Order(prize: Double, description: String)

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val orderFormat = jsonFormat2(Order)
}

object OrdersService extends JsonSupport {

  def convertToString(input: List[BSONDocument]) : String = {
    input
      .map(f => convertToString(f))
      .mkString("[", ",", "]")
  }

  def convertToString(input: BSONDocument) : String = {
    Json.stringify(BSONFormats.toJSON(input))
  }

  def routes() =
    path("cars") {
      get {
        complete(OK, List(Order(30.55, "car")))
      }
    } ~ path("bikes") {
      get {
        complete(OK, List(Order(100.55, "bike")))
      }
    } ~ path("stocks") {
      get {

       val res = for {
          elem <-  MongoDatabase.findAllTickers()
        } yield {
         convertToString(elem)
        }

        complete(OK, res)
      }
    }


} 
开发者ID:MartinKuzdowicz,项目名称:akka-http-rest-example,代码行数:54,代码来源:OrdersService.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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