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


Scala write类代码示例

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


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

示例1: EventSerialiser

//设置package包名称以及导入依赖的类
package serialisation

import java.util

import model.Event
import org.apache.kafka.common.serialization.{Serializer, StringSerializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write
import org.json4s.{Formats, NoTypeHints}

class EventSerialiser extends Serializer[Event] {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  val stringSerialiser = new StringSerializer

  override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
    stringSerialiser.configure(configs, isKey)
  }

  override def serialize(topic: String, data: Event): Array[Byte] = {
    val stringValue = write(data)
    stringSerialiser.serialize(topic, stringValue)
  }

  override def close(): Unit = {
    stringSerialiser.close()
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventSerialiser.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: ItemData

//设置package包名称以及导入依赖的类
package com.project.production

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}

import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.FSM
import akka.actor.FSM._
import akka.actor.Props
import scala.collection.immutable.Queue

case class ItemData(val erpData: ERPData, val specData: SpecData, val prodData: Queue[_])

class Item extends Actor {
    val fsm: ActorRef = context.actorOf(Props[ItemFSM])
    var erpData: Option[ERPData] = None
    var specData: Option[SpecData] = None
    var prodData: Option[Queue[_]] = None

    implicit val formats = Serialization.formats(NoTypeHints)

    def receive = {
        case (x: ProdEvent, y: ProdData) => fsm ! (x, y)
        case x: ERPData => erpData = Some(x)
        case x: SpecData => {
            specData = Some(x)
            trySubmit()
        }
        case x: Queue[_] => prodData = Some(x)
    }

    def itemData: ItemData = {
        val item = for {
            e <- erpData
            s <- specData
            p <- prodData
        } yield ItemData(e, s, p)
        item.get
    }

    def serialize(item: ItemData): String = {
        write(item)
    }

    def trySubmit() {
        erpData.isDefined && specData.isDefined && prodData.isDefined match {
            case true => context.parent ! serialize(itemData)
            case _ => ()
        }
    }
} 
开发者ID:jlagarden,项目名称:dhbw-project-app,代码行数:54,代码来源:Item.scala

示例5: IsWaitFiller

//设置package包名称以及导入依赖的类
package isWaitInstruction

import akka.actor._
import core.Domain._
import core.Helpers._
import core.ServiceBase
import org.json4s._
import org.json4s.native.Serialization.write



class IsWaitFiller extends ServiceBase {
  // Type aliases
  type Instruction = String

  // Functions
  def handleAmqMessage(json: JValue) = {
    if (json.has("programPointerPosition") && json.has("instruction") && !json.has("isWaiting")) {
      val event: PointerWithInstruction = json.extract[PointerWithInstruction]
      fill(event)
    } else {
      // do nothing... OR log.info("Received message of unmanageable type property.")
    }
  }

  def fill(event: PointerWithInstruction) = {
    val instruction: Instruction = event.instruction
    var isWaiting: Boolean = false
    if (instruction.startsWith("Wait") || instruction.startsWith("ExecEngine"))
      isWaiting = true
    val filledEvent = PointerWithIsWaiting(event.robotId, event.workCellId,event.address, instruction, isWaiting,
      event.programPointerPosition)
    val json: String = write(filledEvent)
    log.info("From isWaiting: " + json)
    sendToBus(json)
  }
}

object IsWaitFiller {
  def props = Props[IsWaitFiller]
} 
开发者ID:HenWahl,项目名称:robot-services,代码行数:42,代码来源:IsWaitFiller.scala

示例6: WaitChange

//设置package包名称以及导入依赖的类
package waitChange

import akka.actor._
import core.Domain._
import core.Helpers._
import core.ServiceBase
import java.util.UUID
import org.json4s._
import org.json4s.native.Serialization.write



class WaitChange extends ServiceBase {
  // Type aliases
  type RobotId = String
  type ActivityId = UUID
  type WaitInstruction = String

  // State
  var isWaiting: Map[RobotId, Option[(ActivityId, WaitInstruction)]] = Map.empty

  // Functions
  def handleAmqMessage(json: JValue) = {
    if (json.has("isWaiting"))
      checkIfWaitChange(json)
  }

  def checkIfWaitChange(json: JValue) = {
    val event: PointerWithIsWaiting = json.extract[PointerWithIsWaiting]

    if (!isWaiting.contains(event.robotId)) {
      isWaiting += (event.robotId -> None)
    }

    if (isWaiting(event.robotId).isDefined != event.isWaiting) {
      val (activityId, waitInstruction): (ActivityId, WaitInstruction) = if (event.isWaiting) {
        val id = UUID.randomUUID()
        isWaiting += (event.robotId -> Some((id, event.instruction)))
        (id, event.instruction)
      } else {
        val (id, instruction) = isWaiting(event.robotId).get
        isWaiting += (event.robotId -> None)
        (id, instruction)
      }
      val activityEvent = ActivityEvent(activityId.toString, event.isWaiting, waitInstruction, event.robotId,
        event.programPointerPosition.time, "wait", event.workCellId)
      log.info("From waitChange: " + activityEvent)
      sendToBus(write(activityEvent))
    }

  }
}

object WaitChange {
  def props = Props[WaitChange]
} 
开发者ID:HenWahl,项目名称:robot-services,代码行数:57,代码来源:WaitChange.scala

示例7: Main

//设置package包名称以及导入依赖的类
package com.ponkotuy

import java.nio.charset.{Charset, StandardCharsets}
import java.nio.file.{Files, Path, Paths}

import com.ponkotuy.queries.{Exif, LoginEmail}
import org.json4s.DefaultFormats
import org.json4s.ext.JodaTimeSerializers
import org.json4s.native.Serialization.write
import skinny.http.{HTTP, Request}
import com.ponkotuy.utils.EitherUtil.eitherToRightProjection

import scala.compat.java8.StreamConverters._

object Main {
  implicit val formats = DefaultFormats ++ JodaTimeSerializers.all

  val config = new Config

  def main(args: Array[String]): Unit = {
    val extractor = new com.ponkotuy.Extractor
    login().fold(println("Auth failed")){ session =>
      args.foreach{ raw =>
        val exifs = files(raw).filter(_.toString.toLowerCase.endsWith(".jpg")).flatMap{ file =>
          val map = extractor.read(file).tagMaps
          Exif.fromMap(file.getFileName.toString, map).left.map { e =>
            println(s"${file.toString} parse error: ${e} not found.")
          }.toOption
        }
        exifs.foreach{ exif =>
          println(exif.fileName)
          val req = Request(s"${config.server}/api/exif")
              .header("Cookie", session.toString)
              .body(write(exif).getBytes(Charset.forName("UTF-8")), "application/json")
          val res = HTTP.post(req)
          if(res.status / 100 != 2) println(new String(res.body))
        }
      }
    }
  }

  private def login(): Option[Cookie] = {
    val auth = LoginEmail(config.email, config.password)
    val json = write(auth).getBytes(StandardCharsets.UTF_8)
    val req = Request(s"${config.server}/api/session").body(json, "application/json")
    val res = HTTP.post(req)
    res.header("Set-Cookie").map(Cookie.fromStr)
  }

  private def files(raw: String): List[Path] = {
    val path = Paths.get(raw)
    if(Files.isDirectory(path)) Files.list(path).toScala[List]
    else path :: Nil
  }
} 
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:56,代码来源:Main.scala

示例8: RabbitQueue

//设置package包名称以及导入依赖的类
package com.fustigatedcat.heystk.engine.queue

import com.fustigatedcat.heystk.engine.EngineAPI
import com.fustigatedcat.heystk.common.normalization.Normalization
import com.rabbitmq.client.{MessageProperties, BuiltinExchangeType, ConnectionFactory}
import org.json4s.native.Serialization.write
import org.slf4j.LoggerFactory

object RabbitQueue {

  implicit val formats = org.json4s.DefaultFormats

  val logger = LoggerFactory.getLogger(this.getClass)

  val config = EngineAPI.config.getConfig("engine.queue.amqp")

  val apiExchangeName = config.getString("api.exchange-name")

  val toProcessRoutingKey = config.getString("api.routing-key")

  val factory = {
    val f = new ConnectionFactory()
    f.setHost(config.getString("host"))
    f.setPort(config.getInt("port"))
    f.setVirtualHost(config.getString("vhost"))
    f.setUsername(config.getString("user"))
    f.setPassword(config.getString("password"))
    f
  }

  val connection = factory.newConnection()

  val channel = connection.createChannel()

  def postToProcess(normalization : Normalization) = {
    val norm = write(normalization)
    logger.debug("Publishing normalization {}", norm)
    channel.basicPublish(
      apiExchangeName,
      toProcessRoutingKey,
      MessageProperties.PERSISTENT_TEXT_PLAIN,
      norm.getBytes
    )
  }

} 
开发者ID:fustigatedcat,项目名称:heystk,代码行数:47,代码来源:RabbitQueue.scala

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

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

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

示例12: RequestJson

//设置package包名称以及导入依赖的类
package renesca.json.protocols

import org.json4s.native.Serialization
import renesca.Query
import renesca.json.{Request, Statement}
import org.json4s._
import org.json4s.JsonDSL._
import native.JsonMethods._
import org.json4s.native.Serialization._
import org.json4s.native.Serialization.{read, write}
import renesca.parameter._


object RequestJson {

  implicit val formats = Serialization.formats(NoTypeHints) + new PropertyKeySerializer() + new ParameterMapSerializer()

  def jsonOf(obj: Request): String = {
    write(obj)
  }

  def jsonOf(obj: Statement): String = {
    write(obj)
  }

  def jsonOfStatement(query: Query, resultDataContents: List[String]): String = {
    val a = Statement.apply(query, resultDataContents)
    jsonOf(a)
  }

} 
开发者ID:PhilAndrew,项目名称:renesca_hacking,代码行数:32,代码来源:RequestJson.scala

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

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

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


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