org.json4s.CustomSerializer Scala Examples

The following examples show how to use org.json4s.CustomSerializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: DateTimeNoMillisSerializer.scala    From avoin-voitto   with MIT License 6 votes vote down vote up
package liigavoitto.util

import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.ISODateTimeFormat
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{ JNull, JString }

case object DateTimeNoMillisSerializer extends CustomSerializer[DateTime](format => (
  {
    case JString(s) => ISODateTimeFormat.dateTimeNoMillis().withZone(Time.zone).parseDateTime(s)
    case JNull => null
  },
  {
    case d: DateTime => JString(ISODateTimeFormat.dateTimeNoMillis().withZone(Time.zone).print(d))
  }
))

object Time {
  val zone = DateTimeZone.forID("Europe/Helsinki")
} 
Example 2
Source File: CustomerSerializers.scala    From quiz-management-service   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.quiz.management.serializers

import java.sql.Timestamp

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JInt, JNull}

object CustomSerializers {
  val all = List(CustomTimestampSerializer)
}

case object CustomTimestampSerializer extends CustomSerializer[Timestamp](format =>
  ({
    case JInt(x) => new Timestamp(x.longValue * 1000)
    case JNull => null
  },
    {
      case date: Timestamp => JInt(date.getTime / 1000)
    })) 
Example 3
Source File: CustomerSerializers.scala    From quiz-management-service   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.quiz.management.serializers

import java.sql.Timestamp

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JInt, JNull}

object CustomSerializers {
  val all = List(CustomTimestampSerializer)
}

case object CustomTimestampSerializer extends CustomSerializer[Timestamp](format =>
  ({
    case JInt(x) => new Timestamp(x.longValue * 1000)
    case JNull => null
  },
    {
      case date: Timestamp => JInt(date.getTime / 1000)
    })) 
Example 4
Source File: CustomerSerializers.scala    From quiz-management-service   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.quiz.management.serializers

import java.sql.Timestamp

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JInt, JNull}

object CustomSerializers {
  val all = List(CustomTimestampSerializer)
}

case object CustomTimestampSerializer extends CustomSerializer[Timestamp](format =>
  ({
    case JInt(x) => new Timestamp(x.longValue * 1000)
    case JNull => null
  },
    {
      case date: Timestamp => JInt(date.getTime / 1000)
    })) 
Example 5
Source File: ApkModelSerializer.scala    From Argus-SAF   with Apache License 2.0 5 votes vote down vote up
package org.argus.amandroid.serialization

import org.argus.jawa.core.util._
import org.argus.amandroid.core.model.ApkModel
import org.argus.amandroid.core.appInfo.ApkCertificate
import org.argus.amandroid.core.decompile.DecompileLayout
import org.argus.amandroid.core.parser.{ComponentInfo, ComponentType, IntentFilterDataBase, LayoutControl}
import org.argus.jawa.core.elements.{JawaType, Signature}
import org.json4s.{CustomSerializer, Extraction, Formats, JValue}
import org.json4s.JsonDSL._

object ApkModelSerializer extends CustomSerializer[ApkModel](format => (
  {
    case jv: JValue =>
      implicit val formats: Formats = format + JawaTypeSerializer + JawaTypeKeySerializer + SignatureSerializer + SignatureKeySerializer + IntentFilterDataBaseSerializer + DecompileLayoutSerializer + new org.json4s.ext.EnumNameSerializer(ComponentType)
      val nameUri  = (jv \ "nameUri").extract[FileResourceUri]
      val layout = (jv \ "layout").extract[DecompileLayout]
      val certificates = (jv \ "certificates").extract[ISet[ApkCertificate]]
      val activities = (jv \ "activities").extract[ISet[JawaType]]
      val services = (jv \ "services").extract[ISet[JawaType]]
      val receivers = (jv \ "receivers").extract[ISet[JawaType]]
      val providers = (jv \ "provider").extract[ISet[JawaType]]
      val drReceivers = (jv \ "drReceivers").extract[ISet[JawaType]]
      val rpcMethods = (jv \ "rpcMethods").extract[IMap[JawaType, IMap[Signature, Boolean]]]
      val uses_permissions = (jv \ "uses_permissions").extract[ISet[String]]
      val callbackMethods = (jv \ "callbackMethods").extract[IMap[JawaType, ISet[Signature]]]
      val componentInfos = (jv \ "componentInfos").extract[ISet[ComponentInfo]]
      val layoutControls = (jv \ "layoutControls").extract[IMap[Int, LayoutControl]]
      val appPackageName = (jv \ "appPackageName").extract[Option[String]]
      val intentFdb = (jv \ "intentFdb").extract[IntentFilterDataBase]
      val codeLineCounter = (jv \ "codeLineCounter").extract[Int]
      val envMap = (jv \ "envMap").extract[IMap[JawaType, (Signature, String)]]
      val apk = ApkModel(nameUri, layout)
      apk.addCertificates(certificates)
      apk.addActivities(activities)
      apk.addServices(services)
      apk.addReceivers(receivers)
      apk.addProviders(providers)
      apk.addDynamicRegisteredReceivers(drReceivers)
      apk.addRpcMethods(rpcMethods)
      apk.addUsesPermissions(uses_permissions)
      apk.addCallbackMethods(callbackMethods)
      apk.addComponentInfos(componentInfos)
      apk.addLayoutControls(layoutControls)
      apk.setPackageName(appPackageName.getOrElse(""))
      apk.setIntentFilterDB(intentFdb)
      apk.setCodeLineCounter(codeLineCounter)
      apk.addEnvMap(envMap)
      apk
  },
  {
    case model: ApkModel =>
      implicit val formats: Formats = format + JawaTypeSerializer + JawaTypeKeySerializer + SignatureSerializer + SignatureKeySerializer + IntentFilterDataBaseSerializer + DecompileLayoutSerializer + new org.json4s.ext.EnumNameSerializer(ComponentType)
      val nameUri: FileResourceUri = model.nameUri
      val layout: DecompileLayout = model.layout
      val certificates: ISet[ApkCertificate] = model.getCertificates
      val activities: ISet[JawaType] = model.getActivities
      val services: ISet[JawaType] = model.getServices
      val receivers: ISet[JawaType] = model.getReceivers
      val providers: ISet[JawaType] = model.getProviders
      val drReceivers: ISet[JawaType] = model.getDynamicRegisteredReceivers
      val rpcMethods: IMap[JawaType, IMap[Signature, Boolean]] = model.getRpcMethodMapping
      val uses_permissions: ISet[String] = model.getUsesPermissions
      val callbackMethods: IMap[JawaType, ISet[Signature]] = model.getCallbackMethodMapping
      val componentInfos: ISet[ComponentInfo] = model.getComponentInfos
      val layoutControls: IMap[Int, LayoutControl] = model.getLayoutControls
      val appPackageName: String = model.getPackageName
      val intentFdb: IntentFilterDataBase = model.getIntentFilterDB
      val codeLineCounter: Int = model.getCodeLineCounter
      val envMap: IMap[JawaType, (Signature, String)] = model.getEnvMap
      ("nameUri" -> nameUri) ~
      ("layout" -> Extraction.decompose(layout)) ~
      ("certificates" -> Extraction.decompose(certificates)) ~
      ("activities" -> Extraction.decompose(activities)) ~
      ("services" -> Extraction.decompose(services)) ~
      ("receivers" -> Extraction.decompose(receivers)) ~
      ("providers" -> Extraction.decompose(providers)) ~
      ("drReceivers" -> Extraction.decompose(drReceivers)) ~
      ("rpcMethods" -> Extraction.decompose(rpcMethods)) ~
      ("uses_permissions" -> Extraction.decompose(uses_permissions)) ~
      ("callbackMethods" -> Extraction.decompose(callbackMethods)) ~
      ("componentInfos" -> Extraction.decompose(componentInfos)) ~
      ("layoutControls" -> Extraction.decompose(layoutControls)) ~
      ("appPackageName" -> Option(appPackageName)) ~
      ("intentFdb" -> Extraction.decompose(intentFdb)) ~
      ("codeLineCounter" -> codeLineCounter) ~
      ("envMap" -> Extraction.decompose(envMap))
  }
)) 
Example 6
Source File: DecompileLayoutSerializer.scala    From Argus-SAF   with Apache License 2.0 5 votes vote down vote up
package org.argus.amandroid.serialization

