akka.http.scaladsl.model.ContentTypes 代码实例
以下是展示如何使用akka.http.scaladsl.model.ContentTypes的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。
实例 1
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,5n7,11,13,17,23n29,31,37n"), 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>
实例 2
package de.innfactory.bootstrap import akka.http.scaladsl.model.ContentTypes import com.github.swagger.akka.CustomMediaTypes import de.innfactory.bootstrap.services.SwaggerDocService import de.innfactory.bootstrap.utils.Configuration import akka.http.scaladsl.model.ContentTypes._ import akka.http.scaladsl.model.StatusCodes._ import org.scalatest.BeforeAndAfterAll class MinimalSwaggerHttpServiceSpec extends BaseServiceTest with BeforeAndAfterAll with Configuration { override def afterAll: Unit = { super.afterAll() system.terminate() } trait Context { val swaggerDocService = new SwaggerDocService(httpHost, httpPort, system) val route = httpService.swaggerDocService.routes val uiroute = httpService.swaggerRouter.route } "The SwaggerHttpService" when { "accessing the root doc path" should { "return the basic set of api info" in new Context { Get(s"/${swaggerDocService.apiDocsPath}/swagger.json") ~> route ~> check { handled shouldBe true contentType shouldBe `application/json` } } "return the basic set of api info in yaml" in new Context { Get(s"/${swaggerDocService.apiDocsPath}/swagger.yaml") ~> route ~> check { handled shouldBe true contentType shouldBe CustomMediaTypes.`text/vnd.yaml`.toContentType } } } "accessing the swagger ui" should { "return the html ui" in new Context { Get(s"/swagger/index.html") ~> uiroute ~> check { handled shouldBe true status shouldBe OK contentType shouldBe `text/html(UTF-8)` } } } } }
实例 3
package com.tpalanga.test.account.api.users import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ContentTypes, RequestEntity} import akka.stream.{ActorMaterializer, ActorMaterializerSettings, Materializer} import com.tpalanga.test.account.api.users.model.{NewUser, User, Users} import com.tpalanga.test.config.TestConfig import com.tpalanga.testlib.test.client.{NoEntity, Response, RestServiceClient} import com.tpalanga.testlib.test.config.RestServiceConfig import com.typesafe.scalalogging.LazyLogging import scala.concurrent.{ExecutionContext, Future} class AccountServiceRestClient(val restServiceConfig: RestServiceConfig) (implicit val testConfig: TestConfig, val system: ActorSystem) extends RestServiceClient with LazyLogging { import NoEntity.DataFormats._ import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import com.tpalanga.test.account.api.users.model.UserJsonProtocol._ logger.debug(s"AccountServiceRestServiceClient: $restServiceConfig") private implicit val materializer: Materializer = ActorMaterializer(ActorMaterializerSettings(system)) def userRetrieve(id: String)(implicit ec: ExecutionContext): Future[Response[User]] = client.get(s"/data/users/$id").map { httpResponse => Response[User](httpResponse) } def userCreate(user: NewUser)(implicit ec: ExecutionContext): Future[Response[User]] = for { entity <- Marshal(user).to[RequestEntity] httpResponse <- client.post(s"/data/users", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[User](httpResponse) def userUpdate(user: User)(implicit ec: ExecutionContext): Future[Response[User]] = for { entity <- Marshal(user).to[RequestEntity] httpResponse <- client.put(s"/data/users/${user.id}", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[User](httpResponse) def userDelete(id: String)(implicit ec: ExecutionContext): Future[Response[NoEntity]] = client.delete(s"/data/users/$id").map { httpResponse => Response[NoEntity](httpResponse) } def userList()(implicit ec: ExecutionContext): Future[Response[Users]] = client.get(s"/data/users").map { httpResponse => Response[Users](httpResponse) } }
实例 4
package com.tpalanga.testlib.test.client.impl import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ContentTypes, RequestEntity} import akka.stream.{ActorMaterializer, ActorMaterializerSettings, Materializer} import com.tpalanga.testlib.test.client.{NoEntity, Response, RestServiceClient} import com.tpalanga.testlib.test.config.RestServiceConfig import com.typesafe.scalalogging.LazyLogging import scala.concurrent.{ExecutionContext, Future} object NewsletterServiceRestClient { type NewsletterServiceRestClientFactory = (RestServiceConfig, ActorSystem) => NewsletterServiceRestClient def defaultFactory: NewsletterServiceRestClientFactory = (config, system) => new NewsletterServiceRestClient(config)(system) } class NewsletterServiceRestClient(val restServiceConfig: RestServiceConfig) (implicit val system: ActorSystem) extends RestServiceClient with LazyLogging { import NoEntity.DataFormats._ import SubscriberJsonProtocol._ import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ logger.debug(s"NewsletterServiceRestServiceClient: $restServiceConfig") private implicit val materializer: Materializer = ActorMaterializer(ActorMaterializerSettings(system)) def subscriberRetrieve(id: String)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = client.get(s"/data/subscribers/$id").map { httpResponse => Response[Subscriber](httpResponse) } def subscriberCreate(subscriber: Subscriber)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = for { entity <- Marshal(subscriber).to[RequestEntity] httpResponse <- client.post(s"/data/subscribers", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[Subscriber](httpResponse) def subscriberUpdate(user: Subscriber)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = for { entity <- Marshal(user).to[RequestEntity] httpResponse <- client.put(s"/data/subscribers/${user.id}", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[Subscriber](httpResponse) def subscriberDelete(id: String)(implicit ec: ExecutionContext): Future[Response[NoEntity]] = client.delete(s"/data/subscribers/$id").map { httpResponse => Response[NoEntity](httpResponse) } def subscriberList()(implicit ec: ExecutionContext): Future[Response[Subscribers]] = client.get(s"/data/subscribers").map { httpResponse => Response[Subscribers](httpResponse) } }
实例 5
package com.tpalanga.test.newsletter.api.subscriber import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ContentTypes, RequestEntity} import akka.stream.{ActorMaterializer, ActorMaterializerSettings, Materializer} import com.tpalanga.test.config.TestConfig import com.tpalanga.test.newsletter.api.subscriber.model.{Subscriber, Subscribers} import com.tpalanga.testlib.test.client.{NoEntity, Response, RestServiceClient} import com.tpalanga.testlib.test.config.RestServiceConfig import scala.concurrent.{ExecutionContext, Future} trait NewsletterServiceRestServiceClient extends RestServiceClient { import NoEntity.DataFormats._ import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import com.tpalanga.test.newsletter.api.subscriber.model.SubscriberJsonProtocol._ val testConfig: TestConfig override val restServiceConfig: RestServiceConfig = testConfig.restServiceConfig private implicit val materializer: Materializer = ActorMaterializer(ActorMaterializerSettings(system)) def subscriberRetrieve(id: String)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = client.get(s"/data/subscribers/$id").map { httpResponse => Response[Subscriber](httpResponse) } def subscriberCreate(subscriber: Subscriber)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = for { entity <- Marshal(subscriber).to[RequestEntity] httpResponse <- client.post(s"/data/subscribers", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[Subscriber](httpResponse) def subscriberUpdate(user: Subscriber)(implicit ec: ExecutionContext): Future[Response[Subscriber]] = for { entity <- Marshal(user).to[RequestEntity] httpResponse <- client.put(s"/data/subscribers/${user.id}", Nil, entity.withContentType(ContentTypes.`application/json`)) } yield Response[Subscriber](httpResponse) def subscriberDelete(id: String)(implicit ec: ExecutionContext): Future[Response[NoEntity]] = client.delete(s"/data/subscribers/$id").map { httpResponse => Response[NoEntity](httpResponse) } def subscriberList()(implicit ec: ExecutionContext): Future[Response[Subscribers]] = client.get(s"/data/subscribers").map { httpResponse => Response[Subscribers](httpResponse) } }
实例 6
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))) } } } }
实例 7
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 } }
实例 8
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("]")) }
实例 9
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) }
实例 10
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 } }
实例 11
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 }) }
实例 12
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 }
实例 13
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 }
实例 14
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") }
实例 15
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) } } }