com.fasterxml.jackson.annotation.JsonTypeInfo Scala Examples

The following examples show how to use com.fasterxml.jackson.annotation.JsonTypeInfo. 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: JacksonJsonSerializerTest.scala    From akka-tools   with MIT License 5 votes vote down vote up
package no.nextgentel.oss.akkatools.serializing

import akka.actor.ActorSystem
import akka.serialization.SerializationExtension
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.{SerializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.typesafe.config.{ConfigFactory, Config}
import org.scalatest.{Matchers, FunSuite}

class JacksonJsonSerializerTest extends FunSuite with Matchers {

  val objectMapper = new ObjectMapper()
  objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
  objectMapper.registerModule(new DefaultScalaModule)

  test("serializer") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    val serializer = new JacksonJsonSerializer()
    val a = Animal("our cat", 12, Cat("black", true))
    val bytes = serializer.toBinary(a)
    val ar = serializer.fromBinary(bytes, classOf[Animal]).asInstanceOf[Animal]
    assert( a == ar)
  }

  test("Registering the serializer works") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    val system = ActorSystem("JacksonJsonSerializerTest", ConfigFactory.load("akka-tools-json-serializing.conf"))

    val serialization = SerializationExtension.get(system)
    assert( classOf[JacksonJsonSerializer] ==  serialization.serializerFor(classOf[Animal]).getClass)

    system.terminate()
  }

  test("DepricatedTypeWithMigrationInfo") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    val serializer = new JacksonJsonSerializer()
    val bytes = serializer.toBinary(OldType("12"))
    assert(NewType(12) == serializer.fromBinary(bytes, classOf[OldType]))
  }

  test("verifySerialization - no error") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    JacksonJsonSerializer.setVerifySerialization(true)
    val serializer = new JacksonJsonSerializer()
    val a = Animal("our cat", 12, Cat("black", true))
    val ow = ObjectWrapperWithTypeInfo(a)
    serializer.toBinary(ow)
  }

  test("verifySerialization - with error") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    JacksonJsonSerializer.setVerifySerialization(true)
    val serializer = new JacksonJsonSerializer()
    val a = Animal("our cat", 12, Cat("black", true))
    val ow = ObjectWrapperWithoutTypeInfo(a)
    intercept[JacksonJsonSerializerVerificationFailed] {
      serializer.toBinary(ow)
    }
  }

  test("verifySerialization - disabled") {
    JacksonJsonSerializer.setObjectMapper(objectMapper)
    JacksonJsonSerializer.setVerifySerialization(true)
    val serializer = new JacksonJsonSerializer()
    val a = Animal("our cat", 12, Cat("black", true))
    val ow = ObjectWrapperWithoutTypeInfoOverrided(a)
    serializer.toBinary(ow)
  }



}

case class Animal(name:String, age:Int, t:Cat) extends JacksonJsonSerializable

case class Cat(color:String, tail:Boolean)

case class OldType(s:String) extends DepricatedTypeWithMigrationInfo {
  override def convertToMigratedType(): AnyRef = NewType(s.toInt)
}
case class NewType(i:Int)


case class ObjectWrapperWithTypeInfo(@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@any_class") any:AnyRef)

case class ObjectWrapperWithoutTypeInfo(any:AnyRef)

case class ObjectWrapperWithoutTypeInfoOverrided(any:AnyRef) extends JacksonJsonSerializableButNotDeserializable 
Example 2
Source File: DurableMessage.scala    From akka-tools   with MIT License 5 votes vote down vote up
package no.nextgentel.oss.akkatools.persistence

import akka.actor._
import com.fasterxml.jackson.annotation.JsonTypeInfo
import no.nextgentel.oss.akkatools.serializing.JacksonJsonSerializable

object DurableMessage {
  def apply(deliveryId:Long, payload:AnyRef, sender:String):DurableMessage = DurableMessage(deliveryId, payload, sender, null)
  def apply(deliveryId:Long, payload:AnyRef, sender:ActorPath):DurableMessage = DurableMessage(deliveryId, payload, sender.toString, null)
  def apply(deliveryId:Long, payload:AnyRef, sender:ActorPath, confirmationRoutingInfo:AnyRef):DurableMessage = DurableMessage(deliveryId, payload, sender.toString, confirmationRoutingInfo)
}

case class DurableMessage
(
  deliveryId:Long,
  @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="@payload_class")
  payload:AnyRef,
  sender:String,
  @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@confirmationRoutingInfo_class")
  confirmationRoutingInfo:AnyRef) extends JacksonJsonSerializable {

  def withNewPayload(newPayload:AnyRef):DurableMessage = copy(payload = newPayload)

  def confirm(systemOrContext:ActorRefFactory, confirmingActor:ActorRef):Unit = {
    if (sender != null) {
      systemOrContext.actorSelection(sender).tell(DurableMessageReceived.apply(deliveryId, confirmationRoutingInfo), confirmingActor);
    }
  }

  def payloadAs[T]():T = {
    payload.asInstanceOf[T]
  }

}


/*
Useful when testing receiving of DurableMessages via TestProbe
 */
class DurableMessageForwardAndConfirm(dest:ActorRef, onlyAcceptDurableMessages:Boolean) extends Actor with ActorLogging {

  def receive = {
    case dm:DurableMessage=>
      dest.forward(dm.payload)
      log.debug("durableMessage has been forwarded - confirming it")
      dm.confirm(context, self)
    case x:AnyRef =>
      if (onlyAcceptDurableMessages) {
        log.error("Expecting durableMessage to forward but got this message instead: " + x)
      } else {
        log.debug("Forwarding none-durableMessage")
        dest.forward(x)
      }

  }
}

object DurableMessageForwardAndConfirm {
  def apply(dest:ActorRef, onlyAcceptDurableMessages:Boolean = false)(implicit system:ActorSystem):ActorRef = {
    system.actorOf(Props(new DurableMessageForwardAndConfirm(dest, onlyAcceptDurableMessages)))
  }
} 
Example 3
Source File: DurableMessageReceived.scala    From akka-tools   with MIT License 5 votes vote down vote up
package no.nextgentel.oss.akkatools.persistence

import com.fasterxml.jackson.annotation.JsonTypeInfo
import no.nextgentel.oss.akkatools.serializing.JacksonJsonSerializable

object DurableMessageReceived {
  def apply(deliveryId:Long, confirmationRoutingInfo:AnyRef):DurableMessageReceived = DurableMessageReceived(deliveryId, Option(confirmationRoutingInfo))
}

case class DurableMessageReceived
(
  deliveryId:Long,

  // confirmationRoutingInfo is used as aggregateId when dispatching it to an aggregate using sharding
  @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@confirmationRoutingInfo_class")
  confirmationRoutingInfo:Option[AnyRef]
  ) extends JacksonJsonSerializable 
Example 4
Source File: Site.scala    From scala-serialization   with MIT License 5 votes vote down vote up
package com.komanov.serialization.domain

import java.time.Instant
import java.util.UUID

import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}

import scala.pickling.directSubclasses


case class Domain(name: String,
                  primary: Boolean)


case class MetaTag(name: String,
                   value: String)


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new JsonSubTypes.Type(value = classOf[DomainEntryPoint], name = "DomainEntryPoint"),
  new JsonSubTypes.Type(value = classOf[FreeEntryPoint], name = "FreeEntryPoint")
))
@directSubclasses(Array(
  classOf[DomainEntryPoint],
  classOf[FreeEntryPoint]
))
sealed trait EntryPoint {
  def lookupKey: String

  def primary: Boolean
}

final case class DomainEntryPoint(domain: String, primary: Boolean) extends EntryPoint {
  override def lookupKey: String = domain
}

final case class FreeEntryPoint(userName: String, siteName: String, primary: Boolean) extends EntryPoint {
  override def lookupKey: String = s"$userName.wix.com/$siteName"
}


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new JsonSubTypes.Type(value = classOf[TextComponentData], name = "TextComponentData"),
  new JsonSubTypes.Type(value = classOf[ButtonComponentData], name = "ButtonComponentData"),
  new JsonSubTypes.Type(value = classOf[BlogComponentData], name = "BlogComponentData")
))
@directSubclasses(Array(
  classOf[TextComponentData],
  classOf[ButtonComponentData],
  classOf[BlogComponentData]
))
sealed trait PageComponentData

final case class TextComponentData(text: String) extends PageComponentData

final case class ButtonComponentData(name: String,
                                     text: String,
                                     action: UUID) extends PageComponentData

final case class BlogComponentData(name: String,
                                   rss: Boolean,
                                   tags: Boolean) extends PageComponentData


case class PageComponentPosition(x: Int,
                                 y: Int)

case class PageComponent(id: UUID,
                         componentType: PageComponentType,
                         data: PageComponentData,
                         position: Option[PageComponentPosition],
                         dateCreated: Instant,
                         dateUpdated: Instant)


case class Page(name: String,
                path: String,
                metaTags: Seq[MetaTag],
                components: Seq[PageComponent])


case class Site(id: UUID,
                ownerId: UUID,
                revision: Long,
                siteType: SiteType,
                flags: Seq[SiteFlag],
                name: String,
                description: String,
                domains: Seq[Domain],
                defaultMetaTags: Seq[MetaTag],
                pages: Seq[Page],
                entryPoints: Seq[EntryPoint],
                published: Boolean,
                dateCreated: Instant,
                dateUpdated: Instant) 
Example 5
Source File: CachingEagerEvaluatingDependencyAnalyzer.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.analyze

import java.nio.file.{Files, Path, Paths}
import java.util
import java.util.concurrent.atomic.AtomicInteger

import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.wix.bazel.migrator.model._
import com.wixpress.build.maven.MavenScope
import org.slf4j.LoggerFactory

import scala.collection.JavaConverters._
import scala.collection.parallel.ParMap

//this is needed since currently the transformer isn't thread safe but the dependency analyzer is
class CachingEagerEvaluatingDependencyAnalyzer(sourceModules: Set[SourceModule], dependencyAnalyzer: DependencyAnalyzer, performSourceAnalysis: Boolean) extends DependencyAnalyzer {
  private val log = LoggerFactory.getLogger(getClass)
  private val cachePath = Files.createDirectories(Paths.get("./cache"))
  private val objectMapper = new ObjectMapper()
    .registerModule(DefaultScalaModule)
    .registerModule(new RelativePathSupportingModule)
    .registerModule(new SourceModuleSupportingModule(sourceModules))
    .addMixIn(classOf[Target], classOf[TypeAddingMixin])
    .addMixIn(classOf[CodePurpose], classOf[TypeAddingMixin])
    .addMixIn(classOf[TestType], classOf[TypeAddingMixin])
    .addMixIn(classOf[MavenScope], classOf[TypeAddingMixin])

  private val collectionType = objectMapper.getTypeFactory.constructCollectionType(classOf[util.Collection[Code]], classOf[Code])
  private val clean = performSourceAnalysis

  private def cachePathForSourceModule(m: SourceModule) = {
    cachePath.resolve(m.relativePathFromMonoRepoRoot + ".cache")
  }

  private val size = sourceModules.size
  private val counter = new AtomicInteger()
  private val tenthSize = size / 10

  private def initCachePathForSourceModule(p: Path) = Files.createDirectories(p.getParent)

  private def maybeCodeFromCache(p: Path): Option[List[Code]] = {
    if (clean || !Files.exists(p)) return None
    try {
      val value: util.Collection[Code] = objectMapper.readValue(p.toFile, collectionType)
      val codeList = value.asScala.toList
      Some(codeList)
    } catch {
      case e: Exception =>
        log.warn(s"Error reading $p ,deleting cache file.")
        log.warn(e.getMessage)
        Files.deleteIfExists(p)
        None
    }
  }

  private def retrieveCodeAndCache(m: SourceModule, cachePath: Path): List[Code] = {
    val codeList = dependencyAnalyzer.allCodeForModule(m)
    Files.deleteIfExists(cachePath)
    initCachePathForSourceModule(cachePath)
    Files.createFile(cachePath)
    try {
      objectMapper.writeValue(cachePath.toFile, codeList)
    } catch {
      case e: InterruptedException =>
        log.warn(s"aborting write to file $cachePath")
        Files.deleteIfExists(cachePath)
        throw e
      case e: Exception =>
        log.warn(s"could not write to file $cachePath")
        log.warn(e.getMessage)
    }
    codeList
  }

  private def calculateMapEntryFor(sourceModule: SourceModule) = {
    printProgress()
    val cachePath = cachePathForSourceModule(sourceModule)
    (sourceModule, maybeCodeFromCache(cachePath).getOrElse(retrieveCodeAndCache(sourceModule, cachePath)))
  }

  private def printProgress(): Unit = {
    if (tenthSize > 0) {
      val currentCount = counter.incrementAndGet()
      if (currentCount % tenthSize == 0) {
        log.info(s"DependencyAnalyzer:allCodeForModule:\t ${currentCount / tenthSize * 10}% done")
      }
    }
  }