import org.argus.amandroid.core.decompile.DecompileLayout
import org.argus.jawa.core.util.{FileResourceUri, ISet}
import org.json4s.{CustomSerializer, Extraction, Formats, JValue}
import org.json4s.JsonDSL._


object DecompileLayoutSerializer extends CustomSerializer[DecompileLayout](format => (
  {
    case jv: JValue =>
      implicit val formats: Formats = format
      val outputUri  = (jv \ "outputUri").extract[FileResourceUri]
      val createFolder = (jv \ "createFolder").extract[Boolean]
      val srcFolder = (jv \ "srcFolder").extract[String]
      val libFolder = (jv \ "libFolder").extract[String]
      val createSeparateFolderForDexes = (jv \ "createSeparateFolderForDexes").extract[Boolean]
      val pkg = (jv \ "pkg").extract[String]
      val outputSrcUri = (jv \ "outputSrcUri").extract[FileResourceUri]
      val sourceFolders = (jv \ "sourceFolders").extract[ISet[String]]
      val libFolders = (jv \ "libFolders").extract[ISet[String]]
      val dependencies = (jv \ "dependencies").extract[ISet[String]]
      val thirdPartyLibraries = (jv \ "thirdPartyLibraries").extract[ISet[String]]
      val layout = DecompileLayout(outputUri, createFolder, srcFolder, libFolder, createSeparateFolderForDexes)
      layout.pkg = pkg
      layout.outputSrcUri = outputSrcUri
      layout.sourceFolders = sourceFolders
      layout.libFolders = libFolders
      layout.dependencies = dependencies
      layout.thirdPartyLibraries = thirdPartyLibraries
      layout
  },
  {
    case layout: DecompileLayout =>
      implicit val formats: Formats = format
      val outputUri: FileResourceUri = layout.outputSrcUri
      val createFolder: Boolean = layout.createFolder
      val srcFolder: String = layout.srcFolder
      val libFolder: String = layout.libFolder
      val createSeparateFolderForDexes: Boolean = layout.createSeparateFolderForDexes
      val pkg: String = layout.pkg
      val outputSrcUri: FileResourceUri = layout.outputSrcUri
      val sourceFolders: ISet[String] = layout.sourceFolders
      val libFolders: ISet[String] = layout.libFolders
      val dependencies: ISet[String] = layout.dependencies
      val thirdPartyLibraries: ISet[String] = layout.thirdPartyLibraries
      ("outputUri" -> outputUri) ~
      ("createFolder" -> createFolder) ~
      ("srcFolder" -> srcFolder) ~
      ("libFolder" -> libFolder) ~
      ("createSeparateFolderForDexes" -> createSeparateFolderForDexes) ~
      ("pkg" -> pkg) ~
      ("outputSrcUri" -> outputSrcUri) ~
      ("sourceFolders" -> Extraction.decompose(sourceFolders)) ~
      ("libFolders" -> Extraction.decompose(libFolders)) ~
      ("dependencies" -> Extraction.decompose(dependencies)) ~
      ("thirdPartyLibraries" -> Extraction.decompose(thirdPartyLibraries))
  }
)) 
Example 7
Source File: TableType.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail.types

import is.hail.expr.ir._
import is.hail.types.physical.{PStruct, PType}
import is.hail.types.virtual.{TStruct, Type}
import is.hail.rvd.RVDType
import is.hail.utils._
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

class TableTypeSerializer extends CustomSerializer[TableType](format => (
  { case JString(s) => IRParser.parseTableType(s) },
  { case tt: TableType => JString(tt.toString) }))

object TableType {
  def keyType(ts: TStruct, key: IndexedSeq[String]): TStruct = ts.typeAfterSelect(key.map(ts.fieldIdx))
  def valueType(ts: TStruct, key: IndexedSeq[String]): TStruct = ts.filterSet(key.toSet, include = false)._1
}

case class TableType(rowType: TStruct, key: IndexedSeq[String], globalType: TStruct) extends BaseType {
  lazy val canonicalRowPType = PType.canonical(rowType).setRequired(true).asInstanceOf[PStruct]
  lazy val canonicalRVDType = RVDType(canonicalRowPType, key)

  key.foreach {k =>
    if (!rowType.hasField(k))
      throw new RuntimeException(s"key field $k not in row type: $rowType")
  }

  @transient lazy val globalEnv: Env[Type] = Env.empty[Type]
    .bind("global" -> globalType)

  @transient lazy val rowEnv: Env[Type] = Env.empty[Type]
    .bind("global" -> globalType)
    .bind("row" -> rowType)

  @transient lazy val refMap: Map[String, Type] = Map(
    "global" -> globalType,
    "row" -> rowType)

  def isCanonical: Boolean = rowType.isCanonical && globalType.isCanonical

  lazy val keyType: TStruct = TableType.keyType(rowType, key)
  def keyFieldIdx: Array[Int] = canonicalRVDType.kFieldIdx
  lazy val valueType: TStruct = TableType.valueType(rowType, key)
  def valueFieldIdx: Array[Int] = canonicalRVDType.valueFieldIdx

  def pretty(sb: StringBuilder, indent0: Int = 0, compact: Boolean = false) {
    var indent = indent0

    val space: String = if (compact) "" else " "

    def newline() {
      if (!compact) {
        sb += '\n'
        sb.append(" " * indent)
      }
    }

    sb.append(s"Table$space{")
    indent += 4
    newline()

    sb.append(s"global:$space")
    globalType.pretty(sb, indent, compact)
    sb += ','
    newline()

    sb.append(s"key:$space[")
    key.foreachBetween(k => sb.append(prettyIdentifier(k)))(sb.append(s",$space"))
    sb += ']'
    sb += ','
    newline()

    sb.append(s"row:$space")
    rowType.pretty(sb, indent, compact)

    indent -= 4
    newline()
    sb += '}'
  }
} 
Example 8
Source File: NativeReaderOptions.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail.expr.ir

import is.hail.types.virtual._
import is.hail.expr.JSONAnnotationImpex
import is.hail.utils._
import org.json4s.{CustomSerializer, DefaultFormats, Formats, JObject, JValue}
import org.json4s.JsonDSL._

class NativeReaderOptionsSerializer() extends CustomSerializer[NativeReaderOptions](
  format =>
    ({ case jObj: JObject =>
      implicit val fmt = format
      val filterIntervals = (jObj \ "filterIntervals").extract[Boolean]
      val intervalPointType = IRParser.parseType((jObj \ "intervalPointType").extract[String])
      val intervals = {
        val jv = jObj \ "intervals"
        val ty = TArray(TInterval(intervalPointType))
        JSONAnnotationImpex.importAnnotation(jv, ty).asInstanceOf[IndexedSeq[Interval]]
      }
      NativeReaderOptions(intervals, intervalPointType, filterIntervals)
    }, { case opts: NativeReaderOptions =>
      implicit val fmt = format
      val ty = TArray(TInterval(opts.intervalPointType))
      (("name" -> opts.getClass.getSimpleName) ~
        ("intervals" -> JSONAnnotationImpex.exportAnnotation(opts.intervals, ty)) ~
        ("intervalPointType" -> opts.intervalPointType.parsableString()) ~
        ("filterIntervals" -> opts.filterIntervals))
    })
)

object NativeReaderOptions {
  def fromJValue(jv: JValue): NativeReaderOptions = {
    implicit val formats: Formats = DefaultFormats

    val filterIntervals = (jv \ "filterIntervals").extract[Boolean]
    val intervalPointType = IRParser.parseType((jv \ "intervalPointType").extract[String])
    val intervals = {
      val jvIntervals = jv \ "intervals"
      val ty = TArray(TInterval(intervalPointType))
      JSONAnnotationImpex.importAnnotation(jvIntervals, ty).asInstanceOf[IndexedSeq[Interval]]
    }
    NativeReaderOptions(intervals, intervalPointType, filterIntervals)
  }
}

case class NativeReaderOptions(
  intervals: IndexedSeq[Interval],
  intervalPointType: Type,
  filterIntervals: Boolean = false) {
  def toJson: JValue = {
    val ty = TArray(TInterval(intervalPointType))
    JObject(
      "name" -> "NativeReaderOptions",
      "intervals" -> JSONAnnotationImpex.exportAnnotation(intervals, ty),
      "intervalPointType" -> intervalPointType.parsableString(),
      "filterIntervals" -> filterIntervals)
  }
} 
Example 9
Source File: GenderDetectStrategy.scala    From TransmogrifAI   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.salesforce.op.stages.impl.feature

import enumeratum.{Enum, EnumEntry}
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

import scala.util.Try
import scala.util.matching.Regex


sealed class GenderDetectStrategy extends EnumEntry
case object GenderDetectStrategy extends Enum[GenderDetectStrategy] {
  val values: Seq[GenderDetectStrategy] = findValues
  val delimiter = " WITH VALUE "
  val ByIndexString = "ByIndex"
  val ByLastString = "ByLast"
  val ByRegexString = "ByRegex"
  val FindHonorificString = "FindHonorific"

  case class ByIndex(index: Int) extends GenderDetectStrategy {
    override def toString: String = ByIndexString + delimiter + index.toString
  }
  case class ByLast() extends GenderDetectStrategy {
    override def toString: String = ByLastString
  }
  case class ByRegex(pattern: Regex) extends GenderDetectStrategy {
    override def toString: String = ByRegexString + delimiter + pattern.toString
  }
  case class FindHonorific() extends GenderDetectStrategy {
    override def toString: String = FindHonorificString
  }

  def fromString(s: String): GenderDetectStrategy = {
    Option(s).map(_.split(delimiter)) match {
      case Some(Array(ByIndexString, index)) if Try(index.toInt).isSuccess => ByIndex(index.toInt)
      case Some(Array(ByLastString)) => ByLast()
      case Some(Array(ByRegexString, regex)) if Try (regex.r).isSuccess => ByRegex(regex.r)
      case Some(Array(FindHonorificString)) => FindHonorific()
      case None => sys.error("Attempted to deserialize GenderDetectStrategy but found empty value")
      case _ => sys.error(s"Attempted to deserialize GenderDetectStrategy but no matching entry found for value '$s'")
    }
  }

  def json4s: CustomSerializer[GenderDetectStrategy] = new CustomSerializer[GenderDetectStrategy](_ =>
    (
      { case JString(s) => GenderDetectStrategy.fromString(s) },
      { case x: GenderDetectStrategy => JString(x.toString) }
    )
  )
} 
Example 10
Source File: SpecialDoubleSerializer.scala    From TransmogrifAI   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.salesforce.op.utils.json

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JDouble, JString, JDecimal}


// scalastyle:off
class SpecialDoubleSerializer extends CustomSerializer[Double](ser =>
  ({
    case JString("NaN") => Double.NaN
    case JString("-Infinity") => Double.NegativeInfinity
    case JString("Infinity") => Double.PositiveInfinity
    case JDouble(v) => v
  }, {
    case v: Double if v.isNaN => JString("NaN")
    case Double.NegativeInfinity => JString("-Infinity")
    case Double.PositiveInfinity => JString("Infinity")
    case v: Double if ser.wantsBigDecimal => JDecimal(v)
    case v: Double => JDouble(v)
  })) 
Example 11
Source File: EnumEntrySerializer.scala    From TransmogrifAI   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.salesforce.op.utils.json

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{DeserializationContext, SerializerProvider}
import enumeratum.{Enum, EnumEntry}
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

import scala.reflect.ClassTag


  def jackson[A <: EnumEntry: ClassTag](enum: Enum[A]): SerDes[A] = {
    val klazz = implicitly[ClassTag[A]].runtimeClass.asInstanceOf[Class[A]]
    val ser = new StdSerializer[A](klazz) {
      override def serialize(value: A, gen: JsonGenerator, provider: SerializerProvider): Unit = {
        gen.writeString(value.entryName)
      }
    }
    val des = new StdDeserializer[A](klazz) {
      override def deserialize(p: JsonParser, ctxt: DeserializationContext): A = {
        enum.withNameInsensitive(p.getValueAsString)
      }
    }
    new SerDes[A](klazz, ser, des)
  }

} 
Example 12
Source File: BitSerializer.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.web

import io.radicalbit.nsdb.common._
import io.radicalbit.nsdb.common.protocol.Bit
import org.json4s.JsonAST.{JDouble, JField, JInt, JLong}
import org.json4s.{CustomSerializer, JObject, JString, JsonAST}


case object BitSerializer
    extends CustomSerializer[Bit](
      _ =>
        (
          {
            case _ =>
              throw new IllegalAccessException(
                "BitSerializer can be used only for serialization and not for deserialization")
          }, {
            case bit: Bit =>
              def extractJValue(nsdbType: NSDbType): JsonAST.JValue = {
                nsdbType match {
                  case NSDbDoubleType(rawValue) => JDouble(rawValue)
                  case NSDbIntType(rawValue)    => JInt(rawValue)
                  case NSDbLongType(rawValue)   => JLong(rawValue)
                  case NSDbStringType(rawValue) => JString(rawValue)
                }
              }
              JObject(
                List(
                  JField("timestamp", JLong(bit.timestamp)),
                  JField("value", extractJValue(bit.value)),
                  JField("dimensions",
                         JObject(bit.dimensions.map { case (k, v)   => JField(k, extractJValue(v)) }.toList)),
                  JField("tags", JObject(bit.tags.map { case (k, v) => JField(k, extractJValue(v)) }.toList))
                )
              )
          }
      )) 
Example 13
Source File: CustomSerializerForTest.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.web

import io.radicalbit.nsdb.common.statement.RelativeComparisonValue
import org.json4s.{CustomSerializer, JObject, JString}
import org.json4s.JsonAST.{JField, JInt, JLong}

case object CustomSerializerForTest
    extends CustomSerializer[RelativeComparisonValue](_ =>
      ({
        case JObject(
            List(JField("value", JLong(0L)),
                 JField("operator", JString(operator)),
                 JField("quantity", JInt(quantity)),
                 JField("unitMeasure", JString(unitMeasure)))) =>
          RelativeComparisonValue(0L, operator, quantity.intValue, unitMeasure)
      }, {
        case RelativeComparisonValue(_, operator, quantity: Long, unitMeasure) =>
          JObject(
            List(JField("value", JLong(0L)),
                 JField("operator", JString(operator)),
                 JField("quantity", JLong(quantity)),
                 JField("unitMeasure", JString(unitMeasure))))

      })) 
Example 14
Source File: BoardConfig.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.app

import com.criteo.slab.core.{Box, Layout}
import com.criteo.slab.utils.Jsonable
import org.json4s.JsonAST.{JArray, JString}
import org.json4s.{CustomSerializer, Serializer}


private[slab] case class BoardConfig(
                                      title: String,
                                      layout: Layout,
                                      links: Seq[(Box[_], Box[_])] = Seq.empty,
                                      slo: Double
                                    )

object BoardConfig {
  implicit object ToJSON extends Jsonable[BoardConfig] {
    override val serializers: Seq[Serializer[_]] =
      implicitly[Jsonable[Box[_]]].serializers ++
        implicitly[Jsonable[Layout]].serializers :+
        LinkSer

    object LinkSer extends CustomSerializer[Box[_] Tuple2 Box[_]](_ => ( {
      case _ => throw new NotImplementedError("Not deserializable")
    }, {
      case (Box(title1, _, _, _, _), Box(title2, _, _, _, _)) => JArray(List(JString(title1), JString(title2)))
    }
    ))

  }
} 
Example 15
Source File: GraphiteMetric.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.lib.graphite

import com.criteo.slab.utils.Jsonable
import org.json4s.JsonAST.{JArray, JDouble, JInt, JNull}
import org.json4s.{CustomSerializer, Serializer}

private[slab] case class DataPoint(value: Option[Double], timestamp: Long)

