org.json4s.JsonAST.JNull Scala Examples

The following examples show how to use org.json4s.JsonAST.JNull. 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: 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 3
Source File: QueryFilter.scala    From XSQL   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.datasources.druid

import org.json4s.JsonAST.{JArray, JNull, JObject, JValue}
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

sealed trait QueryFilter extends Expression {
  def and(other: QueryFilter): QueryFilter = And(Seq(this, other))

  def or(other: QueryFilter): QueryFilter = Or(Seq(this, other))
}

case class And(filters: Seq[Expression]) extends QueryFilter {

  override def and(other: QueryFilter): QueryFilter = copy(other +: filters)

  def toJson: JValue = JObject("type" -> "and", "fields" -> JArray(filters.toList.map(_.toJson)))
}

case class Or(filters: Seq[Expression]) extends QueryFilter {

  override def or(other: QueryFilter): QueryFilter = copy(other +: filters)

  def toJson: JValue = JObject("type" -> "or", "fields" -> JArray(filters.toList.map(_.toJson)))
}

case class Not(filter: Expression) extends QueryFilter {

  def toJson: JValue = JObject("type" -> "not", "field" -> filter.toJson)
}

case class IsNotNull(attributeNotNull: String) extends QueryFilter {

//  {
//    "field": {
//      "type": "selector",
//      "dimension": "added",
//      "value": ""
//    },
//    "type": "not"
//  }
  def toJson: JValue =
    JObject(
      "field" -> JObject("type" -> "selector", "dimension" -> attributeNotNull, "value" -> ""),
      "type" -> "not")
}

case class ExprQueryFilter(typeName: String, dimension: String, value: String)
  extends QueryFilter {
  def toJson: JValue = JObject("type" -> typeName, "dimension" -> dimension, "value" -> value)
}

case class SelectorQueryFilter(dimension: String, value: String) extends QueryFilter {
  def toJson: JValue = JObject("type" -> "selector", "dimension" -> dimension, "value" -> value)
}

case class RegexQueryFilter(dimension: String, pattern: String) extends QueryFilter {
  def toJson: JValue = JObject("type" -> "regex", "dimension" -> dimension, "pattern" -> pattern)
}

case class AllQueryFilter(condition: java.util.HashMap[String, Any]) extends QueryFilter {
  //  val json = JSONObject.fromObject(condition.get("filter")).toString
  //  def toJson: JValue = parse(json)
  def toJson: JValue = fromJsonNode(mapper.valueToTree(condition.get("filter")))
}

object QueryFilter {

  def custom(typeName: String, dimension: String, value: String): ExprQueryFilter =
    ExprQueryFilter(typeName, dimension, value)

  def where(dimension: String, value: String): SelectorQueryFilter =
    SelectorQueryFilter(dimension, value)

  def regex(dimension: String, pattern: String): RegexQueryFilter =
    RegexQueryFilter(dimension, pattern)

  val All = new QueryFilter {
    def toJson: JValue = JNull
  }
} 
Example 4
Source File: ColumnAnnotation.scala    From maha   with Apache License 2.0 5 votes vote down vote up
// Copyright 2017, Yahoo Holdings Inc.
// Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms.
package com.yahoo.maha.core

import org.json4s.JsonAST.{JNull, JObject, JValue}
import org.json4s.scalaz.JsonScalaz._


sealed trait ColumnAnnotation {
  def asJSON: JObject = makeObj(
    List(
      ("annotation" -> toJSON(this.getClass.getSimpleName))
    )
  )
}

sealed trait SingletonColumn

trait ClassNameHashCode {
  override final val hashCode: Int = this.getClass.toString.hashCode
  override def equals(other: Any) : Boolean =  this.hashCode == other.hashCode()
}

sealed trait ColumnAnnotationInstance extends ColumnAnnotation with ClassNameHashCode {
  def instance: ColumnAnnotation
}

case class HiveShardingExpression(expression: HiveDerivedExpression) extends ColumnAnnotationInstance with WithHiveEngine {
  def instance: ColumnAnnotation = HiveShardingExpression.instance

  val jUtils = JsonUtils

  override def asJSON(): JObject =
    makeObj(
      List(
        ("annotation" -> toJSON(this.getClass.getSimpleName))
        ,("expression" -> jUtils.asJSON(expression))
      )
    )
}
case object HiveShardingExpression {
  val instance: ColumnAnnotation = HiveShardingExpression(null)
}

case class PrestoShardingExpression(expression: PrestoDerivedExpression) extends ColumnAnnotationInstance with WithPrestoEngine {
  def instance: ColumnAnnotation = PrestoShardingExpression.instance

  val jUtils = JsonUtils

  override def asJSON(): JObject =
    makeObj(
      List(
        ("annotation" -> toJSON(this.getClass.getSimpleName))
        ,("expression" -> jUtils.asJSON(expression))
      )
    )
}
case object PrestoShardingExpression {
  val instance: ColumnAnnotation = PrestoShardingExpression(null)
}

