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

Scala HttpEntity类代码示例

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

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



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

示例1: exportReply

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

import java.io.StringWriter

import akka.http.scaladsl.model.{ContentType, HttpEntity, HttpResponse}
import akka.util.ByteString
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports


  def exportReply: HttpResponse = {
    val writer = new StringWriter
    TextFormat.write004(writer, registry.metricFamilySamples())
    val string = writer.toString

    HttpResponse(entity = HttpEntity.Strict(HttpExport.contentType, ByteString(string)))
  }
}

object HttpExport {
  val contentType: ContentType = ContentType.parse(TextFormat.CONTENT_TYPE_004).right.get
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:24,代码来源:HttpExport.scala


示例2: HttpResponseUtil

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

import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Sink
import akka.util.ByteString

import scala.concurrent.Future
import scala.util.{Failure, Success, Try}

package object http {

  implicit final class HttpResponseUtil(responseF: Future[HttpResponse]) extends HttpClientApi {

    val entityData: Future[ByteString] =
      for {
        response <- responseF
        byteString <- {
          val source = response.entity.dataBytes
          source.runWith(Sink.head[ByteString])
        }
      } yield byteString

    def mapStrict[T](f: HttpResponse => T): Future[T] =
      for {
        response   <- responseF
        byteString <- entityData
        strictEntity = HttpEntity.Strict(response.entity.contentType, byteString)
      } yield f(response.withEntity(strictEntity))

    def entityAs[T](implicit unmarshaller: Unmarshaller[String, T]): Future[Try[T]] = {
      val result = for {
        byteString <- entityData
        t          <- unmarshaller(byteString.utf8String)
      } yield Success(t)
      result.recover {
        case t: Throwable => Failure(t)
      }
    }
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:42,代码来源:package.scala


示例3: HttpExportSpec

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

import akka.http.scaladsl.model.HttpEntity
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.{CollectorRegistry, Gauge}
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._

class HttpExportSpec extends FlatSpec with Matchers {
  "The http export object" should "include metrics provided by the collector" in {
    val export =  new HttpExport {
      override val registry: CollectorRegistry = new CollectorRegistry()
    }
    val gauge = Gauge.build("testgauge", "Test").register(export.registry)
    gauge.inc()
    val reply = export.exportReply

    val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
    val string = entity.data.utf8String
    string should containSubstring("testgauge")
  }

  it should "have the correct content type" in {
    val reply = new HttpExport {}.exportReply
    reply.entity.contentType.value.toLowerCase shouldEqual TextFormat.CONTENT_TYPE_004.toLowerCase
  }
  it should "include the default metrics" in {
    val reply = new HttpExport {}.exportReply
    val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
    val string = entity.data.utf8String
    string should containSubstring("process_cpu_seconds_total")
    string should containSubstring("jvm_classes_loaded")
  }

  private def containSubstring(expected: String) =
    Matcher[String](left => MatchResult(left.contains(expected), s"Contain $expected", s"not contain $expected"))
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:40,代码来源:HttpExportSpec.scala


示例4: MonitoringServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}

import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._

object MonitoringServer {

  lazy val logger = LoggerFactory.getLogger(getClass)

  def handleHealthchecks(registry: HealthCheckRegistry): Route = {
    path("health") {
      get {
        complete {
          val checks = registry.runHealthChecks
          val payload = JsArray(checks.map {
            case (name, result) =>
              Json.obj(
                "name" -> name,
                "healthy" -> result.isHealthy,
                "message" -> result.getMessage
              )
          }.toSeq)
          val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
          HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
        }
      }
    }
  }

  def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
           (implicit system: ActorSystem, materializer: Materializer): Unit = {
    val host = serverConfig.getString("host")
    val port = serverConfig.getInt("port")
    logger.info(s"Starting monitoring server at: $host:$port")

    val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
    import system.dispatcher
    Http()
      .bindAndHandle(routes, host, port).onComplete {
      case Success(Http.ServerBinding(address)) =>
        logger.info(s"Monitoring server started at :$address")
      case Failure(t) =>
        logger.error("Error while trying to start monitoring server", t)
    }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala


示例5: PageToDownload

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.platform

import akka.http.scaladsl.model.{HttpEntity, StatusCode}
import org.joda.time.DateTime
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.scraper.Scraped

case class PageToDownload(
  ref: PageRef
)

case class PageToEnqueue(
  ref: PageRef
)

case class DownloadedPage(
  ref: PageRef,
  time: DateTime,
  status: StatusCode,
  body: HttpEntity.Strict
)

case class ScrapedPage(
  page: DownloadedPage,
  entities: Seq[Scraped]
)

case class ProcessedPage(
  ref: PageRef
)

case class FailedPage(
  ref: PageRef,
  time: DateTime,
  reason: Option[String] = None,
  cause: Option[Throwable] = None
) 
开发者ID:fediq,项目名称:scraping-kit,代码行数:38,代码来源:entities.scala


示例6: FileUploadStream

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, Multipart, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.Framing
import akka.util.ByteString

import scala.concurrent.Future



object FileUploadStream extends BaseSpec{

  def main(args: Array[String]) {

    val route =
      extractRequestContext { ctx =>
        implicit val materializer = ctx.materializer
        implicit val ec = ctx.executionContext
 
        fileUpload("csv") {
          case (metadata, byteSource) =>
            val sumF: Future[Int] =
            // sum the numbers as they arrive so that we can
            byteSource.via(Framing.delimiter(ByteString("\n"), 1024))
              .mapConcat(_.utf8String.split(",").toVector)
              .map(_.toInt)
              .runFold(0) { (acc, n) => acc + n }
              onSuccess(sumF) { sum => complete(s"Sum: $sum") }
        }
      }

    //Test file upload stream
    val multipartForm =
      Multipart.FormData(Multipart.FormData.BodyPart.Strict(
        "csv",
        HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"),
        Map("filename" -> "primes.csv")))
 
    Post("/", multipartForm) ~> route ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual "Sum: 178"
    }

    system.terminate()
  }

}
//File upload direct
//curl --form "[email protected]" http://<host>:<port> 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:51,代码来源:FileUploadStream.scala


示例7: UtilityServiceSlice

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

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._

class UtilityServiceSlice {

  val routes: Route = {
    path("") {
      pathEnd {
        complete("here")
      }
    } ~ path("info") {
      get {
        complete(HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, buildinfo.BuildInfo.toJson)))
      }
    }
  }
} 
开发者ID:polymorphic,项目名称:akka-http-svc.g8,代码行数:21,代码来源:UtilityServiceSlice.scala


示例8: ImperativeRequestContext

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

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise


final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
  private implicit val ec = ctx.executionContext
  def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
  def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}

trait ApiHelper {