object DataPoint {

  implicit object ToJSON extends Jsonable[DataPoint] {
    override val serializers: Seq[Serializer[_]] = List(Ser)

    object Ser extends CustomSerializer[DataPoint](_ => ( {
      case JArray(JDouble(value) :: JInt(date) :: Nil) =>
        DataPoint(Some(value), date.toLong)
      case JArray(JNull :: JInt(date) :: Nil) =>
        DataPoint(None, date.toLong)
    }, {
      case DataPoint(value, date) =>
        val v = value match {
          case Some(v) => JDouble(v)
          case None => JNull
        }
        JArray(
          List(
            v,
            JInt(date)
          )
        )
    }
    ))

  }

}

private[slab] case class GraphiteMetric(
                                         target: String,
                                         datapoints: List[DataPoint]
                                       )

object GraphiteMetric {

  implicit object ToJSON extends Jsonable[GraphiteMetric] {
    override val serializers: Seq[Serializer[_]] = implicitly[Jsonable[DataPoint]].serializers
  }

} 
Example 16
Source File: Box.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.core

import com.criteo.slab.utils.Jsonable
import org.json4s.CustomSerializer
import org.json4s.JsonDSL._


case class Box[T](
                   title: String,
                   checks: Seq[Check[T]],
                   aggregate: (Map[Check[T], CheckResult[T]], Context) => View,
                   description: Option[String] = None,
                   labelLimit: Option[Int] = None
                 )

object Box {

  implicit object toJSON extends Jsonable[Box[_]] {
    override val serializers = List(Ser)

    object Ser extends CustomSerializer[Box[_]](_ => ({
      case _ => throw new NotImplementedError("Not deserializable")
    }, {
      case box: Box[_] =>
        ("title" -> box.title) ~ ("description" -> box.description) ~ ("labelLimit" -> box.labelLimit.getOrElse(64))
    }))

  }

} 
Example 17
Source File: Status.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.core

import com.criteo.slab.utils.Jsonable
import org.json4s.JsonAST.JString
import org.json4s.{CustomSerializer, Serializer}


sealed class Status(val name: String, val level: Int) extends Ordered[Status] {
  override def compare(that: Status) = this.level.compare(that.level)
}

object Status {
  case object Success extends Status("SUCCESS", 0)
  case object Warning extends Status("WARNING", 1)
  case object Error extends Status("ERROR", 2)
  case object Unknown extends Status("UNKNOWN", 3)

  def from(in: String) = in.toUpperCase match {
    case "SUCCESS" => Success
    case "WARNING" => Warning
    case "ERROR" => Error
    case "UNKNOWN" => Unknown
  }

  implicit object ToJSON extends Jsonable[Status] {
    override val serializers: Seq[Serializer[_]] = List(Ser)

    object Ser extends CustomSerializer[Status](_ => (
      {
        case JString(status) => Status.from(status)
      },
      {
        case s: Status => JString(s.name)
      }
    ))

  }
} 
Example 18
Source File: JSONSerializers.scala    From aardpfark   with Apache License 2.0 5 votes vote down vote up
package com.ibm.aardpfark.pfa.document

import scala.util.Try

import com.ibm.aardpfark.pfa.dsl._
import com.ibm.aardpfark.pfa.expression.PFAExpression
import com.ibm.aardpfark.spark.ml.tree.{TreeNode, Trees}
import org.apache.avro.Schema
import org.json4s.native.JsonMethods.parse
import org.json4s.{CustomSerializer, JValue}


object SchemaSerializer {

  def convert(s: Schema): JValue = {
    import Schema.Type._
    import org.json4s.JsonDSL._
    s.getType match {
      case DOUBLE | FLOAT | INT | LONG | STRING | BOOLEAN | BYTES | NULL  =>
        ("type" -> s.getType.getName)
      case _ =>
        parse(s.toString)
    }
  }
}

class SchemaSerializer extends CustomSerializer[Schema](format => (
  {
    case j: JValue =>
      new Schema.Parser().parse(j.toString)
  },
  {
    case s: Schema =>
      SchemaSerializer.convert(s)
  }
)
)

class PFAExpressionSerializer extends CustomSerializer[PFAExpression](format => (
  {
    case j: JValue =>
      throw new UnsupportedOperationException("cannot deserialize")
  },
  {
    case expr: PFAExpression =>
      expr.json
  }
)
)

class TreeSerializer extends CustomSerializer[TreeNode](format => (
  {
    case j: JValue =>
      throw new UnsupportedOperationException("cannot deserialize")
  },
  {
    case tree: TreeNode =>
      Trees.json(tree)
  }
)
)

class ParamSerializer extends CustomSerializer[Param](format => (
  {
    case j: JValue =>
      throw new UnsupportedOperationException("cannot deserialize")
  },
  {
    case p: Param =>
      import org.json4s.JsonDSL._
      if (p.simpleSchema) {
        (p.name -> p.`type`.getFullName)
      } else {
        val schemaSerializer = new SchemaSerializer().serialize(format)
        (p.name -> schemaSerializer(p.`type`))
      }

  }
)
) 
Example 19
Source File: ComponentFlagSerializer.scala    From PackUpdate   with Apache License 2.0 5 votes vote down vote up
package at.chaosfield.packupdate.json.serializer

import at.chaosfield.packupdate.common.ComponentFlag
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

object ComponentFlagSerializer extends CustomSerializer[ComponentFlag](format => (
  {
    case JString(string: String) => ComponentFlag.fromString(string) match {
      case Some(flag) => flag
      case None => throw new Exception(s"unknown component flag $string")
    }
  },
  {
    case ty: ComponentFlag => JString(ty.internalName)
  }
)) 
Example 20
Source File: ComponentTypeSerializer.scala    From PackUpdate   with Apache License 2.0 5 votes vote down vote up
package at.chaosfield.packupdate.json.serializer

import at.chaosfield.packupdate.common.ComponentType
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

object ComponentTypeSerializer extends CustomSerializer[ComponentType](format => (
  {
    case JString(string: String) => ComponentType.fromString(string) match {
      case Some(ty) => ty
      case None => throw new Exception(s"unknown component type $string")
    }
  },
  {
    case ty: ComponentType => JString(ty.stringValue)
  }
)) 
Example 21
Source File: CustomFormats.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.http.serializers

import java.time._

import com.danielasfregola.twitter4s.entities.enums.DisconnectionCode
import com.danielasfregola.twitter4s.entities.enums.DisconnectionCode.DisconnectionCode
import com.danielasfregola.twitter4s.entities.ProfileImage
import org.json4s.JsonAST.{JInt, JLong, JNull, JString}
import org.json4s.{CustomSerializer, Formats}

private[twitter4s] object CustomFormats extends FormatsComposer {

  override def compose(f: Formats): Formats =
    f + InstantSerializer + LocalDateSerializer + DisconnectionCodeSerializer + ProfileImageSerializer

}

private[twitter4s] case object InstantSerializer
    extends CustomSerializer[Instant](format =>
      ({
        case JInt(i)                                            => DateTimeFormatter.parseInstant(i.toLong)
        case JLong(l)                                           => DateTimeFormatter.parseInstant(l)
        case JString(s) if DateTimeFormatter.canParseInstant(s) => DateTimeFormatter.parseInstant(s)
        case JString(stringAsUnixTime) if stringAsUnixTime.forall(_.isDigit) =>
          Instant.ofEpochMilli(stringAsUnixTime.toLong)
      }, {
        case instant: Instant => JString(DateTimeFormatter.formatInstant(instant))
      }))

private[twitter4s] case object LocalDateSerializer
    extends CustomSerializer[LocalDate](format =>
      ({
        case JString(dateString) =>
          dateString.split("-") match {
            case Array(year, month, date) => LocalDate.of(year.toInt, month.toInt, date.toInt)
            case _                        => null
          }
        case JNull => null
      }, {
        case date: LocalDate => JString(date.toString)
      }))

private[twitter4s] case object DisconnectionCodeSerializer
    extends CustomSerializer[DisconnectionCode](format =>
      ({
        case JInt(n) => DisconnectionCode(n.toInt)
        case JNull   => null
      }, {
        case code: DisconnectionCode => JInt(code.id)
      }))

