All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ml.bundle.support.JsonStreamSerializer.scala Maven / Gradle / Ivy

The newest version!
package ml.bundle.support

import java.io._

import ml.bundle.StreamSerializer
import spray.json._

import scala.util.Try

/**
  * Created by hollinwilkins on 3/4/18.
  */
object JsonStreamSerializer {
  implicit class ConversionOps[Obj](_format: RootJsonFormat[Obj]) {
    def toStreamSerializer(_key: String): JsonStreamSerializer[Obj] = {
      new JsonStreamSerializer[Obj] {
        override implicit val format: RootJsonFormat[Obj] = _format
        override val key: String = _key
      }
    }
  }
}

trait JsonStreamSerializer[Obj] extends StreamSerializer[Obj] {
  implicit val format: RootJsonFormat[Obj]

  override def serializeItem(obj: Obj, out: OutputStream): Unit = {
    val json = format.write(obj).compactPrint.getBytes
    val dataOut = new DataOutputStream(out)
    dataOut.writeInt(json.length)
    dataOut.write(json)
    dataOut.writeChar('\n')
  }

  override def serialize(obj: Obj, out: OutputStream): Unit = {
    val json = format.write(obj).prettyPrint.getBytes
    out.write(json)
  }

  override def deserializeItem(in: InputStream): Obj = {
    val dataIn = new DataInputStream(in)
    val size = dataIn.readInt()
    val bytes = new Array[Byte](size)
    dataIn.readFully(bytes)
    dataIn.readChar()

    new String(bytes).parseJson.convertTo[Obj]
  }

  override def deserialize(in: InputStream): Obj = {
    val reader = new BufferedReader(new InputStreamReader(in))
    val sb = new StringBuilder()

    var hasLine = true
    while(hasLine) {
      val line = reader.readLine()

      if(line != null) {
        sb.append(line)
      } else {
        hasLine = false
      }
    }

    sb.toString.parseJson.convertTo[Obj]
  }

  override def validate(in: InputStream): Try[Unit] = Try(deserialize(in))

  override def validateItem(in: InputStream): Try[Unit] = Try(deserializeItem(in))
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy