本文整理汇总了Scala中org.json4s.native.Serialization.read类的典型用法代码示例。如果您正苦于以下问题:Scala read类的具体用法?Scala read怎么用?Scala read使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了read类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: EventDeserialiser
//设置package包名称以及导入依赖的类
package serialisation
import java.util
import model.Event
import org.apache.kafka.common.serialization.{Deserializer, StringDeserializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
import org.json4s.{Formats, NoTypeHints}
class EventDeserialiser extends Deserializer[Event] {
implicit val formats: Formats = Serialization.formats(NoTypeHints)
val stringDeserialiser = new StringDeserializer
override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
stringDeserialiser.configure(configs, isKey)
}
override def deserialize(topic: String, data: Array[Byte]): Event = {
val stringValue = stringDeserialiser.deserialize(topic, data)
read[Event](stringValue)
}
override def close(): Unit = {
stringDeserialiser.close()
}
}
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventDeserialiser.scala
示例2: StringEventCollector
//设置package包名称以及导入依赖的类
package transformation
import model.Event
import org.apache.kafka.streams.KeyValue
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.json4s.{Formats, NoTypeHints}
class StringEventCollector(storeName: String)
extends CollectTransformer[String, String, String, String, String](storeName) {
implicit val formats: Formats = Serialization.formats(NoTypeHints)
override def appendToStore(storeValue: String, appendValue: String): String = {
appendValue
}
override def collectComplete(storeValue: String, appendValue: String): Boolean = {
// just merges two events
storeValue.nonEmpty && appendValue.nonEmpty
}
override def collectOutput(inputKey: String, storeValue: String, mergeValue: String): KeyValue[String, String] = {
new KeyValue(inputKey, collect(storeValue, mergeValue))
}
def collect(storeValue: String, mergeValue: String): String = {
log.info(s"Collecting ...")
log.info(s" with store : $storeValue")
log.info(s" with event : $mergeValue")
val firstEvent = read[Event](storeValue)
val secondEvent = read[Event](mergeValue)
write(Event(firstEvent.eventType + secondEvent.eventType,
firstEvent.count + secondEvent.count,
firstEvent.name + secondEvent.name))
}
}
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:38,代码来源:StringEventCollector.scala
示例3: SerializationTest
//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization
import java.io.{FileReader, FileWriter}
import org.argus.amandroid.alir.componentSummary.ApkYard
import org.argus.amandroid.core.decompile.{ConverterUtil, DecompileLayout, DecompileStrategy, DecompilerSettings}
import org.argus.amandroid.core.model.ApkModel
import org.argus.jawa.core.DefaultReporter
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util.FileUtil
class SerializationTest extends FlatSpec with Matchers {
"ApkModel" should "successfully serialized and deserialized" in {
val apkFile = getClass.getResource("/icc-bench/IccHandling/icc_explicit_src_sink.apk").getPath
val apkUri = FileUtil.toUri(apkFile)
val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
val reporter = new DefaultReporter
val yard = new ApkYard(reporter)
val layout = DecompileLayout(outputUri)
val strategy = DecompileStrategy(layout)
val settings = DecompilerSettings(debugMode = false, forceDelete = true, strategy, reporter)
val apk = yard.loadApk(apkUri, settings, collectInfo = true)
val model = apk.model
implicit val formats = Serialization.formats(NoTypeHints) + ApkModelSerializer
val apkRes = FileUtil.toFile(FileUtil.appendFileName(outputUri, "apk.json"))
val oapk = new FileWriter(apkRes)
try {
write(model, oapk)
} catch {
case e: Exception =>
e.printStackTrace()
} finally {
oapk.flush()
oapk.close()
}
val iapk = new FileReader(apkRes)
var newApkModel: ApkModel = null
try {
newApkModel = read[ApkModel](iapk)
} catch {
case e: Exception =>
e.printStackTrace()
} finally {
iapk.close()
ConverterUtil.cleanDir(outputUri)
}
require(
model.getAppName == newApkModel.getAppName &&
model.getComponents == newApkModel.getComponents &&
model.getLayoutControls == newApkModel.getLayoutControls &&
model.getCallbackMethods == newApkModel.getCallbackMethods &&
model.getComponentInfos == newApkModel.getComponentInfos &&
model.getEnvMap == newApkModel.getEnvMap)
}
}
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:61,代码来源:SerializationTest.scala
示例4: Validator
//设置package包名称以及导入依赖的类
package com.avaglir.tauroneo.validation
import java.io.File
import com.avaglir.tauroneo.knn._
import com.avaglir.tauroneo.utils._
import com.github.tototoshi.csv._
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
import scala.io.Source
import scala.util.Random
object Validator {
implicit val formats = Serialization.formats(NoTypeHints)
val rand = new Random
val allData: Seq[FrameData] = {
val d = new File("replay_data")
d.listFiles.filter { f => f.isFile && f.getName != "all.json" } flatMap { f =>
println(s"loading ${f.getName}")
read[List[FrameData]]((Source fromFile f).reader)
}
}
println(s"total of ${allData.size} features loaded")
val seed = System.currentTimeMillis()
val random = new Random(seed)
val (trainingData, testingData) = allData partition { _ => rand.nextInt(10) <= 7 }
def square(i: Int): Int = i * i
def main(args: Array[String]): Unit = {
implicit val milC: KnnFrameCompanion[MilFrame] = MilFrame
implicit val econC: KnnFrameCompanion[EconFrame] = EconFrame
val mil = execute(MilFrame).flatten
val econ = execute(EconFrame).flatten
writeOut[MilFrame](mil)
writeOut[EconFrame](econ)
}
def execute[T <: KnnFrame](frameCompanion: KnnFrameCompanion[T]) = Stream.range(2, 11) map { k =>
val reg = Reg(trainingData, frameCompanion, k)
testingData.map(frameCompanion.apply).filter { elem => elem.magnitude > 500 }.map { elem => {
(k, elem.score, reg.estimate(elem))
} }.sorted
}
def writeOut[T <: KnnFrame: KnnFrameCompanion](vals: Seq[(Int, Int, Int)]) = {
val writer = CSVWriter open s"validation/${implicitly[KnnFrameCompanion[T]].frameTypeName}.csv"
writer.writeRow(List("k", "actual", "estimate"))
vals foreach { elem => writer.writeRow(elem.productIterator.toSeq) }
writer.close()
}
}
开发者ID:mammothbane,项目名称:tauroneo,代码行数:62,代码来源:Validator.scala
示例5: Persistence
//设置package包名称以及导入依赖的类
package com.mariotti.urlshortener.dao.persistence
import com.mariotti.urlshortener.model.Stats
import java.nio.file.{ Paths, Files }
import scala.io.Source
import java.nio.charset.StandardCharsets
import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{ read, write }
object Persistence extends PersistenceWrapper {
val MAPPING_PREFIX = "MAPPING_"
val STATS_PREFIX = "STATS_"
private def getStatsFileName(id: Int): String = {
STATS_PREFIX + String.valueOf(id)
}
def get(id: Int): String = {
val filename = getMappingFileName(id);
if (Files.exists(Paths.get(filename))) {
Source.fromFile(filename).getLines.mkString
} else
null;
}
def put(id: Int, value: String) {
val filename = getMappingFileName(id);
if (!Files.exists(Paths.get(filename))) {
Files.write(Paths.get(filename), value.getBytes(StandardCharsets.UTF_8))
} else
throw new Exception("key collision detected when writing file")
}
def getStats(id: Int): Stats = {
val filename = getStatsFileName(id);
implicit val formats = Serialization.formats(NoTypeHints)
val ser = Source.fromFile(filename).getLines.mkString
read[Stats](ser)
}
def putStats(id: Int, stats: Stats) {
if (stats != null) {
val filename = getStatsFileName(id);
implicit val formats = Serialization.formats(NoTypeHints)
val ser = write(stats)
Files.write(Paths.get(filename), ser.getBytes(StandardCharsets.UTF_8))
}
}
}
开发者ID:LupoDiRoma,项目名称:miscellanea,代码行数:50,代码来源:Persistence.scala
示例6: URISerializer
//设置package包名称以及导入依赖的类
package com.protegra_ati.agentservices.protocols
import java.net.URI
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
class URISerializer extends Serializer[URI] {
private val URIClass = classOf[URI]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), URI] = {
case (TypeInfo(URIClass, _), json) => json match {
case JString(s) => new URI(s)
case x => throw new MappingException("Can't convert " + x + " to java.net.URI")
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case x: URI => JString(x.toString)
}
}
object Serializer {
implicit val formats = Serialization.formats(NoTypeHints) + new URISerializer
def serialize(o: AnyRef): String = {
write(o)
}
def deserialize[T: Manifest](s: String): T = {
read[T](s)
}
}
开发者ID:synereo,项目名称:synereo,代码行数:34,代码来源:Serializer.scala
示例7: URISerializer
//设置package包名称以及导入依赖的类
package com.biosimilarity.evaluator.spray
import java.net.URI
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
class URISerializer extends Serializer[URI] {
private val URIClass = classOf[URI]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), URI] = {
case (TypeInfo(URIClass, _), json) => json match {
case JString(s) => new URI(s)
case x => throw new MappingException("Can't convert " + x + " to java.net.URI")
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case x: URI => JString(x.toString)
}
}
object Serializer {
implicit val formats = Serialization.formats(NoTypeHints) + new URISerializer
def serialize(o: AnyRef): String = {
write(o)
}
def deserialize[T: Manifest](s: String): T = {
read[T](s)
}
}
开发者ID:synereo,项目名称:synereo,代码行数:34,代码来源:Serializer.scala
示例8: PretentCreditCardService
//设置package包名称以及导入依赖的类
package com.packt.masteringakka.bookstore.server
import io.netty.channel.ChannelHandler.Sharable
import unfiltered.netty.ServerErrorResponse
import unfiltered.request._
import java.util.Date
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import unfiltered.response._
@Sharable
object PretentCreditCardService extends unfiltered.netty.async.Plan with ServerErrorResponse{
case class ChargeRequest(cardHolder:String, cardType:String, cardNumber:String, expiration:Date, amount:Double)
case class ChargeResponse(confirmationCode:String)
implicit val formats = Serialization.formats(NoTypeHints)
def intent = {
case req @ POST(Path(Seg("credit" :: "charge" :: Nil))) =>
val body = Body.string(req)
val request = read[ChargeRequest](body)
val resp = write(ChargeResponse(java.util.UUID.randomUUID().toString))
req.respond(JsonContent ~> ResponseString(resp))
}
}
开发者ID:PacktPublishing,项目名称:Mastering-Akka,代码行数:27,代码来源:PretentCreditCardService.scala
示例9: PretentCreditCardService
//设置package包名称以及导入依赖的类
package com.packt.masteringakka.bookstore.common
import io.netty.channel.ChannelHandler.Sharable
import unfiltered.netty.ServerErrorResponse
import unfiltered.request._
import java.util.Date
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import unfiltered.response._
@Sharable
object PretentCreditCardService extends unfiltered.netty.async.Plan with ServerErrorResponse{
case class ChargeRequest(cardHolder:String, cardType:String, cardNumber:String, expiration:Date, amount:Double)
case class ChargeResponse(confirmationCode:String)
implicit val formats = Serialization.formats(NoTypeHints)
def intent = {
case req @ POST(Path(Seg("credit" :: "charge" :: Nil))) =>
val body = Body.string(req)
val request = read[ChargeRequest](body)
val resp = write(ChargeResponse(java.util.UUID.randomUUID().toString))
req.respond(JsonContent ~> ResponseString(resp))
}
}
开发者ID:PacktPublishing,项目名称:Mastering-Akka,代码行数:27,代码来源:PretentCreditCardService.scala
示例10: JsonSerializer
//设置package包名称以及导入依赖的类
package com.packt.masteringakka.bookstore.common
import akka.serialization.SerializerWithStringManifest
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.json4s.ext.EnumNameSerializer
class JsonSerializer extends SerializerWithStringManifest{
implicit val formats = Serialization.formats(NoTypeHints)
def toBinary(o:AnyRef):Array[Byte] = {
val json = write(o)
json.getBytes()
}
def fromBinary(bytes:Array[Byte], manifest:String):AnyRef = {
val m = Manifest.classType[AnyRef](Class.forName(manifest))
val json = new String(bytes, "utf8")
read[AnyRef](json)(formats, m)
}
def identifier:Int = 999
def manifest(o:AnyRef):String = o.getClass.getName
}
开发者ID:PacktPublishing,项目名称:Mastering-Akka,代码行数:28,代码来源:JsonSerializer.scala
示例11: HttpService
//设置package包名称以及导入依赖的类
package com.example.services
import com.example.ApiSettings
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
class HttpService extends HttpServiceTrait {
implicit val formats = Serialization.formats(NoTypeHints)
def get[T](url: String)(implicit m: Manifest[T]): T = {
val jsonString = scala.io.Source.fromURL(buildUrl(url)).mkString
read[T](jsonString)
}
}
object HttpService {
def apply() = new HttpService()
}
trait HttpServiceTrait {
val API_SECRET = ApiSettings.secret
val API_URL = "https://maps.googleapis.com"
def buildUrl(url: String): String = {
s"$API_URL$url&key=$API_SECRET"
}
}
开发者ID:divanvisagie,项目名称:lazy-places,代码行数:32,代码来源:HttpService.scala
示例12: json4sSerializer
//设置package包名称以及导入依赖的类
package com.ovoenergy.kafka.serialization.json4s
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStreamReader, OutputStreamWriter}
import java.nio.charset.StandardCharsets
import com.ovoenergy.kafka.serialization.core._
import org.apache.kafka.common.serialization.{Deserializer => KafkaDeserializer, Serializer => KafkaSerializer}
import org.json4s.Formats
import org.json4s.native.Serialization.{read, write}
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._
trait Json4sSerialization {
def json4sSerializer[T <: AnyRef](implicit jsonFormats: Formats): KafkaSerializer[T] = serializer { (_, data) =>
val bout = new ByteArrayOutputStream()
val writer = new OutputStreamWriter(bout, StandardCharsets.UTF_8)
// TODO Use scala-arm
try {
write(data, writer)
writer.flush()
} finally {
writer.close()
}
bout.toByteArray
}
def json4sDeserializer[T: TypeTag](implicit jsonFormats: Formats): KafkaDeserializer[T] = deserializer { (_, data) =>
val tt = implicitly[TypeTag[T]]
implicit val cl = ClassTag[T](tt.mirror.runtimeClass(tt.tpe))
read[T](new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8))
}
}
开发者ID:ovotech,项目名称:kafka-serialization,代码行数:37,代码来源:Json4sSerialization.scala
示例13: CaptureFeatures
//设置package包名称以及导入依赖的类
package capture
import db.DAO
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import scala.annotation.tailrec
import scalaj.http.Http
//batchDuration - capture length in ms
//timestamp in ms
//id is needed for database compatibility
case class CaptureFeatures(id: Option[Long], nodeId: String,
timestamp: Long,
tcpAddresses: Int, tcpPorts: Int, tcpSpeed: Double, tcpFrameCount: Double,
udpAddresses: Int, udpPorts: Int, udpSpeed: Double, udpFrameCount: Double,
icmpAddresses: Int, icmpSpeed: Double, icmpFrameCount: Double,
procLoad: Double, ramUsage: Double)
class DataHandling(c: CaptureLoop, serverUrl: String) {
@tailrec final def handlingLoop(): Unit = {
Thread.sleep(c.batchDuration * 1000)
val cf = c.getAccumulatedParamsAndReset()
implicit val formats = Serialization.formats(NoTypeHints)
val json = write(cf)
println(json)
val respCode = try {Http(serverUrl + "/nodeData").
postData(json).header("content-type", "application/json").asString.code}
catch {
case e: Exception => println(e)
11111
}
println(respCode)
handlingLoop()
}
}
开发者ID:AurimasAnskaitis,项目名称:ids,代码行数:40,代码来源:DataHandling.scala
注:本文中的org.json4s.native.Serialization.read类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论