private[twitter4s] case object ProfileImageSerializer
    extends CustomSerializer[ProfileImage](format =>
      ({
        case JString(n) => ProfileImage(n)
        case JNull      => null
      }, {
        case img: ProfileImage => JString(img.normal)
      })) 
Example 22
Source File: ExceptionSerializer.scala    From reliable-http-client   with Apache License 2.0 5 votes vote down vote up
package rhttpc.transport.json4s

import java.lang.reflect.Constructor

import org.json4s.{CustomSerializer, Extraction, Formats, Serializer, TypeInfo}
import org.json4s.JsonAST._

import scala.util.Try

object ExceptionSerializer extends Serializer[Throwable] {
  override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Throwable] = {
    case (
      TypeInfo(clazz, _),
      JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageAndCause(constructor))) ::
        ("message", JString(message)) ::
        ("cause", cause) ::
        Nil)) if classOf[Throwable].isAssignableFrom(clazz) =>
      constructor.newInstance(message, Extraction.extract[Throwable](cause))
    case (
      TypeInfo(clazz, _),
      JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageAndCause(constructor))) ::
        ("message", JNull) ::
        ("cause", cause) ::
        Nil)) if classOf[Throwable].isAssignableFrom(clazz) =>
      constructor.newInstance(null, Extraction.extract[Throwable](cause))
    case (
      TypeInfo(clazz, _),
      JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageOnly(constructor))) ::
        ("message", JString(message)) ::
        Nil)) if classOf[Throwable].isAssignableFrom(clazz) =>
      constructor.newInstance(message)
    case (
      TypeInfo(clazz, _),
      JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageOnly(constructor))) ::
        ("message", JNull) ::
        Nil)) if classOf[Throwable].isAssignableFrom(clazz) =>
      constructor.newInstance(null)
  }

  override def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case ExceptionInstanceHavingConstructorWithMessageAndCause(ex) =>
      JObject(
        formats.typeHintFieldName -> JString(ex.getClass.getName),
        "message" -> Option(ex.getMessage).map(JString).getOrElse(JNull),
        "cause" -> Extraction.decompose(ex.getCause)
      )
    case ExceptionInstanceHavingConstructorWithMessageOnly(ex) =>
      JObject(
        formats.typeHintFieldName -> JString(ex.getClass.getName),
        "message" -> Option(ex.getMessage).map(JString).getOrElse(JNull)
      )
  }
}


object ExceptionClassHavingConstructorWithMessageAndCause {
  def unapply(className: String): Option[Constructor[Throwable]] = {
    (for {
      clazz <- Try(Class.forName(className))
      if classOf[Throwable].isAssignableFrom(clazz)
      constructor <- constructorWithMessageAndCause(clazz)
    } yield constructor).toOption
  }

  def constructorWithMessageAndCause(clazz: Class[_]): Try[Constructor[Throwable]] =
    Try(clazz.getDeclaredConstructor(classOf[String], classOf[Throwable]).asInstanceOf[Constructor[Throwable]])
}

object ExceptionInstanceHavingConstructorWithMessageAndCause {

  def unapply(instance: Throwable): Option[Throwable] = {
    ExceptionClassHavingConstructorWithMessageAndCause.constructorWithMessageAndCause(instance.getClass).map(_ => instance).toOption
  }

}

object ExceptionClassHavingConstructorWithMessageOnly {
  def unapply(className: String): Option[Constructor[Throwable]] = {
    (for {
      clazz <- Try(Class.forName(className))
      if classOf[Throwable].isAssignableFrom(clazz)
      constructor <- constructorWithMessageOnly(clazz)
    } yield constructor).toOption
  }

  def constructorWithMessageOnly(clazz: Class[_]): Try[Constructor[Throwable]] =
    Try(clazz.getDeclaredConstructor(classOf[String]).asInstanceOf[Constructor[Throwable]])
}

object ExceptionInstanceHavingConstructorWithMessageOnly {

  def unapply(instance: Throwable): Option[Throwable] = {
    ExceptionClassHavingConstructorWithMessageOnly.constructorWithMessageOnly(instance.getClass).map(_ => instance).toOption
  }

} 
Example 23
Source File: EncryptedKeyJsonCodec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.keystore

import java.util.UUID

import akka.util.ByteString
import io.iohk.ethereum.domain.Address
import io.iohk.ethereum.keystore.EncryptedKey._
import org.json4s.JsonAST.{JObject, JString, JValue}
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.{CustomSerializer, DefaultFormats, Extraction, JField}
import org.spongycastle.util.encoders.Hex

import scala.util.Try

object EncryptedKeyJsonCodec {

  private val byteStringSerializer = new CustomSerializer[ByteString](_ => (
    { case JString(s) => ByteString(Hex.decode(s)) },
    { case bs: ByteString => JString(Hex.toHexString(bs.toArray)) }
  ))

  private implicit val formats = DefaultFormats + byteStringSerializer

  private def asHex(bs: ByteString): String =
    Hex.toHexString(bs.toArray)

  def toJson(encKey: EncryptedKey): String = {
    import encKey._
    import cryptoSpec._

    val json =
      ("id" -> id.toString) ~
      ("address" -> asHex(address.bytes)) ~
      ("version" -> version) ~
      ("crypto" -> (
        ("cipher" -> cipher) ~
        ("ciphertext" -> asHex(ciphertext)) ~
        ("cipherparams" -> ("iv" -> asHex(iv))) ~
        encodeKdf(kdfParams) ~
        ("mac" -> asHex(mac))
      ))

    pretty(render(json))
  }

  def fromJson(jsonStr: String): Either[String, EncryptedKey] = Try {
    val json = parse(jsonStr).transformField { case JField(k, v) => JField(k.toLowerCase, v) }

    val uuid = UUID.fromString((json \ "id").extract[String])
    val address = Address((json \ "address").extract[String])
    val version = (json \ "version").extract[Int]

    val crypto = json \ "crypto"
    val cipher = (crypto \ "cipher").extract[String]
    val ciphertext = (crypto \ "ciphertext").extract[ByteString]
    val iv = (crypto \ "cipherparams" \ "iv").extract[ByteString]
    val mac = (crypto \ "mac").extract[ByteString]

    val kdfParams = extractKdf(crypto)
    val cryptoSpec = CryptoSpec(cipher, ciphertext, iv, kdfParams, mac)
    EncryptedKey(uuid, address, cryptoSpec, version)

  }.fold(ex => Left(ex.toString), encKey => Right(encKey))

  private def encodeKdf(kdfParams: KdfParams): JObject =
    kdfParams match {
      case ScryptParams(salt, n, r, p, dklen) =>
        ("kdf" -> Scrypt) ~
        ("kdfparams" -> Extraction.decompose(kdfParams))

      case Pbkdf2Params(salt, prf, c, dklen) =>
        ("kdf" -> Pbkdf2) ~
        ("kdfparams" -> Extraction.decompose(kdfParams))
    }

  private def extractKdf(crypto: JValue): KdfParams = {
    val kdf = (crypto \ "kdf").extract[String]
    kdf.toLowerCase match {
      case Scrypt =>
        (crypto \ "kdfparams").extract[ScryptParams]

      case Pbkdf2 =>
        (crypto \ "kdfparams").extract[Pbkdf2Params]
    }
  }

} 
Example 24
Source File: OrderDomain.scala    From akka-serialization-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.domain

import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

object OrderDomain {
  final val CD = ItemType.CD.toString
  final val DVD = ItemType.DVD.toString
  final val BluRay = ItemType.BluRay.toString
  final val Game = ItemType.Game.toString

  case object DirectDebitTypeSerializer extends CustomSerializer[ItemType](_ ⇒ ({
    case JString(CD)     ⇒ ItemType.CD
    case JString(DVD)    ⇒ ItemType.DVD
    case JString(BluRay) ⇒ ItemType.BluRay
    case JString(Game)   ⇒ ItemType.Game
  }, {
    case msg: ItemType ⇒ JString(msg.toString)
  }))