  def notImplementedResponse(msg: String = ""): StandardRoute =
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
      s"<h1>We plan to support this resource soon.</h1>"))

  def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
    val p = Promise[RouteResult]()
    inner(new ImperativeRequestContext(ctx, p))
    p.future
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala


示例9: postRequest

//设置package包名称以及导入依赖的类
package se.meldrum.machine

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Matchers, WordSpec}
import PostgresTestDb._
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpEntity, HttpMethods, HttpRequest, MediaTypes}
import akka.stream.ActorMaterializer
import akka.util.ByteString
import se.meldrum.machine.http.RestService
import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext

trait BaseSpec extends WordSpec with Matchers with ScalatestRouteTest {
  dbProcess.getProcessId
  implicit val db = Database.forConfig("postgres-test")
  implicit val sys = ActorSystem("machine")
  implicit val ec = ExecutionContext
  implicit val mat = ActorMaterializer()
  val restService = new RestService()
  val route = restService.route

  def postRequest(path: String, json: ByteString): HttpRequest =
    HttpRequest(HttpMethods.POST,
      uri = path,
      entity = HttpEntity(MediaTypes.`application/json`, json)
    )


  def userJsonRequest(name: String, pass: String, email: String): ByteString =
    ByteString(
      s"""
       |{
       |    "name":"$name",
       |    "password":"$pass",
       |    "email":"$email"
       |}
        """.stripMargin)


  def createTestUsers(): Seq[HttpRequest] = {
    val userOne = userJsonRequest("testuser", "secret", "[email protected]")
    val userTwo = userJsonRequest("testuser2", "secret", "[email protected]")
    val userThree = userJsonRequest("testuser3", "secret", "[email protected]")

    val requests = Seq(
      postRequest("/v1/user/create", userOne),
      postRequest("/v1/user/create", userTwo),
      postRequest("/v1/user/create", userThree)
    )
    requests
  }
} 
开发者ID:Max-Meldrum,项目名称:machine,代码行数:56,代码来源:BaseSpec.scala


