当前位置: 首页>>代码示例>>Scala>>正文


Scala ContentTypes类代码示例

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


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

示例1: ConsulStoreActorMapper

//设置package包名称以及导入依赖的类
package io.vamp.persistence.consul

import java.util.Base64

import akka.http.scaladsl.model.ContentTypes
import io.vamp.common.{ ClassMapper, Config }
import io.vamp.persistence.KeyValueStoreActor

import scala.concurrent.Future

class ConsulStoreActorMapper extends ClassMapper {
  val name = "consul"
  val clazz = classOf[ConsulStoreActor]
}

class ConsulStoreActor extends KeyValueStoreActor {

  private lazy val url = Config.string("vamp.persistence.key-value-store.consul.url")()

  override protected def info(): Future[Any] = httpClient.get[Any](s"$url/v1/agent/self") map { consul ?
    Map("type" ? "consul", "consul" ? consul)
  }

  override protected def all(path: List[String]): Future[List[String]] = {
    val key = pathToString(path)
    checked[List[String]](httpClient.get[List[String]](urlOf(path, keys = true), logError = false) recover { case _ ? Nil }) map { list ?
      list.map(_.substring(key.length))
    }
  }

  override protected def get(path: List[String]): Future[Option[String]] = {
    httpClient.get[List[_]](urlOf(path), logError = false) recover { case _ ? None } map {
      case head :: Nil ? Option(result(head.asInstanceOf[Map[_, _]]))
      case _           ? None
    }
  }

  override protected def set(path: List[String], data: Option[String]): Future[Any] = data match {
    case None        ? httpClient.delete(urlOf(path), logError = false)
    case Some(value) ? httpClient.put[Any](urlOf(path), value, contentType = ContentTypes.`text/plain(UTF-8)`)
  }

  private def urlOf(path: List[String], keys: Boolean = false) = {
    s"$url/v1/kv${pathToString(path)}${if (keys) "?keys" else ""}"
  }

  private def result(map: Map[_, _]): String = map.asInstanceOf[Map[String, _]].get("Value") match {
    case Some(value) if value != null ? new String(Base64.getDecoder.decode(value.asInstanceOf[String]))
    case _                            ? ""
  }
} 
开发者ID:magneticio,项目名称:vamp-consul,代码行数:52,代码来源:ConsulStoreActor.scala

示例2: Marshalling

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala

示例3: 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

示例4: MinimalSwaggerHttpServiceSpec

//设置package包名称以及导入依赖的类
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)`
        }
      }
    }
  }

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:53,代码来源:SwaggerHttpServiceSpec.scala

示例5: AccountServiceRestClient

//设置package包名称以及导入依赖的类
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)
    }
} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:52,代码来源:AccountServiceRestClient.scala

示例6: NewsletterServiceRestClient

//设置package包名称以及导入依赖的类
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)
    }

} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:60,代码来源:NewsletterServiceRestClient.scala

示例7: subscriberRetrieve

//设置package包名称以及导入依赖的类
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)
    }

} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:51,代码来源:NewsletterServiceRestServiceClient.scala

示例8: 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

示例9: 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

示例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: 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

示例15: 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


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