  private val allCode: ParMap[SourceModule, List[Code]] = sourceModules.par.map(calculateMapEntryFor).toMap

  override def allCodeForModule(module: SourceModule): List[Code] = allCode(module)
}

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "__class")
trait TypeAddingMixin 
Example 6
Source File: ExceptionFormattingDependencyAnalyzer.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.analyze

import com.fasterxml.jackson.annotation.{JsonIgnoreProperties, JsonTypeInfo}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.wix.bazel.migrator.model.SourceModule
import com.wix.bazel.migrator.transform.failures.{AnalyzeException, AnalyzeFailure}

class ExceptionFormattingDependencyAnalyzer(dependencyAnalyzer: DependencyAnalyzer) extends DependencyAnalyzer {
  private val om = new ObjectMapper().registerModule(DefaultScalaModule)
    .addMixIn(classOf[AnalyzeFailure], classOf[AnalyzeFailureMixin])
    .addMixIn(classOf[Throwable], classOf[ThrowableMixin])
    .addMixIn(classOf[SourceModule], classOf[IgnoringMavenDependenciesMixin])

  override def allCodeForModule(module: SourceModule): List[Code] =
    try {
      dependencyAnalyzer.allCodeForModule(module)
    } catch {
      case e: AnalyzeException =>
        val message = om.writerWithDefaultPrettyPrinter().writeValueAsString(e.failure)
        throw new RuntimeException(message +
          """|***Detailed error is in a prettified json which starts above***
          |***Inner most AnalyzeFailure has root cause, look for it***
          |More info at https://github.com/wix-private/bazel-tooling/blob/master/migrator/docs
          |""".stripMargin)
    }
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "__class")
trait AnalyzeFailureMixin

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "__class")
abstract class ThrowableMixin

@JsonIgnoreProperties(Array("dependencies"))
trait IgnoringMavenDependenciesMixin 
Example 7
Source File: PolymorphismOrdering.scala    From mbknor-jackson-jsonSchema   with MIT License 5 votes vote down vote up
package com.kjetland.jackson.jsonSchema.testDataScala

import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new JsonSubTypes.Type(value = classOf[PolymorphismOrderingChild3], name = "PolymorphismOrderingChild3"),
  new JsonSubTypes.Type(value = classOf[PolymorphismOrderingChild1], name = "PolymorphismOrderingChild1"),
  new JsonSubTypes.Type(value = classOf[PolymorphismOrderingChild4], name = "PolymorphismOrderingChild4"),
  new JsonSubTypes.Type(value = classOf[PolymorphismOrderingChild2], name = "PolymorphismOrderingChild2")))
trait PolymorphismOrderingParentScala

case class PolymorphismOrderingChild1() extends PolymorphismOrderingParentScala
case class PolymorphismOrderingChild2() extends PolymorphismOrderingParentScala
case class PolymorphismOrderingChild3() extends PolymorphismOrderingParentScala
case class PolymorphismOrderingChild4() extends PolymorphismOrderingParentScala 
Example 8
Source File: UsingJsonSchemaOptions.scala    From mbknor-jackson-jsonSchema   with MIT License 5 votes vote down vote up
package com.kjetland.jackson.jsonSchema.testDataScala

import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaOptions
import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}


@JsonSchemaOptions( items = Array(
  new JsonSchemaOptions.Item(name = "classOption", value="classOptionValue")))
case class UsingJsonSchemaOptions
(
  @JsonSchemaOptions( items = Array(
    new JsonSchemaOptions.Item(name = "o1", value="v1")))
  propertyUsingOneProperty:String

)


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
new JsonSubTypes.Type(value = classOf[UsingJsonSchemaOptionsChild1], name = "c1"),
new JsonSubTypes.Type(value = classOf[UsingJsonSchemaOptionsChild2], name = "c2")))
trait UsingJsonSchemaOptionsBase


@JsonSchemaOptions( items = Array(
  new JsonSchemaOptions.Item(name = "classOption1", value="classOptionValue1")))
case class UsingJsonSchemaOptionsChild1
(
  @JsonSchemaOptions( items = Array(
    new JsonSchemaOptions.Item(name = "o1", value="v1")))
  propertyUsingOneProperty:String

)

@JsonSchemaOptions( items = Array(
  new JsonSchemaOptions.Item(name = "classOption2", value="classOptionValue2")))
