标签: spray

将多态案例类转换为json并返回

我试图在scala中使用spray-json来识别转换为Json和返回时Ec2Provider和OpenstackProvider之间的选择.我希望能够在"提供者"中做出选择,如果这些选择不符合可用的选择,那么它就不应该验证.

我在这方面的尝试可以在以下代码中看到:

import spray.json._
import DefaultJsonProtocol._ 

case class Credentials(username: String, password: String)
abstract class Provider
case class Ec2Provider(endpoint: String,credentials: Credentials) extends Provider
case class OpenstackProvider(credentials: Credentials) extends Provider
case class Infrastructure(name: String, provider: Provider, availableInstanceTypes: List[String])
case class InfrastructuresList(infrastructures: List[Infrastructure])

object Infrastructures extends App with DefaultJsonProtocol {
   implicit val credFormat = jsonFormat2(Credentials)
   implicit val ec2Provider = jsonFormat2(Ec2Provider)
   implicit val novaProvider = jsonFormat1(OpenstackProvider)
   implicit val infraFormat = jsonFormat3(Infrastructure)
   implicit val infrasFormat = jsonFormat1(InfrastructuresList)

  println(
    InfrastructuresList(
      List(
        Infrastructure("test", Ec2Provider("nova", Credentials("user","pass")), List("1", "2")) …
Run Code Online (Sandbox Code Playgroud)

json scala spray spray-json

9
推荐指数
1
解决办法
4056
查看次数

如何指定喷涂Content-Type响应头?

我知道喷雾为我做了这个,但我仍然希望用我的标题覆盖它,我怎样才能覆盖响应中的标题?

我的回答如下:

case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
  sender ! HttpResponse(entity = """{ "key": "value" }""" // here i want to specify also response header i would like to explicitly set it and not get it implicitly
Run Code Online (Sandbox Code Playgroud)

scala akka spray

9
推荐指数
1
解决办法
1万
查看次数

在Spray POST路由中将Raw JSON提取为String

我有一个POST Spray路由,请求包含一个JSON主体(内容类型"application/json").我想要一种方法从我的路线中的这个请求中提取原始JSON.

对于http:// host:port/somepath/value1我想将post体提取TextMsgResponse.但是对于http:// host:port/somepath/value2我想提取 post体就像一个原始的Json(例如,{ "name":"Jack", "age":30 }

val myRoute = path("somepath" / Segment) { pathSegment => 
post {   //use only POST requests
  pathSegment match {
    case "value1" =>
      entity(as[TextMsgResponse]) { textMsg =>
        complete {
          //do something with the request
          StatusCodes.OK
        }
      } 
    case "value2" => { 
       //here is I want to extract the RAW JSON from the request          
      } 
    }
   }
Run Code Online (Sandbox Code Playgroud)

rest post json scala spray

9
推荐指数
1
解决办法
2880
查看次数

如何解构Spray API HTTPResponse?

我正在使用Spray API(spray-client)来访问内部Solr URL,我希望能够将响应解析为Scala案例类.

如果我只是期望和HTTPResponse,我得到一个值,但是当我尝试将它编组到我的case类中时,它失败了(我不能生成除null()以外的消息,因为我正在使用匹配和显然没有得到正确的测试用例.)

我认为我的一些问题是它以数据的形式返回数据text/plain而不是application/json.当我期待HttpResponse而不是我的案例类时,

val f: Future[HttpResponse] =
    (IO(Http) ? Get("http://1.2.3.4:8983/solr/collection1/select?q=*%3A*&wt=json")).mapTo[HttpResponse]
Run Code Online (Sandbox Code Playgroud)

我明白了:

HttpResponse(200 OK,HttpEntity(text/plain; charset=UTF-8,
{
  "responseHeader":{"status":0,"QTime":65,"params":{"q":"*:*","wt":"json"}},
  "response":{"numFound":147437873,"start":0,"maxScore":1.0,"docs":
    [
      {"guid":"TLQ0jVlMYCXQrYkBIZHNXfMmifw+3","alias":["greg"],"_version_":1440942010264453120},
      {"guid":"TQsDY1ZG7q+Ne5e6F7qAUhFyomSH9","_version_":1440942010296958976},
      {"guid":"TzWB5grOBAJJZcAQDo2k9xBUVGPFr","alias":["spark"],"_version_":1440942010298007552},
      {"guid":"T0judCG4UI9RYqDDQVcn+gyZEU7Bb","alias":["zombie"],...),List(Connection: close, Content-Type: text/plain; charset=UTF-8),HTTP/1.1)
Run Code Online (Sandbox Code Playgroud)

但是当我改变它以期待我的案例类时,我无法比拟.那么,我如何编组它返回到Scala案例类的数据呢?这是我尝试过的:

case class SolrParams(q: String, wt: String)
case class SolrResponseHeader(status: String, qtime: String, params: SolrParams)
case class SolrDoc(guid: String, alias: List[String], version: String)
case class SolrResponse(numFound: Long, start: Long, maxScore: String, docs: List[SolrDoc])

case class SolrApResult(responseHeader: SolrResponseHeader, response: SolrResponse)

object SolrJsonProtocol extends DefaultJsonProtocol {
  implicit val paramsFormat = …
Run Code Online (Sandbox Code Playgroud)

solr scala akka spray

8
推荐指数
1
解决办法
4462
查看次数

喷涂路由:如何响应不同的内容类型?

在喷涂中,我想根据给定的Accept标题响应不同的内容类型.我在rompetroll问题中看到了一些建议,但我想听听是否有任何规范的方法(即简单或已经实现).

从本质上讲,我想象的应该是:

path("somepath") {
  get {
    // Find whatever we would like to return (lazily)
    ...
    // Marshall resource and complete depending on the `Accept` header
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

routing scala http-headers spray http-accept-header

8
推荐指数
2
解决办法
4477
查看次数

Scala:接收服务器发送事件

建立:

我正在处理的项目有一个带有HTTP接口的pub/sub服务器.订阅通过接受服务器发送事件来工作.

curl -X GET server:port/topics/news
Run Code Online (Sandbox Code Playgroud)

每当消息发布到给定主题URL时将被推送

curl -X PUT server:port/topics/news -d "Politician Lies!"
Run Code Online (Sandbox Code Playgroud)

问题:

我有一个scala项目需要订阅这个pub/sub服务器.表演!框架能够通过使用带有Enumeratee + Iteratee的PlayWS来处理这个问题.不幸的是,PlayWS库需要Play!应用程序在范围内,我不使用Play.是否有一个库(具有最小的依赖性)我可以使用它允许我接受服务器发送事件?我需要至少一个工作示例才能开始使用.

我喜欢scala库,但如果必须,我愿意接受Java解决方案.

scala http server-sent-events spray playframework-2.0

8
推荐指数
1
解决办法
1304
查看次数

Scala - 避免过于复杂的嵌套模式匹配

我尝试简化在Spray中为HTTP请求提供响应的验证过程(我使用Slick进行数据库访问).目前,我检查一个查询是否应该进一步查询以下查询(返回错误).最终会出现嵌套模式匹配.每个验证案例都可以返回不同的错误,因此我无法使用任何flatMap.

class LocationDao {
  val db = DbProvider.db

  // Database tables
  val devices = Devices.devices
  val locations = Locations.locations
  val programs = Programs.programs
  val accessTokens = AccessTokens.accessTokens

def loginDevice(deviceSerialNumber: String, login: String, password: String): Either[Error, LocationResponse] = {
    try {
      db withSession { implicit session =>
        val deviceRowOption = devices.filter(d => d.serialNumber === deviceSerialNumber).map(d => (d.id, d.currentLocationId.?, d.serialNumber.?)).firstOption
        deviceRowOption match {
          case Some(deviceRow) => {
            val locationRowOption = locations.filter(l => l.id === deviceRow._2.getOrElse(0L) && l.login === login && l.password === …
Run Code Online (Sandbox Code Playgroud)

scala pattern-matching spray slick

8
推荐指数
1
解决办法
4239
查看次数

Spray中的jsonFormatN中的N是什么意思?

我正在看由eigengo编写的Typesafe的Activator中的“ Akka and Spray ”教程的代码。我没有定义jsonFormat1,jsonFormat2,...的位置以及jsonFormatN的工作方式。

implicit val sendMessageFormat = jsonFormat2(SendMessage)

上面的代码片段在scala> api> MessengerService.scala中

谢谢。

json marshalling spray

8
推荐指数
1
解决办法
1380
查看次数

在1秒的Scala Spray Testing中,请求既未完成也未被拒绝

我目前正在测试一个Web服务,并且我一直在遇到Web服务测试失败的错误,因为它已超时.我试图将超时延长到5秒.我试图模仿一个解决方案,一些人发布在Scala Spray谷歌组论坛上无济于事.这是我试图在我的测试中使用的代码:

import akka.testkit._
import akka.actor.ActorSystem
import com.github.nfldb.config.{NflDbApiActorSystemConfig, NflDbApiDbConfigTest}
import org.scalatest.MustMatchers
import org.specs2.mutable.Specification
import spray.testkit.Specs2RouteTest
import spray.routing.HttpService
import spray.http.StatusCodes._
import spray.json.DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport._
import concurrent.duration._

/**
 * Created by chris on 8/25/15.
 */
class NflPlayerScoringSvcTest extends Specification with Specs2RouteTest  with NflPlayerScoringService
  with NflDbApiDbConfigTest with NflDbApiActorSystemConfig {
  import PlayerScoreProtocol.playerScoreProtocol
  implicit def actorRefFactory = actorSystem
  implicit def default(system: ActorSystem = actorSystem) = RouteTestTimeout(new DurationInt(5).second.dilated)

  "NflPlayerScoringSvc" should {

    "return hello" in {
      Get("/hello") ~> nflPlayerScoringServiceRoutes ~> check {
        responseAs[String] must contain("Say …
Run Code Online (Sandbox Code Playgroud)

scala spray

8
推荐指数
2
解决办法
3978
查看次数

在docker容器中使用akka应用程序的问题

我们有一个以非集群模式在生产中运行的akka​​应用程序(不是akka集群).我们正在尝试将此应用程序停靠,并遇到问题.我们正在使用docker主机网络,并且由于各种其他原因,我们尚未准备好使用其他类型的网络.

应用程序绑定到端口9080上的0.0.0.0接口,并对其自身进行简单的http运行状况检查.此运行状况检查失败,因为我们看到连接重置错误.我们只在docker容器内看到这个.

在启动时,应用程序绑定到0:0:0:0:0:0:0:0:9080.2018-04-13T08:29:54.921-0700 [INFO] - 绑定到/ 0:0:0:0:0:0:0:0:9080

akka日志:

2018-04-13T08:34:25.311-0700 [DEBUG] akka.io.TcpListener            [15:34:25.311UTC] - New connection accepted
2018-04-13T08:34:25.312-0700 [DEBUG] akka.io.SelectionHandler       [15:34:25.312UTC] - now supervising Actor[akka://appname/system/IO-TCP/selectors/$d/12#394551476]
2018-04-13T08:34:25.312-0700 [DEBUG] akka.io.TcpIncomingConnection  [15:34:25.312UTC] - started (akka.io.TcpIncomingConnection@1dafecc7)
2018-04-13T08:34:25.312-0700 [DEBUG] akka.io.TcpIncomingConnection  [15:34:25.312UTC] - now watched by Actor[akka://appname/system/IO-TCP/selectors/$d#992175932]
2018-04-13T08:34:25.312-0700 [DEBUG] akka.io.TcpIncomingConnection  [15:34:25.312UTC] - now watched by Actor[akka://appname/user/IO-HTTP/listener-0/88#-1187840999]
2018-04-13T08:34:25.313-0700 [DEBUG] akka.io.SelectionHandler       [15:34:25.313UTC] - now supervising Actor[akka://appname/system/IO-TCP/selectors/$h/11#789402148]
2018-04-13T08:34:25.313-0700 [DEBUG] akka.io.TcpOutgoingConnection  [15:34:25.313UTC] - started (akka.io.TcpOutgoingConnection@62c77639)
2018-04-13T08:34:25.313-0700 [DEBUG] akka.io.TcpOutgoingConnection  [15:34:25.313UTC] - now watched by Actor[akka://appname/system/IO-TCP/selectors/$h#227381172]
2018-04-13T08:34:25.313-0700 [DEBUG] akka.io.TcpOutgoingConnection  [15:34:25.313UTC] - Attempting connection …
Run Code Online (Sandbox Code Playgroud)

akka spray docker

8
推荐指数
1
解决办法
473
查看次数