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

Scala Json4sSupport类代码示例

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

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



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

示例1: DataConsumer

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

import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson.Serialization.writePretty
import org.json4s.{DefaultFormats, jackson}

import scala.concurrent.Future

object DataConsumer extends Json4sSupport {

  implicit val serialization = jackson.Serialization // or native.Serialization
  implicit val formats = DefaultFormats

  val route =
    path("data") {
      post {
      entity(as[RootObject]) {
        data =>
          println(writePretty(data))
          complete(Future.successful(data.toString))
      }

      }
    }
} 
开发者ID:rmorais,项目名称:akka-http-playground,代码行数:27,代码来源:DataConsumer.scala


示例2: TapStreamRouteSpec

//设置package包名称以及导入依赖的类
import org.scalatest.{Matchers, WordSpec}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.server._
import Directives._
import org.goingok.httpServer.{ResponseMessage, GenericApi, GoingOkAPI}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._

class TapStreamRouteSpec extends WordSpec with Matchers with ScalatestRouteTest with GoingOkAPI with Json4sSupport {


  "The service" should {

    "return a greeting for GET requests to the root path" in {
      // tests:
      Get() ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "The current version of this API can be found at /v1"
      }
    }

    "return an 'ok' message for GET requests to /v1/health" in {
      // tests:
      Get("/v1/health") ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "ok"
      }
    }

    "leave GET requests to other paths unhandled" in {
      // tests:
      Get("/someOtherPath") ~> routes ~> check {
        handled shouldBe false
      }
    }

    "return a MethodNotAllowed error for PUT requests to the root path" in {
      // tests:
      Put() ~> Route.seal(routes) ~> check {
        status === StatusCodes.MethodNotAllowed
        import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers.stringUnmarshaller
        responseAs[String] shouldEqual "HTTP method not allowed, supported methods: GET"
      }
    }
  }
} 
开发者ID:GoingOK,项目名称:goingok-server,代码行数:46,代码来源:TapStreamRouteSpec.scala


示例3: userProcessor

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

import akka.cluster.sharding.ClusterSharding
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.util.Timeout
import commands.CreateUser
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import models.User
import org.json4s.{native, DefaultFormats}
import queries.FindUser
import responses.{NotFound, Acknowledge}
import services.UserProcessor
import akka.pattern._
import scala.concurrent.duration._
import scala.language.postfixOps

trait ApiRoutes extends Json4sSupport {
  this: Api =>
  private[this] implicit val formats = DefaultFormats
  private[this] implicit val serialization = native.Serialization
  private[this] implicit val timeout = Timeout(3 seconds)

  val host = context.system.settings.config.getString("constructr.consul.agent-name")
  def userProcessor = ClusterSharding(context.system).shardRegion(UserProcessor.shardName)

  val routes: Route =
    pathSingleSlash {
      get {
        complete("Welcome at the API of: " + host)
      }
    } ~
    pathPrefix("user") {
      pathEnd {
        post {
          entity(as[CreateUser]) { cmd =>
            onSuccess(userProcessor ? cmd) {
              case ack: Acknowledge => complete(StatusCodes.Created -> "Created user")
              case _ => complete(StatusCodes.Conflict -> s"Failed to create user, email=${cmd.email}")
            }
          }
        }
      } ~
      path(Segment) { email =>
        onSuccess(userProcessor ? FindUser(email)) {
          case usr: User => complete(usr)
          case nf: NotFound => complete(StatusCodes.NotFound -> s"User with email=$email not found")
          case _ => complete(StatusCodes.BadRequest -> "Something went wrong")
        }
      }
    }

} 
开发者ID:MavenCode,项目名称:akkaDocker,代码行数:55,代码来源:ApiRoutes.scala


示例4: nothingHere

//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.server

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, StandardRoute}
import au.edu.utscic.athanorserver.message.Exception.UnknownAnalysisType
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._


//noinspection ForwardReference
trait GenericApi extends Json4sSupport {

  import au.edu.utscic.athanorserver.StreamsContext._