  type Title = String
  type Price = Double
  type ItemId = Option[String]

  type ZipCode = String
  type HouseNumber = Int

  type OrderName = String
  type Items = List[Item]
  type UnixTimestamp = Long
  type OrderId = Option[String]

  sealed trait ItemType
  object ItemType {
    case object CD extends ItemType
    case object DVD extends ItemType
    case object BluRay extends ItemType
    case object Game extends ItemType
  }

  final case class Item(itemType: ItemType, title: Title, price: Price, id: ItemId)
  final case class Address(zipcode: ZipCode, houseNumber: HouseNumber)
  final case class Order(name: OrderName, address: Address, items: Items, date: UnixTimestamp, id: OrderId)

  def withOrder(f: Order ⇒ Order = identity[Order])(g: Order ⇒ Unit): Unit = (g compose f)(Order(
    name = "",
    address = Address("", 1),
    items = List(Item(ItemType.BluRay, "", 25.0, Option("itemId"))),
    date = 1L,
    Some("orderId")
  ))
} 
Example 25
Source File: SparkKind.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.engine.spark.common

import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString


object SparkKind {
  val SCALA_LAN = "scala"
  val PYTHON_LAN = "python"
  val PYTHON_END = "py"
  val R_LAN = "r"
  val SQL_LAN = "sql"
  val ML_LAN = "ml"

  val SPARK_TYPE = "spark"
  val SPARKSCALA_TYPE = "sparkscala"
  val PYSPARK_TYPE = "pyspark"
  val SPARKR_TYPE = "sparkr"
  val SPARKMIX_TYPE = "sparkmix"
  val MIX_TYPE = "mix"
  val SPARKSQL_TYPE = "sparksql"
  val SPARKMLSQL_TYPE = "mlsql"
  val FUNCTION_MDQ_TYPE = "function.mdq"

  def getCodeKind(code: String): Kind = {
    getKind(Kind.getKind(code))
  }

  def getSessionKind(code: String) = {
    val kindStr = Kind.getKindString(code)
    if(kindStr.indexOf("@") == 0) getKind(kindStr.substring(1)) else SparkMix()
  }

  private def getKind(kindStr: String) = {
    kindStr match {
      case SPARKSCALA_TYPE | SCALA_LAN => SparkScala()
      case PYSPARK_TYPE | PYTHON_LAN | PYTHON_END => PySpark()
      case SPARKR_TYPE | R_LAN => SparkR()
      case SPARKMIX_TYPE | MIX_TYPE => SparkMix()
      case SQL_LAN | SPARKSQL_TYPE => SparkSQL()
      case SPARKMLSQL_TYPE | ML_LAN => SparkMLSQL()
      case _ => throw new RuntimeException("Unknown code kind: " + kindStr)
    }
  }

}
import com.webank.wedatasphere.linkis.engine.spark.common.SparkKind._
case class SparkScala() extends Kind {
  override val toString = SPARKSCALA_TYPE
}
case class PySpark() extends Kind {
  override val toString = PYSPARK_TYPE
}

case class SparkR() extends Kind {
  override val toString = SPARKR_TYPE
}

case class SparkMix() extends Kind {
  override val toString: String = SPARKMIX_TYPE
}

case class SparkSQL() extends Kind {
  override val toString: String = SPARKSQL_TYPE
}

case class SparkMLSQL() extends Kind {
  override val toString = SPARKMLSQL_TYPE
}

case object SparkSessionKindSerializer extends CustomSerializer[Kind](implicit formats => ( {
  case JString(SPARKSCALA_TYPE) | JString(SCALA_LAN) => SparkScala()
  case JString(PYSPARK_TYPE) | JString(PYTHON_LAN) | JString(PYTHON_END) => PySpark()
  case JString(SPARKR_TYPE) | JString(R_LAN) => SparkR()
  case JString(SPARKMIX_TYPE) | JString(MIX_TYPE) => SparkMix()
  case JString(SQL_LAN) | JString(SPARKSQL_TYPE) => SparkSQL()
  case JString(SPARKMLSQL_TYPE) | JString(ML_LAN) => SparkMLSQL()
}, {
  case kind: Kind => JString(kind.toString)
})
) 
Example 26
Source File: ResultResource.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.resourcemanager

import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.{CustomSerializer, Extraction}


trait ResultResource

case class NotEnoughResource(reason: String = null) extends ResultResource

case class AvailableResource(ticketId: String) extends ResultResource

case class UserResultResource(ticketId: String, user: String) extends ResultResource

object ResultResourceSerializer extends CustomSerializer[ResultResource](implicit formats => ( {
  case JObject(List(("NotEnoughResource", JObject(List(("reason", reason)))))) => NotEnoughResource(reason.extract[String])
  case JObject(List(("AvailableResource", JObject(List(("ticketId", ticketId)))))) => AvailableResource(ticketId.extract[String])
  case JObject(List(("UserResultResource", JObject(List(("ticketId", ticketId), ("user", user)))))) =>
    UserResultResource(ticketId.extract[String], user.extract[String])
}, {
  case r: NotEnoughResource => ("NotEnoughResource", ("reason", Extraction.decompose(r.reason)))
  case r: AvailableResource => ("AvailableResource", ("ticketId", Extraction.decompose(r.ticketId)))
  case r: UserResultResource => ("UserResultResource", ("ticketId", r.ticketId) ~ ("user", r.user))
})) 
Example 27
Source File: ModuleResourceInfo.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.resourcemanager.domain

import com.webank.wedatasphere.linkis.common.ServiceInstance
import com.webank.wedatasphere.linkis.resourcemanager.{Resource, ResourceSerializer}
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.{CustomSerializer, DefaultFormats, Extraction}


case class ModuleResourceInfo(moduleInstance: ServiceInstance, totalResource: Resource, usedResource: Resource)

object ModuleResourceInfoSerializer extends CustomSerializer[ModuleResourceInfo](implicit formats => ( {
  case JObject(List(("ModuleResourceInfo", JObject(List(("moduleInstance", moduleInstance), ("totalResource", totalResource), ("usedResource", usedResource)))))) =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    ModuleResourceInfo(moduleInstance.extract[ServiceInstance], totalResource.extract[Resource], usedResource.extract[Resource])
}, {
  case m: ModuleResourceInfo =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    ("ModuleResourceInfo", new JObject(List(("moduleInstance", Extraction.decompose(m.moduleInstance)), ("totalResource", Extraction.decompose(m.totalResource)), ("usedResource", Extraction.decompose(m.usedResource)))))
}))

case class ModuleResourceRecord(moduleInfo: ModuleInfo, moduleUsedResources: Resource, moduleLeftResource: Resource, moduleLockedResource: Resource, registerTime: Long = System.currentTimeMillis()) 
Example 28
Source File: ModuleInfo.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.resourcemanager.domain

import com.webank.wedatasphere.linkis.common.ServiceInstance
import com.webank.wedatasphere.linkis.resourcemanager.ResourceRequestPolicy.ResourceRequestPolicy
import com.webank.wedatasphere.linkis.resourcemanager.{Resource, ResourceRequestPolicy, ResourceSerializer}
import org.json4s.JsonAST.JObject
import org.json4s.{CustomSerializer, DefaultFormats, Extraction}


case class ModuleInfo(moduleInstance: ServiceInstance,
                      totalResource: Resource,
                      protectedResource: Resource, //Enter the protection mode when the resource reaches(当资源达到多少时,进入保护模式)
                      resourceRequestPolicy: ResourceRequestPolicy
                     )