示例10: AppReturningChunking

//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document

import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn

object AppReturningChunking extends Directives {
  
  implicit val system = ActorSystem()
  implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
  implicit val mat = ActorMaterializer()

  def main(args: Array[String]): Unit = {
    val mongoClient = MongoClients.create()
    val coll = mongoClient.getDatabase("test").getCollection("resources")

    val route =
      path("resources") {
        get {
          complete(HttpEntity(ContentTypes.`application/json`, getData(coll)))
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }

  def getData(coll: MongoCollection[Document]): Source[ByteString, NotUsed] =
    Source.fromPublisher(coll.find())
      .map(_.toJson)
      .map(ByteString(_))
      .intersperse(ByteString("["), ByteString(","), ByteString("]"))

} 
开发者ID:michalbogacz,项目名称:http-streaming,代码行数:51,代码来源:AppReturningChunking.scala


示例11: ApiReturningList

//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document

import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.io.StdIn

object ApiReturningList extends ServiceDirectives {

  implicit val system = ActorSystem()
  implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
  implicit val mat = ActorMaterializer()

  def main(args: Array[String]): Unit = {
    val mongoClient = MongoClients.create()
    val coll = mongoClient.getDatabase("test").getCollection("resources")

    val route =
      path("resources") {
        pageParams { pageParams =>
          get {
            complete(getData(coll, pageParams).map(HttpEntity(ContentTypes.`application/json`, _)))
          }
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }

  def getData(coll: MongoCollection[Document], pageParams: PageParams): Future[String] =
    Source.fromPublisher(coll.find().skip(pageParams.skip).limit(pageParams.limit))
      .map(_.toJson)
      .intersperse("[", ",", "]")
      .runFold("")((acc, e) ? acc + e)


} 
开发者ID:michalbogacz,项目名称:http-streaming,代码行数:51,代码来源:ApiReturningList.scala


示例12: WebServer

//设置package包名称以及导入依赖的类
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn
import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.model.ContentTypes
 
object WebServer {
  def main(args: Array[String]) {
 
    implicit val system = ActorSystem("my-system")
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher
 
    val route =
      path("hello") {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
        }
      }
 
    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
 
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ ? system.terminate()) // and shutdown when done
  }
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:33,代码来源:WebServer.scala


示例13: unmarshaller

//设置package包名称以及导入依赖的类
package com.github.bots4s.telegramkit.client

import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToEntityMarshaller}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}

import com.github.bots4s.telegramkit.marshalling.{BotMarshaller, BotUnmarshaller}
import com.github.bots4s.telegramkit.method.{BotApiRequest, BotApiRequestJson, BotApiRequestMultipart}
import com.github.bots4s.telegramkit.model._


private[client] trait HttpMarshalling { this: BotApiClient =>
  implicit def unmarshaller[T: Manifest](implicit um: BotUnmarshaller[T]): FromEntityUnmarshaller[T] = {
    Unmarshaller.stringUnmarshaller.map(body => um(body))
  }

  implicit def marshaller[T](implicit m: BotMarshaller[BotApiRequestJson[T]]): ToEntityMarshaller[BotApiRequest[T]] = {
    Marshaller.strict {
      case request: BotApiRequestJson[T] =>
        val content = m(request)
        Marshalling.Opaque(() => HttpEntity(ContentTypes.`application/json`, content))
      case request: BotApiRequestMultipart[T] =>
        def flatten(value: Any): Any = value match {
          case Some(x) => flatten(x)
          case e: Either[_, _] => flatten(e.fold(identity, identity))
          case _ => value
        }
        val fields = request.getClass.getDeclaredFields.iterator.zip(request.productIterator).map {
          case (k, v) => HttpMarshalling.snakeCase(k.getName) -> flatten(v)
        }.filterNot(_._2 == None)

        if (fields.isEmpty) {
          Marshalling.Opaque(() => HttpEntity.empty(ContentTypes.`application/octet-stream`))
        } else {
          val parts = fields map {
            case (k, v @ (_: String | _: Boolean | _: Long | _: Float)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(v.toString))
            case (k, InputFile.InputFilePath(path)) =>
              Multipart.FormData.BodyPart.fromPath(k, MediaTypes.`application/octet-stream`, path)
            case (k, InputFile.InputFileData(filename, bs)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(ContentTypes.`application/octet-stream`, bs), Map("filename" -> filename))
            case (k, other) =>
              log.warning(s"unexpected field in multipart request, $k: $other")
              Multipart.FormData.BodyPart(k, HttpEntity(""))
          }
          Marshalling.Opaque(() => Multipart.FormData(parts.toSeq: _*).toEntity())
        }
    }
  }
}

private[client] object HttpMarshalling {
  private val CapitalLetter = "[A-Z]".r
  def snakeCase(s: String): String =
    CapitalLetter.replaceAllIn(s, { "_" + _.group(0).toLowerCase })
} 
开发者ID:bots4s,项目名称:TelegramKit,代码行数:57,代码来源:HttpMarshalling.scala


示例14: ClientsServiceTest

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

import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import gateway.restapi.domain.ClientEnitity
import io.circe.generic.auto._
import org.scalatest.concurrent.ScalaFutures

class ClientsServiceTest extends BaseServiceTest with ScalaFutures {