  val version = "v2"
  val details:String = "no details yet" // ApiInfo(Config.name,Config.description,Config.version,Config.colour)
  val healthEndPoint = "health"

  val athanorExceptionHandler = ExceptionHandler {
    case _: UnknownAnalysisType =>
      extractUri { uri =>
        log.error(s"Request to $uri did not include a valid analysis type")
        complete(HttpResponse(InternalServerError, entity = "The request did not include a valid analysis type"))
      }
  }

  implicit val formats: Formats = DefaultFormats
  implicit val jacksonSerialization: Serialization = jackson.Serialization

  def nothingHere: StandardRoute =  complete(ResponseMessage("There is nothing at this URL"))

  val routes: Route = handleExceptions(athanorExceptionHandler) {
    pathSingleSlash {
      get(complete(ResponseMessage("The current version of this API can be found at /"+version)))
    } ~
      pathPrefix(version) {
        customRoutes ~
          path(healthEndPoint) {
            get(complete(ResponseMessage("ok")))
          } ~
          apiDetails ~
          adminRoutes
      }
  }

  val customRoutes: Route = path("custom") { get(complete("")) }
  val adminRoutes: Route = path("admin") { get(complete(""))}
  val apiDetails: Route = pathEnd(complete(ResponseMessage(details)))
} 
开发者ID:uts-cic,项目名称:athanor-server,代码行数:52,代码来源:GenericApi.scala


示例5:

//设置package包名称以及导入依赖的类
package nl.tradecloud.item

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import nl.tradecloud.common.utils.session.{SessionManager, SessionDirectives}
import nl.tradecloud.common.views
import nl.tradecloud.common.views.Identity
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.ext.EnumNameSerializer
import org.json4s.{DefaultFormats, Formats, jackson}

import scala.language.postfixOps

trait ApiRoutes extends SessionDirectives[Identity] with Json4sSupport {
  this: Api =>

  implicit val serialization = jackson.Serialization
  implicit val formats: Formats = DefaultFormats + new EnumNameSerializer(views.IdentityRole)
  val sessionManager = new SessionManager[views.Identity](context.system.settings.config)

  val host = context.system.settings.config.getString("constructr.consul.agent-name")

  val routes: Route =
    pathPrefix("api" / "v1") {
      pathSingleSlash {
        get {
          complete("Welcome at the item api at: " + host)
        }
      } ~
      pathPrefix("item") {
        requireSession { identity: Identity =>
          get {
            complete(identity)
          }
        }
      }
    }
} 
开发者ID:tradecloud,项目名称:tradecloud-microservices-demo,代码行数:39,代码来源:ApiRoutes.scala


示例6: HttpServer

//设置package包名称以及导入依赖的类
package com.pragmasoft.eventaggregator.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson.Serialization
import org.json4s.{NoTypeHints, jackson}

import scala.concurrent.duration._
import scala.util.{Failure, Success}

class HttpServer(port: Int)(implicit actorSystem: ActorSystem) extends LazyLogging with Json4sSupport {

  private val metaService = MetaService.create()

  implicit val materializer = ActorMaterializer()
  implicit val timeout = Timeout(10.seconds)

  implicit val serialization = jackson.Serialization // or native.Serialization
  implicit val jsonFormats = Serialization.formats(NoTypeHints)

  val route =
    path("meta") {
      get {
        complete(metaService.metaInfo)
      }
    }

  def start(): Unit = {
    implicit val executionContext = actorSystem.dispatcher

    Http().bindAndHandle(route, "0.0.0.0", port).onComplete {
      case Success(binding) =>
        logger.info("HTTP server started successfully and bound to {}", binding.localAddress)

      case Failure(ex) =>
        logger.error(s"Error while starting HTTP server ${ex.getMessage}", ex)
    }
  }
} 
开发者ID:galarragas,项目名称:event-aggregator,代码行数:46,代码来源:http.scala


示例7: simpleRequest

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

import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.Materializer
import akka.stream.scaladsl.{Flow, Sink, Source}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.apache.logging.log4j.scala.Logging
import org.json4s.{DefaultFormats, native}

