本文整理汇总了Scala中akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport类的典型用法代码示例。如果您正苦于以下问题:Scala SprayJsonSupport类的具体用法?Scala SprayJsonSupport怎么用?Scala SprayJsonSupport使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SprayJsonSupport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DateJsonFormat
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import java.sql.Date
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.durooma.api.model._
import com.durooma.db.Tables
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import spray.json.{DefaultJsonProtocol, DeserializationException, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit object DateJsonFormat extends RootJsonFormat[DateTime] {
private val parserISO : DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis()
override def write(obj: DateTime) = JsString(parserISO.print(obj))
override def read(json: JsValue) : DateTime = json match {
case JsString(s) => parserISO.parseDateTime(s)
case _ => throw DeserializationException("Invalid date format: " + json)
}
}
implicit object SqlDateJsonFormat extends RootJsonFormat[Date] {
override def write(obj: Date) = JsString(obj.toString)
override def read(json: JsValue) = json match {
case JsString(s) => Date.valueOf(s)
case _ => throw DeserializationException("Invalid date format: " + json)
}
}
implicit val userFormat = jsonFormat5(User.apply)
implicit val userRegistrationFormat = jsonFormat5(UserRegistration.apply)
implicit val accountFormat = jsonFormat4(Account.apply)
implicit val accounBodyFormat = jsonFormat2(AccountBody.apply)
implicit val labelFormat = jsonFormat3(Tables.LabelRow.apply)
implicit val transactionFormat = jsonFormat8(Transaction.apply)
implicit val transactionBodyFormat = jsonFormat7(TransactionBody.apply)
implicit val sessionFormat = jsonFormat3(Session.apply)
implicit val credentialsFormat = jsonFormat2(CustomCredentials.apply)
}
示例2: ApiSpec
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory
import scala.concurrent.duration._
import scalikejdbc._
abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
case class FixtureParam(api: Api, webHookActorProbe: TestProbe)
val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")
// Stop Flyway from producing so much spam that Travis terminates the process.
LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)
val flyway = new Flyway()
flyway.setDataSource(databaseUrl, "postgres", "")
flyway.setSchemas("test")
flyway.setLocations("classpath:/sql")
override def testConfigSource =
s"""
|db.default.url = "${databaseUrl}?currentSchema=test"
|authorization.skip = true
|akka.loglevel = INFO
""".stripMargin
override def withFixture(test: OneArgTest) = {
val webHookActorProbe = TestProbe()
val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)
webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)
DB localTx { implicit session =>
sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
sql"CREATE SCHEMA test".update.apply()
}
flyway.migrate()
super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
}
}
示例3: Person
//设置package包名称以及导入依赖的类
package com.opalab.proto.models
import java.util.UUID
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
import spray.json._
trait JsonSupportProtocols extends DefaultJsonProtocol with SprayJsonSupport {
implicit val personProtocol = jsonFormat3(Person.apply)
}
case class Person(
first_name: String,
last_name: Option[String] = None,
var uuid: Option[String] = Some(UUID.randomUUID().toString)
) {
def asTuple = {
this.uuid = Some(this.uuid.getOrElse(UUID.randomUUID().toString))
this.uuid.get -> this
}
}
object Person extends JsonSupportProtocols
示例4: BooksFoundFormat
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog.protocols
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BookAdded, BooksFound}
import reactivemongo.bson.BSONObjectID
import spray.json.{DefaultJsonProtocol, JsArray, JsObject, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val BookAddedFormat = jsonFormat1(BookAdded.apply)
implicit object BooksFoundFormat extends RootJsonFormat[BooksFound] {
override def read(json: JsValue): BooksFound = ???
override def write(b: BooksFound): JsValue = JsObject(
"books" -> JsArray(b.books.map(book => BookFormat.write(book)).toVector)
)
}
implicit object BookFormat extends RootJsonFormat[Book] {
override def read(value: JsValue) = {
val uuid = fromField[Option[String]](value, "uuid")
val isbn = fromField[String](value, "isbn")
val title = fromField[String](value, "title")
val review = fromField[Option[String]](value, "review")
val publisher = fromField[Option[String]](value, "publisher")
Book(uuid.getOrElse(BSONObjectID.generate().stringify), isbn, title, review, publisher)
}
override def write(obj: Book): JsValue = JsObject(
"uuid" -> JsString(obj.uuid),
"isbn" -> JsString(obj.isbn),
"title" -> JsString(obj.title),
"review" -> JsString(obj.review.getOrElse("")),
"publisher" -> JsString(obj.publisher.getOrElse(""))
)
}
}
示例5: DocumentService
//设置package包名称以及导入依赖的类
package service.documents
import javax.inject.{Inject, Named}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives._
import spray.json.DefaultJsonProtocol
@Named
class DocumentService @Inject()(documentRepository: DocumentRepository) extends DefaultJsonProtocol with SprayJsonSupport {
val docRoutes =
path("documents") {
get {
complete(documentRepository.getDocuments)
}
} ~
path("document"/Segment ) {
r => complete(documentRepository.getDocument(r))
} ~
path("nowatermarks") {
complete(documentRepository.getNoWatermarks)
} ~
path("nowatermark"/"""\w+""".r) {
r => complete(documentRepository.getNoWatermark(r))
}
}
示例6: UsersProtonModule
//设置package包名称以及导入依赖的类
package proton.users
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import akka.stream.ActorMaterializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import scaldi.{Injectable, Module, TypesafeConfigInjector}
import spray.json.{CompactPrinter, JsonPrinter}
import scala.concurrent.ExecutionContext
class UsersProtonModule(config: Config) extends Module {
bind[ExecutionContext] to scala.concurrent.ExecutionContext.Implicits.global
bind[ActorSystem] to ActorSystem("ProtonUsers", config) destroyWith (_.terminate())
bind[JsonPrinter] to CompactPrinter
}
object UsersProtonApp extends App with Injectable with LazyLogging with SprayJsonSupport with UsersProtocol {
ProtonConfig.parse("users-dev.conf", args).foreach(c => {
val config = c.config
implicit val injector = TypesafeConfigInjector(config) :: new UsersProtonModule(config)
implicit val executionContext = inject[ExecutionContext]
implicit val system = inject[ActorSystem]
implicit val materializer = ActorMaterializer()
implicit val printer = inject[JsonPrinter]
implicit val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error("HTTP unhandled exception.", e)
var message = "HTTP unhandled exception."
if (e != null) {
message = e.getMessage
}
complete(InternalServerError -> Message(message, UsersEvents.Unhandled))
}
def route: Route =
pathSingleSlash {
get {
complete("test")
}
}
Http().bindAndHandle(route, config.getString("proton.ip"), config.getInt("proton.users.http.port"))
})
}
示例7: Hello
//设置package包名称以及导入依赖的类
package com.github.cupenya.hello
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, Directives, RejectionHandler }
import akka.http.scaladsl.model.StatusCodes._
import com.github.cupenya.hello.authentication.AuthorizationDirectives
import spray.json._
import scala.concurrent.ExecutionContext
case class Hello(message: String)
case class AuthError(error: String)
trait Protocols extends DefaultJsonProtocol {
implicit val helloFormat = jsonFormat1(Hello)
}
trait HelloHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with Protocols with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val helloRoute = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("hello") {
get {
complete(Hello(s"hello ${authInfo.userId}"))
}
}
}
}
}
示例8: HealthCheckModel
//设置package包名称以及导入依赖的类
package com.github.cupenya.hello
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.model.StatusCodes._
import spray.json.DefaultJsonProtocol
sealed trait HealthCheckModel
object HealthCheckModel extends DefaultJsonProtocol {
implicit val healthCheckResultFormat = jsonFormat2(HealthCheckResult)
}
case class HealthCheckResult(name: String, status: String) extends HealthCheckModel
trait HealthHttpService extends Directives with SprayJsonSupport with Protocols with Logging {
val healthRoute =
pathPrefix("health") {
get {
complete(OK -> Map(
"services" -> List(
HealthCheckResult("service1", "ok")
)
))
}
}
}
示例9: RecordHistoryService
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry
import akka.actor.ActorSystem
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import akka.stream.scaladsl.Sink
import au.csiro.data61.magda.model.Registry._
import io.swagger.annotations._
import javax.ws.rs.Path
import scala.concurrent.Await
import scala.concurrent.duration._
import scalikejdbc.DB
@Path("/records/{recordId}/history")
@io.swagger.annotations.Api(value = "record history", produces = "application/json")
class RecordHistoryService(system: ActorSystem, materializer: Materializer) extends Protocols with SprayJsonSupport {
@ApiOperation(value = "Get a list of all events affecting this record", nickname = "history", httpMethod = "GET", response = classOf[EventsPage])
@ApiImplicitParams(Array(
new ApiImplicitParam(name = "recordId", required = true, dataType = "string", paramType = "path", value = "ID of the record for which to fetch history.")
))
def history = get { path(Segment / "history") { id => { parameters('pageToken.as[Long].?, 'start.as[Int].?, 'limit.as[Int].?) { (pageToken, start, limit) =>
complete {
DB readOnly { session =>
EventPersistence.getEvents(session, recordId = Some(id), pageToken = pageToken, start = start, limit = limit)
}
}
} } } }
@Path("/{eventId}")
@ApiOperation(value = "Get the version of a record that existed after a given event was applied", nickname = "version", httpMethod = "GET", response = classOf[Record])
@ApiImplicitParams(Array(
new ApiImplicitParam(name = "recordId", required = true, dataType = "string", paramType = "path", value = "ID of the record to fetch."),
new ApiImplicitParam(name = "eventId", required = true, dataType = "string", paramType = "path", value = "The ID of the last event to be applied to the record. The event with this ID need not actually apply to the record, in which case that last event prior to this even that does apply will be used.")
))
@ApiResponses(Array(
new ApiResponse(code = 404, message = "No record exists with the given ID, it does not have a CreateRecord event, or it has been deleted.", response = classOf[BadRequest])
))
def version = get { path(Segment / "history" / Segment) { (id, version) => { parameters('aspect.*, 'optionalAspect.*) { (aspects: Iterable[String], optionalAspects: Iterable[String]) =>
DB readOnly { session =>
val events = EventPersistence.streamEventsUpTo(version.toLong, recordId = Some(id))
val recordSource = RecordPersistence.reconstructRecordFromEvents(id, events, aspects, optionalAspects)
val sink = Sink.head[Option[Record]]
val future = recordSource.runWith(sink)(materializer)
Await.result[Option[Record]](future, 5 seconds) match {
case Some(record) => complete(record)
case None => complete(StatusCodes.NotFound, BadRequest("No record exists with that ID, it does not have a CreateRecord event, or it has been deleted."))
}
}
} } } }
val route =
history ~
version
}
示例10: MessageFormat
//设置package包名称以及导入依赖的类
package bot.line.json
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import bot.line.model.send.{Message, Messages, TextMessage}
import spray.json._
trait MessagesJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit object MessageFormat extends RootJsonFormat[Message] {
def write(e: Message): JsValue = e match {
case TextMessage(text) => JsObject(
"type" -> JsString(e.`type`),
"text" -> JsString(text)
)
}
def read(value: JsValue): Message = value match {
case JsArray(Vector(JsString(messageType), JsString(text))) =>
if (messageType == "text") TextMessage(text)
else deserializationError(s"Unsupported Message Type '$messageType' !")
case _ => deserializationError("Message expected")
}
}
implicit val messageFormat: RootJsonFormat[Messages] = jsonFormat2(Messages)
}
示例11: AuthError
//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directives, RejectionHandler}
import com.github.cupenya.microservices.sdk.authentication.AuthorizationDirectives
import com.github.cupenya.microservices.sdk.logging.Logging
import spray.json._
import scala.concurrent.ExecutionContext
case class AuthError(error: String)
trait SampleHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with DefaultJsonProtocol with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val routes = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("test") {
get {
complete(OK, None)
}
}
}
}
}
示例12: Conversions
//设置package包名称以及导入依赖的类
package com.edu.chat.util
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.edu.chat.database.UsersDBActor.{CheckAuth, User}
import com.edu.chat.web.ConnectionHandlerActor.SignUp
import com.edu.chat.web.WebSocketConnectionActor.ChatMessage
import org.mongodb.scala.bson.collection.immutable.Document
import spray.json._
import scala.collection.JavaConverters._
import scala.collection.mutable
object Conversions {
implicit class DocumentConversions(document: Document) {
def asMessage: ChatMessage = ChatMessage(
document("from").asString().getValue,
document("to").asString().getValue,
document("payload").asString().getValue,
document("datetime").asDateTime().getValue)
def asUser: User = User(
document("userId").asString().getValue,
document("password").asString().getValue,
mutable.Set[String](document("rooms").asArray().getValues.asScala.map(_.asString().getValue): _*)
)
}
object JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
implicit val chatMessageFormat: RootJsonFormat[ChatMessage] = jsonFormat4(ChatMessage)
implicit val signUpFormat: RootJsonFormat[SignUp] = jsonFormat2(SignUp)
implicit val authRequestFormat: RootJsonFormat[CheckAuth] = jsonFormat2(CheckAuth)
}
}
示例13: JsonSupport
//设置package包名称以及导入依赖的类
package se.meldrum.machine.http
import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTime, DateTimeZone}
import se.meldrum.machine.db.models.Task
object JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
// To make Joda DateTime available
// cred to suin
implicit object DateTimeJsonFormat extends RootJsonFormat[DateTime] {
private lazy val format = ISODateTimeFormat.dateTimeNoMillis()
def write(datetime: DateTime): JsValue = JsString(format.print(datetime.withZone(DateTimeZone.UTC)))
def read(json: JsValue): DateTime = json match {
case JsString(x) => format.parseDateTime(x)
case x => deserializationError("Expected DateTime as JsString, but got " + x)
}
}
implicit val taskFormat = jsonFormat5(Task)
implicit val userCreationFormat = jsonFormat3(UserCreation)
implicit val userNamesFormat = jsonFormat1(UserNames)
}
示例14: SupplierRoutes
//设置package包名称以及导入依赖的类
package rest
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import entities.JsonProtocol
import persistence.entities.{SimpleSupplier, Supplier}
import utils.{PersistenceModule, Configuration}
import JsonProtocol._
import SprayJsonSupport._
import scala.util.{Failure, Success}
class SupplierRoutes(modules: Configuration with PersistenceModule) {
private val supplierGetRoute = path("supplier" / IntNumber) { (supId) =>
get {
onComplete((modules.suppliersDal.findById(supId)).mapTo[Option[Supplier]]) {
case Success(supplierOpt) => supplierOpt match {
case Some(sup) => complete(sup)
case None => complete(NotFound, s"The supplier doesn't exist")
}
case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
}
}
}
private val supplierPostRoute = path("supplier") {
post {
entity(as[SimpleSupplier]) { supplierToInsert => onComplete((modules.suppliersDal.insert(Supplier(0, supplierToInsert.name, supplierToInsert.desc)))) {
// ignoring the number of insertedEntities because in this case it should always be one, you might check this in other cases
case Success(insertedEntities) => complete(Created)
case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
}
}
}
}
val routes: Route = supplierPostRoute ~ supplierGetRoute
}
示例15: Marshallers
//设置package包名称以及导入依赖的类
package com.jatescher.layer.marshalling
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller
import com.jatescher.layer.marshalling.v1._
import com.jatescher.layer.models.MessagePartContents.ImageMessagePartContent
import com.jatescher.layer.models.MessageParts.{ ImageMessagePart, TextMessagePart }
import com.jatescher.layer.models.MessageSenders.{ HumanMessageSender, NonHumanMessageSender }
import com.jatescher.layer.models._
import spray.json._
object Marshallers extends SprayJsonSupport with DefaultJsonProtocol {
implicit val ConversationMarshaller: ToEntityMarshaller[Conversation] = ConversationFormat.ConversationJsonFormat
implicit val ErrorResponseUnmarshaller: FromEntityUnmarshaller[ErrorResponse] = ErrorResponseFormat.ErrorResponseJsonFormat
implicit val NonHumanMessageSenderMarshaller: ToEntityMarshaller[NonHumanMessageSender] = MessageSenderFormat.NonHumanMessageSenderJsonFormat
implicit val HumanMessageSenderMarshaller: ToEntityMarshaller[HumanMessageSender] = MessageSenderFormat.HumanMessageSenderJsonFormat
implicit val MessageSenderMarshaller: ToEntityMarshaller[MessageSender] = MessageSenderFormat.MessageSenderJsonFormat
implicit val MessagePartContentMarshaller: ToEntityMarshaller[MessagePartContent] = MessagePartContentFormat.MessagePartContentJsonFormat
implicit val ImageMessagePartContentMarshaller: ToEntityMarshaller[ImageMessagePartContent] = MessagePartContentFormat.ImageMessagePartContentJsonFormat
implicit val TextMessagePartMarshaller: ToEntityMarshaller[TextMessagePart] = MessagePartFormat.TextMessagePartJsonFormat
implicit val ImageMessagePartMarshaller: ToEntityMarshaller[ImageMessagePart] = MessagePartFormat.ImageMessagePartJsonFormat
implicit val MessagePartMarshaller: ToEntityMarshaller[MessagePart] = MessagePartFormat.MessagePartJsonFormat
implicit val MessageMarshaller: ToEntityMarshaller[Message] = MessageFormat.MessageJsonFormat
implicit val MessageUnmarshaller: FromEntityUnmarshaller[Message] = MessageFormat.MessageJsonFormat
}