  trait Context {
    val cleanUp = cleanContext
    val testClients = provisionClientsList(5)
    val route = httpService.clientsRouter.route
  }

  "Users service" should {

    "retrieve empty clients list" in new Context {
      cleanContext
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(0)
      }
    }

    "retrieve clients list" in new Context {
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(5)
      }
    }

    "retrieve client by id" in new Context {
      val testClient = testClients(4)
      Get(s"/clients/${testClient.id.get}") ~> route ~> check {
        responseAs[ClientEnitity] should be(testClient)
      }
    }

    "create a new client" in new Context {
      val newClientName = "Smith Test"
      val requestEntity = HttpEntity(MediaTypes.`application/json`, s"""{"name": "$newClientName"}""")
      Post("/clients/", requestEntity) ~> route ~> check {
        responseAs[ClientEnitity].name should be(newClientName)
      }
    }
  }
} 
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:47,代码来源:ClientsServiceTest.scala


示例15: WebServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.{complete, get, path}
import akka.stream.ActorMaterializer

import scala.io.StdIn

object WebServer extends App {
  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher

  val route =
    path("hello") {
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
      }
    }

  val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
} 
开发者ID:hiroinamine,项目名称:akka-labs,代码行数:32,代码来源:WebServer.scala


示例16: CatalogueRoutesTest

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


import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.techmonad.es.{CatalogueRepository, ESTestHelper}
import org.scalatest.{Matchers, WordSpec}


class CatalogueRoutesTest extends WordSpec with Matchers with ScalatestRouteTest with CatalogueRoutes with MockedCatalogueRepository {

  "Catalogue service " should {
    "accept and add record to catalogue " in {
      val requestJson = """{"id":4,"type":"book","author":"Rúnar Bjarnason","title":"Functional programming in Scala"}"""
      Post("/catalogue/add", HttpEntity(ContentTypes.`application/json`, requestJson)) ~> routes ~> check {
        responseAs[String] shouldEqual "Record added to catalogue successfully"
      }
    }
    "search by query" in {
      val queryJson = """{"author":"martin"}"""
      Post("/catalogue/search", HttpEntity(ContentTypes.`application/json`, queryJson)) ~> routes ~> check {
        responseAs[String] shouldEqual """[{"id":2,"type":"book","author":"Martin Odersky","title":"Programming in Scala"}]"""
      }
    }


  }
}


trait MockedCatalogueRepository extends CatalogueRepository with ESTestHelper {
  override def ingest(docs: List[Map[String, Any]]): Boolean = true

  override def searchByQuery(params: Map[String, Any]): String =
    """[{"id":2,"type":"book","author":"Martin Odersky","title":"Programming in Scala"}]"""

  override def ingest(doc: Map[String, Any]): Boolean = true
} 
开发者ID:techmonad,项目名称:activator-akka-http-elasticsearch,代码行数:39,代码来源:CatalogueRoutesTest.scala


示例17: StartBot

//设置package包名称以及导入依赖的类
package me.kkanojia.hipbot

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import me.kkanojia.hipbot.models.WebHook
import me.kkanojia.hipbot.serializers.JsonSupport
import me.kkanojia.hipbot.service.BotService

import scala.concurrent.duration._

object StartBot extends App with JsonSupport{

  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher
  implicit val timeout = Timeout(20 seconds)

  val config = ConfigFactory.load()
  val logger = Logging(system, getClass)


  lazy val botService = new BotService