import scala.concurrent.{ExecutionContext, Future}


trait SimpleHttpClient extends Logging {

  import Json4sSupport._

  implicit val serialization = native.Serialization
  implicit val formats = DefaultFormats

  def simpleRequest[T](request: HttpRequest)(implicit server: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]], mater: Materializer, ec: ExecutionContext, m: Manifest[T]): Future[T] = {
    Source.single(request)
      .via(server)
      .runWith(Sink.head).flatMap {
      resp ?
        resp.status match {
          case StatusCodes.OK | StatusCodes.NoContent ?
            m match {
              case _ if m.runtimeClass.getSimpleName == "String" ? Future.successful(resp.entity.asInstanceOf[T])
              case _ ? Unmarshal(resp.entity).to[T]
            }
          case _ ? logger.error(resp.toString()); throw new RuntimeException(s"Network error, statusCode:${resp.status}")
        }
    }
  }
} 
开发者ID:huanwuji,项目名称:teleporter,代码行数:38,代码来源:SimpleHttpClient.scala


示例8: nothingHere

//设置package包名称以及导入依赖的类
package au.edu.utscic.tap.httpServer

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import au.edu.utscic.tap.message.Exception.UnknownAnalysisType
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._




trait GenericApi extends Json4sSupport {

  import au.edu.utscic.tap.TapStreamContext._

  val version = "v2"
  val details:String = "no details yet" // ApiInfo(Config.name,Config.description,Config.version,Config.colour)
  val healthEndPoint = "health"

  val TapExceptionHandler = ExceptionHandler {
    case _: UnknownAnalysisType =>
      extractUri { uri =>
        log.error(s"Request to $uri did not include a valid analysis type")
        complete(HttpResponse(InternalServerError, entity = "The request did not include a valid analysis type"))
      }
  }

  implicit val formats: Formats = DefaultFormats
  implicit val jacksonSerialization: Serialization = jackson.Serialization

  def nothingHere =  complete(ResponseMessage("There is nothing at this URL"))

  val routes = handleExceptions(TapExceptionHandler) {
    pathSingleSlash {
      get(complete(ResponseMessage("The current version of this API can be found at /"+version)))
    } ~
      pathPrefix(version) {
        customRoutes ~
          path(healthEndPoint) {
            get(complete(ResponseMessage("ok")))
          } ~
          apiDetails ~
          adminRoutes
      }
  }

  val customRoutes = path("custom") { get(complete("")) }
  val adminRoutes = path("admin") { get(complete(""))}
  val apiDetails = pathEnd(complete(ResponseMessage(details)))
} 
开发者ID:uts-cic,项目名称:tap-api,代码行数:53,代码来源:GenericApi.scala


示例9: TapStreamRouteSpec

//设置package包名称以及导入依赖的类
import org.scalatest.{Matchers, WordSpec}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.server._
import Directives._
import au.edu.utscic.tap.httpServer.{ResponseMessage, GenericApi, TapStreamApi}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._

class TapStreamRouteSpec extends WordSpec with Matchers with ScalatestRouteTest with TapStreamApi with Json4sSupport {


  "The service" should {

    "return a greeting for GET requests to the root path" in {
      // tests:
      Get() ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "The current version of this API can be found at /v2"
      }
    }

    "return an 'ok' message for GET requests to /v2/health" in {
      // tests:
      Get("/v2/health") ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "ok"
      }
    }

    "leave GET requests to other paths unhandled" in {
      // tests:
      Get("/someOtherPath") ~> routes ~> check {
        handled shouldBe false
      }
    }

    "return a MethodNotAllowed error for PUT requests to the root path" in {
      // tests:
      Put() ~> Route.seal(routes) ~> check {
        status === StatusCodes.MethodNotAllowed
        import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers.stringUnmarshaller
        responseAs[String] shouldEqual "HTTP method not allowed, supported methods: GET"
      }
    }
  }
} 
开发者ID:uts-cic,项目名称:tap-api,代码行数:46,代码来源:TapStreamRouteSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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