case object PrimaryKey extends ColumnAnnotation
case object EscapingRequired extends ColumnAnnotation
case object HiveSnapshotTimestamp extends ColumnAnnotation with SingletonColumn with WithHiveEngine
case object OracleSnapshotTimestamp extends ColumnAnnotation with SingletonColumn with WithOracleEngine
case object PostgresSnapshotTimestamp extends ColumnAnnotation with SingletonColumn with WithPostgresEngine
case object IsAggregation extends ColumnAnnotation
case object CaseInsensitive extends ColumnAnnotation
case class ForeignKey(publicDimName: String) extends ColumnAnnotationInstance {
  def instance: ColumnAnnotation = ForeignKey.instance

  override def asJSON(): JObject =
    makeObj(
      List(
        ("annotation" -> toJSON(this.getClass.getSimpleName))
        ,("publicDimName" -> toJSON(publicDimName))
      )
    )
}
case object ForeignKey {
  val instance: ColumnAnnotation = ForeignKey("instance")
}
case class DayColumn(fmt: String) extends ColumnAnnotationInstance {
  def instance: ColumnAnnotation = DayColumn.instance

  override def asJSON(): JObject =
    makeObj(
      List(
        ("annotation" -> toJSON(this.getClass.getSimpleName))
        ,("fmt" -> toJSON(fmt))
      )
    )
}
case object DayColumn {
  val instance: ColumnAnnotation = DayColumn("instance")
} 
Example 5
Source File: SQLInterpreter.scala    From incubator-livy   with Apache License 2.0 5 votes vote down vote up
package org.apache.livy.repl

import java.lang.reflect.InvocationTargetException
import java.sql.Date

import scala.util.control.NonFatal

import org.apache.spark.SparkConf
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
import org.json4s._
import org.json4s.JsonAST.{JNull, JString}
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

import org.apache.livy.Logging
import org.apache.livy.rsc.RSCConf
import org.apache.livy.rsc.driver.SparkEntries


class SQLInterpreter(
    sparkConf: SparkConf,
    rscConf: RSCConf,
    sparkEntries: SparkEntries) extends Interpreter with Logging {

  case object DateSerializer extends CustomSerializer[Date](_ => ( {
    case JString(s) => Date.valueOf(s)
    case JNull => null
  }, {
    case d: Date => JString(d.toString)
  }))

  private implicit def formats: Formats = DefaultFormats + DateSerializer

  private var spark: SparkSession = null

  private val maxResult = rscConf.getInt(RSCConf.Entry.SQL_NUM_ROWS)

  override def kind: String = "sql"

  override def start(): Unit = {
    require(!sparkEntries.sc().sc.isStopped)
    spark = sparkEntries.sparkSession()
  }

  override protected[repl] def execute(code: String): Interpreter.ExecuteResponse = {
    try {
      val result = spark.sql(code)
      val schema = parse(result.schema.json)

      // Get the row data
      val rows = result.take(maxResult)
        .map {
          _.toSeq.map {
            // Convert java BigDecimal type to Scala BigDecimal, because current version of
            // Json4s doesn't support java BigDecimal as a primitive type (LIVY-455).
            case i: java.math.BigDecimal => BigDecimal(i)
            case e => e
          }
        }

      val jRows = Extraction.decompose(rows)

      Interpreter.ExecuteSuccess(
        APPLICATION_JSON -> (("schema" -> schema) ~ ("data" -> jRows)))
    } catch {
      case e: InvocationTargetException =>
        warn(s"Fail to execute query $code", e.getTargetException)
        val cause = e.getTargetException
        Interpreter.ExecuteError("Error", cause.getMessage, cause.getStackTrace.map(_.toString))

      case NonFatal(f) =>
        warn(s"Fail to execute query $code", f)
        Interpreter.ExecuteError("Error", f.getMessage, f.getStackTrace.map(_.toString))
    }
  }

  override def close(): Unit = { }
} 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: SnsNotifier.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.api.notifier.sns

import cats.effect.IO
import com.amazonaws.services.sns.AmazonSNS
import com.amazonaws.services.sns.model.{MessageAttributeValue, PublishRequest}
import org.json4s.JsonAST.JNull
import org.json4s.jackson.JsonMethods._
import org.slf4j.LoggerFactory
import vinyldns.api.route.VinylDNSJsonProtocol
import vinyldns.core.domain.batch.BatchChange
import vinyldns.core.notifier.{Notification, Notifier}

class SnsNotifier(config: SnsNotifierConfig, sns: AmazonSNS)
    extends Notifier
    with VinylDNSJsonProtocol {

  private val logger = LoggerFactory.getLogger(classOf[SnsNotifier])

  def notify(notification: Notification[_]): IO[Unit] =
    notification.change match {
      case bc: BatchChange => sendBatchChangeNotification(bc)
      case _ => IO.unit
    }

  def sendBatchChangeNotification(bc: BatchChange): IO[Unit] =
    IO {
      val message =
        compact(render(BatchChangeSerializer.toJson(bc).replace(List("changes"), JNull)).noNulls)
      logger.info(s"Sending batchChange='${bc.id}'; userName='${bc.userName}'; json='$message'")

      val request = new PublishRequest(config.topicArn, message)
      request.addMessageAttributesEntry(
        "userName",
        new MessageAttributeValue().withDataType("String").withStringValue(bc.userName)
      )
      sns.publish(request)
      logger.info(s"Sending batch change success; batchChange='${bc.id}'")
    }.handleErrorWith { e =>
      IO(logger.error(s"Failed sending batch change; batchChange='${bc.id}'", e))
    }.void
} 
Example 14
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 15
Source File: Machine.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.cluster

import org.json4s.JObject
import org.json4s.JsonAST.{JNull, JNothing}
import org.json4s.JsonDSL._


case class Machine(// The friendly name of the machine, if any
				   alias: Option[String],
				   // The IP address of the machine
				   ip: String,
				   // The port on which the machine can be reached
				   port: Int,
				   // The role of the machine
				   roles: List[String],
				   // The status of the machine
				   status: Option[String]) {
	def toJson(): JObject = {
		("alias" -> alias.orNull) ~
		("ip" -> ip) ~
		("port" -> port) ~
		("roles" -> roles) ~
		("status" -> status)
	}
} 
Example 16
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)
      }))