case class UsingJsonSchemaOptionsChild2
(
  @JsonSchemaOptions( items = Array(
    new JsonSchemaOptions.Item(name = "o1", value="v1")))
  propertyUsingOneProperty:String

) 
Example 9
Source File: NestedPolymorphism.scala    From mbknor-jackson-jsonSchema   with MIT License 5 votes vote down vote up
package com.kjetland.jackson.jsonSchema.testDataScala

import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}

case class NestedPolymorphism3(b:String)

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new JsonSubTypes.Type(value = classOf[NestedPolymorphism2_1], name = "NestedPolymorphism2_1"),
  new JsonSubTypes.Type(value = classOf[NestedPolymorphism2_2], name = "NestedPolymorphism2_2")
))
trait NestedPolymorphism2Base

case class NestedPolymorphism2_1(a:String, pojo:Option[NestedPolymorphism3]) extends NestedPolymorphism2Base
case class NestedPolymorphism2_2(a:String, pojo:Option[NestedPolymorphism3]) extends NestedPolymorphism2Base

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new JsonSubTypes.Type(value = classOf[NestedPolymorphism1_1], name = "NestedPolymorphism1_1"),
  new JsonSubTypes.Type(value = classOf[NestedPolymorphism1_2], name = "NestedPolymorphism1_2")
))
trait NestedPolymorphism1Base

case class NestedPolymorphism1_1(a:String, pojo:NestedPolymorphism2Base) extends NestedPolymorphism1Base
case class NestedPolymorphism1_2(a:String, pojo:NestedPolymorphism2Base) extends NestedPolymorphism1Base 
Example 10
Source File: ADT.scala    From jsoniter-scala   with MIT License 5 votes vote down vote up
package com.github.plokhotnyuk.jsoniter_scala.benchmark

import com.avsystem.commons.serialization.flatten
import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
import com.rallyhealth.weepickle.v1.implicits.{discriminator, key}

@discriminator("type")
@flatten("type")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(Array(
  new Type(value = classOf[X], name = "X"),
  new Type(value = classOf[Y], name = "Y"),
  new Type(value = classOf[Z], name = "Z")))
sealed trait ADTBase extends Product with Serializable

@key("X")
case class X(a: Int) extends ADTBase

@key("Y")
case class Y(b: String) extends ADTBase

@key("Z")
case class Z(l: ADTBase, r: ADTBase) extends ADTBase 
Example 11
Source File: GeoJSON.scala    From jsoniter-scala   with MIT License 5 votes vote down vote up
package com.github.plokhotnyuk.jsoniter_scala.benchmark

import com.avsystem.commons.serialization.{flatten, transientDefault}
import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
import com.rallyhealth.weepickle.v1.implicits.{discriminator, dropDefault, key}

import scala.collection.immutable.IndexedSeq

object GeoJSON {
  @discriminator("type")
  @flatten("type")
  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
  @JsonSubTypes(Array(
    new Type(value = classOf[Point], name = "Point"),
    new Type(value = classOf[MultiPoint], name = "MultiPoint"),
    new Type(value = classOf[LineString], name = "LineString"),
    new Type(value = classOf[MultiLineString], name = "MultiLineString"),
    new Type(value = classOf[Polygon], name = "Polygon"),
    new Type(value = classOf[MultiPolygon], name = "MultiPolygon"),
    new Type(value = classOf[GeometryCollection], name = "GeometryCollection")))
  sealed trait Geometry extends Product with Serializable

  @discriminator("type")
  sealed trait SimpleGeometry extends Geometry

  @key("Point")
  case class Point(coordinates: (Double, Double)) extends SimpleGeometry

  @key("MultiPoint")
  case class MultiPoint(coordinates: IndexedSeq[(Double, Double)]) extends SimpleGeometry

  @key("LineString")
  case class LineString(coordinates: IndexedSeq[(Double, Double)]) extends SimpleGeometry

  @key("MultiLineString")
  case class MultiLineString(coordinates: IndexedSeq[IndexedSeq[(Double, Double)]]) extends SimpleGeometry

  @key("Polygon")
  case class Polygon(coordinates: IndexedSeq[IndexedSeq[(Double, Double)]]) extends SimpleGeometry

  @key("MultiPolygon")
  case class MultiPolygon(coordinates: IndexedSeq[IndexedSeq[IndexedSeq[(Double, Double)]]]) extends SimpleGeometry

  @key("GeometryCollection")
  case class GeometryCollection(geometries: IndexedSeq[SimpleGeometry]) extends Geometry