object ModuleInfoSerializer extends CustomSerializer[ModuleInfo](implicit formats => ( {
  case JObject(List(("moduleInstance", moduleInstance), ("totalResource", totalResource), ("protectedResource", protectedResource), ("resourceRequestPolicy", resourceRequestPolicy))) =>
    implicit val formats = DefaultFormats + ResourceSerializer + ModuleInstanceSerializer
    new ModuleInfo(moduleInstance.extract[ServiceInstance], totalResource.extract[Resource], protectedResource.extract[Resource], ResourceRequestPolicy.withName(resourceRequestPolicy.extract[String]))
}, {
  case i: ModuleInfo =>
    implicit val formats = DefaultFormats + ResourceSerializer + ModuleInstanceSerializer
    val policy = Extraction.decompose(i.resourceRequestPolicy.toString)
    new JObject(List(("moduleInstance", Extraction.decompose(i.moduleInstance)), ("totalResource", Extraction.decompose(i.totalResource)), ("protectedResource", Extraction.decompose(i.protectedResource)), ("resourceRequestPolicy", policy)))
})
) 
Example 29
Source File: UserResourceInfo.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.resourcemanager.domain

import com.webank.wedatasphere.linkis.common.ServiceInstance
import com.webank.wedatasphere.linkis.resourcemanager.{Resource, ResourceSerializer}
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.{CustomSerializer, DefaultFormats, Extraction}



trait UserResourceInfo

case class UserPreUsedResource(ticketId: String, moduleInstance: ServiceInstance, resource: Resource) extends UserResourceInfo

case class UserUsedResource(ticketId: String, moduleInstance: ServiceInstance, resource: Resource, engineInstance: ServiceInstance = null) extends UserResourceInfo

case class UserReleasedResource(ticketId: String, moduleInstance: ServiceInstance) extends UserResourceInfo


object UserResourceInfoSerializer extends CustomSerializer[UserResourceInfo](implicit formats => ( {
  case JObject(List(("UserPreUsedResource", JObject(List(("ticketId", ticketId), ("moduleInstance", moduleInstance), ("resource", resource)))))) =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    new UserPreUsedResource(ticketId.extract[String], moduleInstance.extract[ServiceInstance], resource.extract[Resource])
  case JObject(List(("UserUsedResource", JObject(List(("ticketId", ticketId), ("moduleInstance", moduleInstance), ("resource", resource), ("engineInstance", engineInstance)))))) =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    new UserUsedResource(ticketId.extract[String], moduleInstance.extract[ServiceInstance], resource.extract[Resource], engineInstance.extract[ServiceInstance])
  case JObject(List(("UserReleasedResource", JObject(List(("ticketId", ticketId), ("moduleInstance", moduleInstance)))))) =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    new UserReleasedResource(ticketId.extract[String], moduleInstance.extract[ServiceInstance])
}, {
  case d: UserPreUsedResource =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    ("UserPreUsedResource", new JObject(List(("ticketId", Extraction.decompose(d.ticketId)), ("moduleInstance", Extraction.decompose(d.moduleInstance)), ("resource", Extraction.decompose(d.resource)))))
  case d: UserUsedResource =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    ("UserUsedResource", new JObject(List(("ticketId", Extraction.decompose(d.ticketId)), ("moduleInstance", Extraction.decompose(d.moduleInstance)), ("resource", Extraction.decompose(d.resource)), ("engineInstance", Extraction.decompose(d.engineInstance)))))
  case d: UserReleasedResource =>
    implicit val formats = DefaultFormats + ModuleInstanceSerializer + ResourceSerializer
    ("UserReleasedResource", new JObject(List(("ticketId", Extraction.decompose(d.ticketId)), ("moduleInstance", Extraction.decompose(d.moduleInstance)))))
})
) 
Example 30
Source File: JavaCollectionSerializer.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.rpc.transform

import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper
import org.json4s.{CustomSerializer, JArray, JObject}
import org.json4s.jackson.Serialization.write
import org.json4s.jackson.JsonMethods.parse

//TODO is now only the simplest implementation, and there is a need to optimize it later.(TODO 现在只做最简单的实现,后续有需要再优化)

object JavaCollectionSerializer extends CustomSerializer[java.util.List[_]](implicit formats => ( {
  case j: JArray=> BDPJettyServerHelper.gson.fromJson(write(j), classOf[java.util.List[_]])
}, {
  case list: java.util.List[_] => parse(BDPJettyServerHelper.gson.toJson(list))
}
)
)

object JavaMapSerializer extends CustomSerializer[java.util.Map[_, _]](implicit formats => ( {
  case j: JObject => BDPJettyServerHelper.gson.fromJson(write(j), classOf[java.util.Map[_, _]])
}, {
  case map: java.util.Map[_, _] => parse(BDPJettyServerHelper.gson.toJson(map))
}
)
) 
Example 31
Source File: RPCFormatsTest.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.rpc

import java.lang.reflect.ParameterizedType
import java.util

import com.webank.wedatasphere.linkis.rpc.transform.{JavaCollectionSerializer, JavaMapSerializer}
import org.apache.commons.lang.ClassUtils
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.jackson.Serialization
import org.json4s.reflect.ManifestFactory
import org.json4s.{CustomSerializer, DefaultFormats, Extraction}

object RPCFormatsTest {

  trait ResultResource
  class AvailableResource(val ticketId: String) extends ResultResource

  object ResultResourceSerializer extends CustomSerializer[ResultResource](implicit formats => ({
    case JObject(List(("AvailableResource", JObject(List(("ticketId", ticketId)))))) => new AvailableResource(ticketId.extract[String])
  },{
    case r: AvailableResource => ("AvailableResource", ("ticketId", Extraction.decompose(r.ticketId)))
  }))

  def testRPC1(args: Array[String]): Unit = {
    implicit val formats = DefaultFormats + ResultResourceSerializer
    val serializerClasses = formats.customSerializers.map(_.getClass.getGenericSuperclass match {
      case p: ParameterizedType =>
        val params = p.getActualTypeArguments
        if(params == null || params.isEmpty) null
        else params(0).asInstanceOf[Class[_]]
    }).filter(_ != null)
    val a = new AvailableResource("aaa")
    val str = Serialization.write(a)
    println(str)
    val clazz = classOf[AvailableResource]
    println(serializerClasses)
    val realClass1 = serializerClasses.find(ClassUtils.isAssignable(clazz, _))
    println(realClass1)
    val realClass = realClass1.getOrElse(clazz)
    val obj = Serialization.read(str)(formats, ManifestFactory.manifestOf(realClass))
    println(obj)
    println(classOf[Array[_]].getClass.getName)
  }

  case class TestCollection1(a: String, list: java.util.List[String])
  case class TestCollection2(a: String, list: java.util.Map[String, Integer])

  def testRPC2(args: Array[String]): Unit = {
    implicit val formats = DefaultFormats + JavaCollectionSerializer + JavaMapSerializer
    //    val a = TestCollection1("1", new util.ArrayList[String]())
    val a = TestCollection2("1", new util.HashMap[String, Integer]())
    //    a.list.add("1111")
    a.list.put("1111", 2)
    val str = Serialization.write(a)
    println(str)
    val realClass = classOf[TestCollection2]
    val obj = Serialization.read(str)(formats, ManifestFactory.manifestOf(realClass))
    println(obj)
  }

  def main(args: Array[String]): Unit = {
    testRPC2(args)
  }
} 
Example 32
Source File: JsonSerializers.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.jsonrpc

import akka.util.ByteString
import io.iohk.ethereum.domain.Address
import org.json4s.JsonAST.{JNull, JString}
import org.json4s.CustomSerializer
import org.spongycastle.util.encoders.Hex

object JsonSerializers {

  object UnformattedDataJsonSerializer extends CustomSerializer[ByteString](_ =>
    (
      { PartialFunction.empty },
      { case bs: ByteString => JString(s"0x${Hex.toHexString(bs.toArray)}") }
    )
  )

  object QuantitiesSerializer extends CustomSerializer[BigInt](_ =>
    (
      {PartialFunction.empty},
      {
        case n: BigInt =>
          if(n == 0)
            JString("0x0")
          else
            JString(s"0x${Hex.toHexString(n.toByteArray).dropWhile(_ == '0')}")
      }
    )
  )

  object OptionNoneToJNullSerializer extends CustomSerializer[Option[_]](formats =>
    (
      {PartialFunction.empty},
      { case None => JNull }
    )
  )