  val route =
    path("") {
      logger.info("Bot Called >>")
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Bot says hello</h1>"))
      } ~
        post {
          entity(as[WebHook]) { order =>
            logger.info("Received a message" + order.toString)
            val commandResult = botService.getCommandResponse(order)
            complete(commandResult)
          }
        }
    }

  val systemPort = System.getenv("PORT")
  val port = if(systemPort == null) config.getInt("http.port") else systemPort.toInt

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

  logger.info("Bot Started")

} 
开发者ID:kunalkanojia,项目名称:hip-chat-bot,代码行数:55,代码来源:StartBot.scala


示例18: modifiedLar

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

import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import akka.http.scaladsl.model.{ ContentTypes, HttpEntity, HttpResponse }
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import hmda.api.EC
import hmda.api.http.HmdaCustomDirectives
import hmda.query.DbConfiguration._
import hmda.query.repository.filing.FilingComponent

trait PublicLarHttpApi extends HmdaCustomDirectives with FilingComponent {

  implicit val system: ActorSystem
  implicit val materializer: ActorMaterializer
  val log: LoggingAdapter

  val modifiedLarRepository = new ModifiedLarRepository(config)

  def modifiedLar[_: EC](institutionId: String) =
    path("filings" / Segment / "lar") { period =>
      timedGet { _ =>
        val data = modifiedLarRepository.findByInstitutionIdSource(institutionId, period)
          .map(x => ChunkStreamPart(x.toCSV + "\n"))
        val response = HttpResponse(entity = HttpEntity.Chunked(ContentTypes.`text/csv(UTF-8)`, data))
        complete(response)
      }
    }

} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:33,代码来源:PublicLarHttpApi.scala


示例19: extractFormData

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives

import java.io.File

import akka.Done
import akka.http.scaladsl.model.{HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import akka.stream.scaladsl.FileIO
import com.flipkart.connekt.commons.utils.StringUtils._
import com.flipkart.connekt.receptors.directives.MultiPartFormData._

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try


  def extractFormData: Directive1[Map[Name,  Either[Value, FileInfo]]] = {
    Directive[Tuple1[Map[Name,  Either[Value, FileInfo]]]] { inner =>
      extractMaterializer { implicit mat =>
        extractExecutionContext { implicit ec =>
          uploadFileImpl(mat, ec) { filesFuture =>
            ctx => {
              filesFuture.map(map => inner(Tuple1(map))).flatMap(route => route(ctx))
            }
          }
        }
      }
    }
  }

  def downloadFile(file: String): Route = {
    val f = new File(file)
    val responseEntity = HttpEntity(
      MediaTypes.`application/octet-stream`,
      f.length,
      FileIO.fromFile(f, chunkSize = 262144))
    complete(responseEntity)
  }
}


object MultiPartFormData {

  //form field name
  type Name = String
  type Value = String

  case class FileInfo(fileName: String, tmpFilePath: String, status: Try[Done])
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:51,代码来源:FileDirective.scala


示例20: CallbackRouteTest

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.tests.routes.callbacks

import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import com.flipkart.connekt.receptors.routes.callbacks.CallbackRoute
import com.flipkart.connekt.receptors.tests.routes.BaseRouteTest

class CallbackRouteTest extends BaseRouteTest {

  val mssgId = "7a4df25c383d4c7a9438c478ddcadd1f2"
  val deviceId = "d7ae09474408d039ecad4534ed040f4a"
  val appName = "RetailApp"
  val mobilePlatform = "android"

  "Callback Test " should "return Ok" in {
    val callbackRoute = new CallbackRoute().route
    val payload =
      s"""
         |{
         |	"type": "PN",
         |	"eventType": "received",
         |	"timestamp": 1449597968,
         |	"messageId": "$mssgId",
         |	"contextId": "connekt-wx-01"
         |}
      """.stripMargin

    Post(s"/v1/push/callback/$mobilePlatform/$appName/$deviceId", HttpEntity(MediaTypes.`application/json`, payload)).addHeader(header) ~>
      callbackRoute ~>
      check {
        status shouldEqual StatusCodes.OK
      }

    Delete(s"/v1/push/callback/$mobilePlatform/$appName/$deviceId/$mssgId").addHeader(header) ~> callbackRoute ~>
      check {
        status shouldEqual StatusCodes.OK
      }
  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:40,代码来源:CallbackRouteTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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