  @discriminator("type")
  @flatten("type")
  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
  @JsonSubTypes(Array(
    new Type(value = classOf[Feature], name = "Feature"),
    new Type(value = classOf[FeatureCollection], name = "FeatureCollection")))
  sealed trait GeoJSON extends Product with Serializable

  @discriminator("type")
  sealed trait SimpleGeoJSON extends GeoJSON

  @key("Feature")
  case class Feature(
    @transientDefault @dropDefault properties: Map[String, String] = Map.empty,
    geometry: Geometry,
    @transientDefault @dropDefault bbox: Option[(Double, Double, Double, Double)] = None) extends SimpleGeoJSON

  @key("FeatureCollection")
  case class FeatureCollection(
    features: IndexedSeq[SimpleGeoJSON],
    @transientDefault @dropDefault bbox: Option[(Double, Double, Double, Double)] = None) extends GeoJSON
} 
Example 12
Source File: StatementParserResult.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.sql.parser

import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
import io.radicalbit.nsdb.common.protocol.NSDbSerializable
import io.radicalbit.nsdb.common.statement.{CommandStatement, SQLStatement}

object StatementParserResult {

  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
  @JsonSubTypes(
    Array(
      new JsonSubTypes.Type(value = classOf[SqlStatementParserSuccess], name = "SqlStatementParserSuccess"),
      new JsonSubTypes.Type(value = classOf[SqlStatementParserFailure], name = "SqlStatementParserFailure")
    ))
  trait SqlStatementParserResult

  case class SqlStatementParserSuccess(queryString: String, statement: SQLStatement)
      extends SqlStatementParserResult
      with NSDbSerializable
  case class SqlStatementParserFailure(queryString: String, error: String)
      extends SqlStatementParserResult
      with NSDbSerializable

  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
  @JsonSubTypes(
    Array(
      new JsonSubTypes.Type(value = classOf[CommandStatementParserSuccess], name = "CommandStatementParserSuccess"),
      new JsonSubTypes.Type(value = classOf[CommandStatementParserFailure], name = "CommandStatementParserFailure")
    ))
  trait CommandStatementParserResult

  case class CommandStatementParserSuccess(inputString: String, statement: CommandStatement)
      extends CommandStatementParserResult
      with NSDbSerializable
  case class CommandStatementParserFailure(inputString: String, error: String)
      extends CommandStatementParserResult
      with NSDbSerializable

} 
Example 13
Source File: ShardOperation.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.actors

import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
import io.radicalbit.nsdb.common.protocol.{Bit, NSDbSerializable}
import io.radicalbit.nsdb.common.statement.DeleteSQLStatement
import io.radicalbit.nsdb.model.{Location, Schema}


  def getCompensation(action: ShardOperation): Option[ShardOperation] = {
    action match {
      case DeleteShardRecordOperation(namespace, location, bit) =>
        Some(WriteShardOperation(namespace, location, bit))
      case DeleteShardQueryOperation(_, _, _, _) =>
        None
      case WriteShardOperation(namespace, location, bit) =>
        Some(DeleteShardRecordOperation(namespace, location, bit))
    }
  }
} 
Example 14
Source File: ProcessDefinition.scala    From sundial   with MIT License 5 votes vote down vote up
package model

import java.util.Date

import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo}
@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include = JsonTypeInfo.As.PROPERTY,
  property = Constants.Type,
  visible = true
)
@JsonSubTypes(
  Array(
    new Type(value = classOf[EmailNotification], name = Constants.Email),
    new Type(value = classOf[PagerdutyNotification], name = Constants.Pagerduty)
  ))
sealed trait Notification {
  def `type`: String
}

case class EmailNotification(name: String, email: String, notifyAction: String)
    extends Notification {
  override val `type` = Constants.Email
}

case class PagerdutyNotification(serviceKey: String,
                                 apiUrl: String,
                                 numConsecutiveFailures: Int)
    extends Notification {
  override val `type` = Constants.Pagerduty
}

case class Team(name: String, email: String, notifyAction: String)

case class ProcessDefinition(name: String,
                             description: Option[String],
                             schedule: Option[ProcessSchedule],
                             overlapAction: ProcessOverlapAction,
                             notifications: Seq[Notification],
                             createdAt: Date,
                             isPaused: Boolean)

object Constants {

  private[model] final val Type = "type"

  private[model] final val Email = "email"

  private[model] final val Pagerduty = "pagerduty"

}