  object AddressJsonSerializer extends CustomSerializer[Address](_ =>
    (
      { PartialFunction.empty },
      { case addr: Address => JString(s"0x${Hex.toHexString(addr.bytes.toArray)}")  }
    )
  )

} 
Example 33
Source File: VatReturnDeclaration.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.json4s.JsonAST._
import org.json4s.native.Serialization
import org.json4s.{CustomSerializer, DefaultFormats}
import uk.gov.hmrc.vatapi.models.Amount

object VatReturnDeclaration {
}

case class VatReturnDeclaration(
                                 periodKey: String,
                                 vatDueSales: Amount,
                                 vatDueAcquisitions: Amount,
                                 vatDueTotal: Amount,
                                 vatReclaimedCurrPeriod: Amount,
                                 vatDueNet: Amount,
                                 totalValueSalesExVAT: Amount,
                                 totalValuePurchasesExVAT: Amount,
                                 totalValueGoodsSuppliedExVAT: Amount,
                                 totalAllAcquisitionsExVAT: Amount,
                                 agentReferenceNumber: Option[String] = None,
                                 receivedAt: DateTime
                               ) {
  def toJsonString: String = {
    implicit val formats = DefaultFormats ++ Seq(BigDecimalSerializer) ++ Seq(JodaSerializer)
    Serialization.write(this)
  }
}


private object BigDecimalSerializer extends CustomSerializer[Amount](format => ( {
  case jde: JDecimal => jde.num
}, {
  case bd: Amount => JDecimal(bd.setScale(2))
}
))

private object JodaSerializer extends CustomSerializer[DateTime](format => ( {
  case js: JString => DateTime.parse(js.s)
}, {
  case dt: DateTime => {
    val fmt = ISODateTimeFormat.dateTime()
    JString(dt.toString(fmt))
  }
}
)) 
Example 34
Source File: ResponseParser.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import org.json4s.native.JsonMethods.{pretty, render}
import org.json4s.{CustomSerializer, JObject}

import scala.util.control.NonFatal

class ResponseParser[T](f: JObject => T)(implicit m: Manifest[T]) extends CustomSerializer[T](_ => ({
  case o: JObject =>
    try {
      f(o)
    } catch {
      case NonFatal(t) => throw ResponseParseException(pretty(render(o)), t)
    }
}, PartialFunction.empty))

case class ResponseParseException(doc: String, cause: Throwable)
  extends Exception(s"Unable to parse document:\n$doc", cause) 
Example 35
Source File: DoNothingNetwork.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.util

import org.json4s.CustomSerializer
import stellar.sdk.Network
import stellar.sdk.inet.HorizonAccess
import stellar.sdk.model.response.{DataValueResponse, TransactionPostResponse}
import stellar.sdk.model.{HorizonCursor, HorizonOrder, SignedTransaction}

import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag

class DoNothingNetwork(override val passphrase: String = "Scala SDK do-nothing network") extends Network {
  override val horizon: HorizonAccess = new HorizonAccess {
    override def post(txn: SignedTransaction)(implicit ec: ExecutionContext): Future[TransactionPostResponse] = ???

    override def get[T: ClassTag](path: String, params: Map[String, String])
      (implicit ec: ExecutionContext, m: Manifest[T]): Future[T] =
      if (path.endsWith("data/data_key")) {
        Future(DataValueResponse("00").asInstanceOf[T])(ec)
      } else ???

    override def getStream[T: ClassTag](path: String, de: CustomSerializer[T], cursor: HorizonCursor, order: HorizonOrder, params: Map[String, String] = Map.empty)
      (implicit ec: ExecutionContext, m: Manifest[T]): Future[LazyList[T]] =
      ???

    override def getSeq[T: ClassTag](path: String, de: CustomSerializer[T], params: Map[String, String])
      (implicit ec: ExecutionContext, m: Manifest[T]): Future[LazyList[T]] =
      Future.successful(LazyList.empty[T])
  }
} 
Example 36
Source File: JobFrequency.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}

sealed trait JobFrequency
case object Daily extends JobFrequency
case object Hourly extends JobFrequency

case object JobFrequencySerializer extends CustomSerializer[JobFrequency](format => (
  {
    case JString(frequency) => frequency match {
      case "Daily" => Daily
      case "Hourly" => Hourly
    }
    case JNull => null
  },
  {
    case frequency: JobFrequency => JString(frequency.getClass.getSimpleName.replace("$", ""))
  }
)) 
Example 37
Source File: JobType.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}

sealed trait JobType
case object Console extends JobType
case object Sql extends JobType

object JobTypeSerializer extends CustomSerializer[JobType](format => (
  {
    case JString(jobType) => jobType match {
      case "Console" => Console
      case "Sql" => Sql
    }
    case JNull => null
  },
  {
    case jobType: JobType => JString(jobType.getClass.getSimpleName.replace("$", ""))
  }
)) 
Example 38
Source File: JobFrequency.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}

sealed trait JobFrequency
case object Daily extends JobFrequency
case object Hourly extends JobFrequency

case object JobFrequencySerializer extends CustomSerializer[JobFrequency](format => (
  {
    case JString(frequency) => frequency match {
      case "Daily" => Daily
      case "Hourly" => Hourly
    }
    case JNull => null
  },
  {
    case frequency: JobFrequency => JString(frequency.getClass.getSimpleName.replace("$", ""))
  }
)) 
Example 39
Source File: JobType.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}

sealed trait JobType
case object Console extends JobType
case object Sql extends JobType

object JobTypeSerializer extends CustomSerializer[JobType](format => (
  {
    case JString(jobType) => jobType match {
      case "Console" => Console
      case "Sql" => Sql
    }
    case JNull => null
  },
  {
    case jobType: JobType => JString(jobType.getClass.getSimpleName.replace("$", ""))
  }
)) 
Example 40
Source File: BasicBitcoinJsonRPCClient.scala    From eclair   with Apache License 2.0 5 votes vote down vote up
package fr.acinq.eclair.blockchain.bitcoind.rpc

import com.softwaremill.sttp._
import com.softwaremill.sttp.json4s._
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.eclair.KamonExt
import fr.acinq.eclair.blockchain.Monitoring.{Metrics, Tags}
import org.json4s.{CustomSerializer, DefaultFormats}
import org.json4s.JsonAST.{JString, JValue}
import org.json4s.jackson.Serialization

import scala.concurrent.{ExecutionContext, Future}

class BasicBitcoinJsonRPCClient(user: String, password: String, host: String = "127.0.0.1", port: Int = 8332, ssl: Boolean = false)(implicit http: SttpBackend[Future, Nothing]) extends BitcoinJsonRPCClient {

  // necessary to properly serialize ByteVector32 into String readable by bitcoind
  object ByteVector32Serializer extends CustomSerializer[ByteVector32](_ => ( {
    null
  }, {
    case x: ByteVector32 => JString(x.toHex)
  }))
  implicit val formats = DefaultFormats.withBigDecimal + ByteVector32Serializer
  private val scheme = if (ssl) "https" else "http"
  private val serviceUri = uri"$scheme://$host:$port/wallet/" // wallet/ specifies to use the default bitcoind wallet, named ""
  implicit val serialization = Serialization

  override def invoke(method: String, params: Any*)(implicit ec: ExecutionContext): Future[JValue] =
    invoke(Seq(JsonRPCRequest(method = method, params = params))).map(l => jsonResponse2Exception(l.head).result)

  def jsonResponse2Exception(jsonRPCResponse: JsonRPCResponse): JsonRPCResponse = jsonRPCResponse match {
    case JsonRPCResponse(_, Some(error), _) => throw JsonRPCError(error)
    case o => o
  }

  def invoke(requests: Seq[JsonRPCRequest])(implicit ec: ExecutionContext): Future[Seq[JsonRPCResponse]] = {
    requests.groupBy(_.method).foreach {
      case (method, calls) => Metrics.RpcBasicInvokeCount.withTag(Tags.Method, method).increment(calls.size)
    }
    KamonExt.timeFuture(Metrics.RpcBasicInvokeDuration.withoutTags()) {
      for {
        res <- sttp
          .post(serviceUri)
          .body(requests)
          .auth.basic(user, password)
          .response(asJson[Seq[JsonRPCResponse]])
          .send()
      } yield res.unsafeBody
    }
  }

}