本文整理汇总了Scala中spray.json.JsonParser类的典型用法代码示例。如果您正苦于以下问题:Scala JsonParser类的具体用法?Scala JsonParser怎么用?Scala JsonParser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsonParser类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RandomAuthService
//设置package包名称以及导入依赖的类
package com.rndmi.messaging.auth
import java.util.logging.Logger
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import io.bigfast.messaging.MessagingServer._
import io.bigfast.messaging.auth.AuthService
import io.grpc.Metadata
import spray.json.{JsonParser, ParserInput}
class RandomAuthService extends AuthService {
import RandomAuthService._
override def doAuth(metadata: Metadata) = {
val authorization = metadata.get[String](authorizationKey)
val session = metadata.get[String](sessionKey)
logger.info(s"Checking auth for $authorization, $session")
val httpResponse = http.singleRequest(
HttpRequest(uri = uri).withHeaders(
AuthorizationHeader(authorization),
SessionHeader(session)
)
)(materializer)
httpResponse flatMap { response =>
val responseEntity = response.entity
val eventualRandomResponse = unmarshaller.apply(responseEntity)
logger.info(s"Parsed this response: $eventualRandomResponse")
eventualRandomResponse
} map { resp =>
resp.data.userId.toString
}
}
}
object RandomAuthService extends JsonSupport {
val authorizationKey = Metadata.Key.of("AUTHORIZATION", Metadata.ASCII_STRING_MARSHALLER)
val sessionKey = Metadata.Key.of("X-AUTHENTICATION", Metadata.ASCII_STRING_MARSHALLER)
val http = Http()
val uri = ConfigFactory.load().getString("auth.uri")
implicit val materializer = ActorMaterializer()
val logger = Logger.getLogger(this.getClass.getName)
val unmarshaller: Unmarshaller[HttpEntity, RandomResponse] = {
Unmarshaller.byteArrayUnmarshaller mapWithCharset { (data, charset) =>
JsonParser(ParserInput(data)).asJsObject.convertTo[RandomResponse]
}
}
}
示例2: createToken
//设置package包名称以及导入依赖的类
package shine.st.blog.handler
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.Credentials
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
import shine.st.blog.api.tokenKey
import shine.st.blog.dao.ManagerCollectionDao
import shine.st.blog.protocol.document.Manager
import shine.st.blog.protocol.input.TokenHeader
import spray.json.JsonParser
trait AuthenticationHandler {
def createToken(secretKey: String, id: String): String = {
val jwtClaim = JwtClaim(s"""{"id": "$id"}""").issuedNow.expiresIn(60 * 60 * 6)
Jwt.encode(jwtClaim, tokenKey, JwtAlgorithm.HS256)
}
def authenticator(key: String): Credentials => Option[Manager] =
credentials =>
credentials match {
case [email protected](token) =>
Jwt.validate(token, key, Seq(JwtAlgorithm.HS256))
val res0 = Jwt.decodeRaw(token, key, Seq(JwtAlgorithm.HS256))
val json = JsonParser(res0.toOption.get)
val tokenHeader = json.convertTo[TokenHeader]
ManagerCollectionDao.findById(tokenHeader.id)
case _ => None
}
def authenticate(tokenKey: String) =
authenticateOAuth2("", authenticator(tokenKey))
}
示例3: Connection
//设置package包名称以及导入依赖的类
package pl.com.bms.fileSynchronizer.config
import spray.json.JsonParser
case class Connection(login: String, password: String, url: String)
case class Configuration(
connection: Connection,
sourceRoot: String,
destinationRoot: String,
files: List[String],
directories: List[String]) extends Product{
val hasAlfrescoDestination = destinationRoot.startsWith("workspace://")
def allFilesToLoad = {
val filesFromDirectories = directories.flatMap(directory => DirectoryToLoad(sourceRoot, directory).filesToLoad())
files ::: directories ::: filesFromDirectories
}
}
object Configuration{
def load(configFileName: String = "config.json"): Configuration = {
import pl.com.bms.fileSynchronizer.config.MyJsonProtocol._
val configFile = loadConfigFile(configFileName)
val config = JsonParser(configFile).convertTo[Configuration]
config
}
private def loadConfigFile(configFileName: String): String = {
scala.io.Source.fromFile(configFileName).getLines().mkString
}
}
示例4: AsyncInterface
//设置package包名称以及导入依赖的类
package io.hydrosphere.mist.master.interfaces.async
import io.hydrosphere.mist.jobs.JobDetails.Source
import io.hydrosphere.mist.master.MasterService
import io.hydrosphere.mist.master.interfaces.JsonCodecs
import io.hydrosphere.mist.master.models._
import io.hydrosphere.mist.utils.Logger
import spray.json.{DeserializationException, JsonParser, pimpString}
import JsonCodecs._
class AsyncInterface(
masterService: MasterService,
input: AsyncInput,
source: Source
) extends Logger {
def start(): this.type = {
input.start(process)
this
}
private def process(message: String): Unit = {
try {
val json = message.parseJson
val request = json.convertTo[AsyncJobStartRequest]
masterService.runJob(request.toCommon, source)
} catch {
case e: DeserializationException =>
logger.warn(s"Message $message does not conform with start request")
case e: JsonParser.ParsingException =>
logger.warn(s"Handled invalid message $message")
case e: Throwable =>
logger.error(s"Error occurred during handling message $message", e)
}
}
def close(): Unit = input.close()
}
示例5:
//设置package包名称以及导入依赖的类
package http_handling
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.HostConnectionPool
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}
import akka.util.ByteString
import models.docs.Outter
import spray.json.JsonParser
import scala.util.{Failure, Success, Try}
trait Flows extends Protocols {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
val delimiter: String = """{"response"""
val log = Flow[ByteString].map{ bytes =>
println(bytes.utf8String)
println("-------------------------")
bytes
}
val readdDelimiter = Flow[String].map(str => delimiter + str)
val deserialize = Flow[String].mapConcat{ str =>
Try(JsonParser(str).convertTo[Outter]) match {
case Success(outter) => outter :: Nil
case Failure(ex) =>
println(s"One deserialization failed with: ${ex.getMessage}")
Nil
}
}
val dropBrokenRequests = Flow[(Try[HttpResponse], Int)]
.map(_._1)
.collect{ case Success(httpRes) => httpRes }
val connecFlow: String => Flow[(HttpRequest, Int), (Try[HttpResponse], Int), HostConnectionPool] = host => Http().cachedHostConnectionPool[Int](host)
val checkHttpStatus =
Flow[HttpResponse].flatMapConcat { response =>
response.status match {
case StatusCodes.OK => response.entity.dataBytes
case StatusCodes.Forbidden =>
response.entity.dataBytes.runWith(Sink.ignore)
Source.failed(new IllegalArgumentException("Please check your api key, seems to be invalid"))
case _ =>
response.entity.dataBytes.map(_.utf8String).runForeach(println)
Source.failed(new IllegalArgumentException("Something went wrong, check your query"))
}
}
}
示例6: ApplicationMain
//设置package包名称以及导入依赖的类
package io.ticofab.meetup_akka_streams
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Framing}
import akka.util.ByteString
import spray.json.JsonParser
import scala.concurrent.ExecutionContext.Implicits.global
object ApplicationMain extends App with RSVPJsonFormatSupport {
implicit val system = ActorSystem("MyActorSystem")
implicit val materializer = ActorMaterializer()
val httpRequest = HttpRequest(
method = HttpMethods.GET,
uri = "http://stream.meetup.com/2/rsvps"
)
Http().singleRequest(httpRequest).map { response =>
println(response.status)
response.status match {
case StatusCodes.OK =>
// delimiting frame to make sure we take items when separated by a line-break
val frame = Flow[ByteString]
.via(Framing.delimiter(
delimiter = ByteString("\n"),
maximumFrameLength = 3000,
allowTruncation = false))
// get the response entity as a source and manipulate it
response.entity.dataBytes
.via(frame)
.map(_.utf8String)
.map(JsonParser(_).convertTo[RSVP])
.runForeach(println)
case _ =>
println("Unexpected error, shutting down")
system.terminate();
}
}
}