play.api.libs.json.JsNumber Scala Examples

The following examples show how to use play.api.libs.json.JsNumber. 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: ItemsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.internal.refs.{SchemaRefResolver, SchemaResolutionScope}
import com.eclipsesource.schema.internal.validators.ArrayValidator
import com.eclipsesource.schema.test.JsonSpec
import org.specs2.mutable.Specification
import play.api.libs.json.{JsNumber, Json}

class ItemsSpec extends Specification with JsonSpec {

  "validate draft4" in {
    import Version4._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
    validate("items", "draft4")
  }

  "validate draft7" in {
    import Version7._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version7))
    validate("items", "draft7")
  }

  "validate array with some invalid items" in {
    import Version4._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
    val schema = JsonSource.schemaFromString(
      """{
        |  "type": "array",
        |  "items": {
        |    "minimum": 3
        |  }
        |}""".stripMargin).get

    val instance = Json.arr(2, 3, 4, 1)

    val result = validator.validate(schema, instance)
    result.isError must beTrue
    result.asEither must beLeft.like { case error =>
      error.toJson.value must haveLength(2)
    }
  }

  "validate array with wrong json type" in {
    import Version4._
    val schema = JsonSource.schemaFromString(
      """{
        |  "type": "array",
        |  "items": {
        |    "minimum": 3
        |  }
        |}""".stripMargin).get.asInstanceOf[SchemaArray]
    val context = SchemaResolutionContext(SchemaRefResolver(Version4), SchemaResolutionScope(schema))
    val result = ArrayValidator.validate(schema, JsNumber(2), context)
    result.isFailure must beTrue
  }
} 
Example 2
Source File: JsonFormatsTest.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.collection.Enum
import org.coursera.common.collection.EnumSymbol
import org.coursera.common.stringkey.StringKey
import org.coursera.common.stringkey.StringKeyFormat
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.Duration
import org.joda.time.Instant
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.Format
import play.api.libs.json.JsNumber
import play.api.libs.json.JsString
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json

class JsonFormatsTest extends AssertionsForJUnit {

  import JsonFormatsTest._

  @Test
  def stringKey(): Unit = {
    val id = TestId(2, "test")
    val idString = StringKey.stringify(id)
    assert(JsString(idString) === Json.toJson(id))
    assert(JsSuccess(id) === Json.fromJson[TestId](JsString(idString)))
    assert(JsString(s"invalid stuff $idString").validate[TestId].isError)
  }

  @Test
  def enums(): Unit = {
    assertResult(Color.Amber)(JsString("Amber").as[Color])

    assertResult(JsString("Green"))(Json.toJson(Color.Green))
  }

  @Test
  def instant(): Unit = {
    import JsonFormats.Implicits.instantFormat
    val testInstant = new Instant(137)
    assertResult(JsNumber(137))(Json.toJson(testInstant))
    assertResult(Some(testInstant))(Json.parse("137").asOpt[Instant])
  }


  @Test
  def duration(): Unit = {
    import JsonFormats.Implicits.durationFormat
    val testDuration = Duration.millis(137L)
    assertResult(JsNumber(137))(Json.toJson(testDuration))
    assertResult(Some(testDuration))(Json.parse("137").asOpt[Duration])
  }


  @Test
  def dateTime(): Unit = {
    import JsonFormats.Implicits.dateTimeFormat
    val testDatetime = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC)
    assertResult(JsNumber(1262304000000L))(Json.toJson(testDatetime))
    assertResult(Some(testDatetime))(Json.parse("1262304000000").asOpt[DateTime].map(_.withZone(DateTimeZone.UTC)))
  }
}

object JsonFormatsTest {

  case class TestId(part1: Int, part2: String)

  object TestId {
    implicit val stringKeyFormat: StringKeyFormat[TestId] =
      StringKeyFormat.caseClassFormat((apply _).tupled, unapply)
    implicit val format: Format[TestId] = JsonFormats.stringKeyFormat[TestId]
  }

  sealed trait Color extends EnumSymbol

  object Color extends Enum[Color] {
    case object Red extends Color
    case object Amber extends Color
    case object Green extends Color

    implicit val format: Format[Color] = JsonFormats.enumFormat(Color)
  }

} 
Example 3
Source File: GithubHttpSpecs.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser.github

import org.scalatest.{Matchers, OptionValues, WordSpec}
import play.api.libs.json.{JsNumber, JsObject}
import play.api.libs.ws.{EmptyBody, WSAuthScheme}
import uk.gov.hmrc.ServiceCredentials

class GithubHttpSpecs extends WordSpec with Matchers with OptionValues{

  "GithubHttpSpecs" should {
    "build request holder" in {
      val githubHttp = new GithubHttp(ServiceCredentials("Charles", "123"))

      val body = JsObject(Seq("a" -> JsNumber(1)))
      val call = githubHttp.buildCall("POST", "http://example.com", Some(body))

      call.method shouldBe "POST"
      call.body should not be EmptyBody
      call.url shouldBe "http://example.com"
      call.auth.value shouldBe (("Charles", "123", WSAuthScheme.BASIC))
    }
  }

} 
Example 4
Source File: IssueV2Request.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.transaction.assets.IssueTransaction
import play.api.libs.json.{Format, JsNumber, JsObject, Json}

case class IssueV2Request(
    sender: String,
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long]
)

object IssueV2Request {
  implicit val jsonFormat: Format[IssueV2Request] = Json.format
  implicit class SmartIssueRequestExt(val self: IssueV2Request) extends AnyVal {
    def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(IssueTransaction.typeId.toInt))
  }
} 
Example 5
Source File: SetAssetScriptRequest.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.requests

import com.wavesplatform.transaction.assets.SetAssetScriptTransaction
import play.api.libs.json.{Format, JsNumber, JsObject, Json}

case class SetAssetScriptRequest(
    version: Option[Byte],
    sender: String,
    assetId: String,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long] = None
) {}

object SetAssetScriptRequest {
  implicit val jsonFormat: Format[SetAssetScriptRequest] = Json.format
  implicit class SetAssetScriptRequestExt(val self: SetAssetScriptRequest) extends AnyVal {
    def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(SetAssetScriptTransaction.typeId.toInt))
  }
} 
Example 6
Source File: LeaseApiRoute.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http.leasing

import akka.http.scaladsl.server.Route
import com.wavesplatform.api.common.CommonAccountsApi
import com.wavesplatform.api.http._
import com.wavesplatform.api.http.requests.{LeaseCancelRequest, LeaseRequest}
import com.wavesplatform.http.BroadcastRoute
import com.wavesplatform.network.UtxPoolSynchronizer
import com.wavesplatform.settings.RestAPISettings
import com.wavesplatform.state.Blockchain
import com.wavesplatform.transaction._
import com.wavesplatform.transaction.lease.LeaseTransaction
import com.wavesplatform.utils.Time
import com.wavesplatform.wallet.Wallet
import play.api.libs.json.JsNumber

case class LeaseApiRoute(
    settings: RestAPISettings,
    wallet: Wallet,
    blockchain: Blockchain,
    utxPoolSynchronizer: UtxPoolSynchronizer,
    time: Time,
    commonAccountApi: CommonAccountsApi
) extends ApiRoute
    with BroadcastRoute
    with AuthRoute {

  override val route: Route = pathPrefix("leasing") {
    active ~ deprecatedRoute
  }

  private def deprecatedRoute: Route =
    (path("lease") & withAuth) {
      broadcast[LeaseRequest](TransactionFactory.lease(_, wallet, time))
    } ~ (path("cancel") & withAuth) {
      broadcast[LeaseCancelRequest](TransactionFactory.leaseCancel(_, wallet, time))
    } ~ pathPrefix("broadcast") {
      path("lease")(broadcast[LeaseRequest](_.toTx)) ~
        path("cancel")(broadcast[LeaseCancelRequest](_.toTx))
    }

  def active: Route = (pathPrefix("active") & get & extractScheduler) { implicit sc =>
    path(AddrSegment) { address =>
      complete(
        commonAccountApi
          .activeLeases(address)
          .collect {
            case (height, leaseTransaction: LeaseTransaction) =>
              leaseTransaction.json() + ("height" -> JsNumber(height))
          }
          .toListL
          .runToFuture
      )
    }
  }
} 
Example 7
Source File: SmartTransactionsConstraintsSuite.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.it.async

import com.typesafe.config.Config
import com.wavesplatform.account.KeyPair
import com.wavesplatform.api.http.requests.SignedSetScriptRequest
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.it.api.AsyncHttpApi._
import com.wavesplatform.it.transactions.NodesFromDocker
import com.wavesplatform.it.{NodeConfigs, TransferSending}
import com.wavesplatform.lang.directives.values.V1
import com.wavesplatform.lang.script.v1.ExprScript
import com.wavesplatform.lang.v1.compiler.Terms
import com.wavesplatform.mining.MiningConstraints.MaxScriptRunsInBlock
import com.wavesplatform.transaction.TxVersion
import com.wavesplatform.transaction.smart.SetScriptTransaction
import org.scalatest._
import play.api.libs.json.{JsNumber, Json}

import scala.concurrent.Await.result
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

class SmartTransactionsConstraintsSuite extends FreeSpec with Matchers with TransferSending with NodesFromDocker {

  override protected val nodeConfigs: Seq[Config] = NodeConfigs.newBuilder
    .overrideBase(
      _.raw(
        s"""akka.http.server {
         |  parsing.max-content-length = 3737439
         |  request-timeout = 60s
         |}
         |
         |waves {
         |  miner.quorum = 0
         |
         |  blockchain.custom {
         |    functionality {
         |      pre-activated-features {
         |        2: 0
         |        4: 0
         |        11: 100500
         |      }
         |    }
         |  }
         |}""".stripMargin
      )
    )
    .withDefault(1)
    .build(false)

  private def miner                   = nodes.head
  private val smartPrivateKey  = KeyPair.fromSeed(NodeConfigs.Default(1).getString("account-seed")).explicitGet()
  private val simplePrivateKey = KeyPair.fromSeed(NodeConfigs.Default(2).getString("account-seed")).explicitGet()

  s"Block is limited by size after activation" in result(
    for {
      _ <- miner.signedBroadcast(Json.toJsObject(toRequest(setScriptTx(smartPrivateKey))) + ("type" -> JsNumber(13)))
      _ <- processRequests(generateTransfersFromAccount(MaxScriptRunsInBlock * 3, smartPrivateKey.toAddress.toString))
      _ <- miner.waitForHeight(5)
      _ <- processRequests(generateTransfersFromAccount(MaxScriptRunsInBlock * 3, smartPrivateKey.toAddress.toString))
      _ <- scala.concurrent.Future.sequence((0 to 9).map(_ =>
        processRequests(generateTransfersFromAccount((50 - MaxScriptRunsInBlock / 10), simplePrivateKey.toAddress.toString))))
      _                  <- miner.waitForHeight(6)
      blockWithSetScript <- miner.blockHeadersAt(2)
      restBlocks         <- miner.blockHeadersSeq(3, 4)
      newBlock           <- miner.blockHeadersAt(5)
    } yield {
      blockWithSetScript.transactionCount should (be <= (MaxScriptRunsInBlock + 1) and be >= 1)
      restBlocks.foreach { x =>
        x.transactionCount should be(MaxScriptRunsInBlock)
      }
      newBlock.transactionCount should be > MaxScriptRunsInBlock
    },
    12.minutes
  )

  private def setScriptTx(sender: KeyPair) =
    SetScriptTransaction
      .selfSigned(1.toByte, sender = sender, script = Some(ExprScript(V1, Terms.TRUE, checkSize = false).explicitGet()), fee = 1000000, timestamp = System.currentTimeMillis() - 5.minutes.toMillis)
      .explicitGet()

  private def toRequest(tx: SetScriptTransaction): SignedSetScriptRequest = SignedSetScriptRequest(
    version = Some(TxVersion.V1),
    senderPublicKey = tx.sender.toString,
    script = tx.script.map(_.bytes().base64),
    fee = tx.fee,
    timestamp = tx.timestamp,
    proofs = tx.proofs
  )

} 
Example 8
Source File: JSONBuilder.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.util;

import mimir.algebra.{PrimitiveValue,StringPrimitive,TypePrimitive};
import play.api.libs.json.JsString
import play.api.libs.json.JsArray
import play.api.libs.json.JsObject
import play.api.libs.json.JsValue
import play.api.libs.json.JsNumber
import play.api.libs.json.JsNull
import play.api.libs.json.JsBoolean
import mimir.algebra.NullPrimitive
import mimir.algebra.RowIdPrimitive
import mimir.algebra.IntPrimitive
import mimir.algebra.FloatPrimitive
import mimir.algebra.BoolPrimitive
import mimir.algebra.TimestampPrimitive
import mimir.algebra.DatePrimitive


object JSONBuilder {
	
	def list(content: Seq[Any]): String =
		listJs(content).toString()

  private def listJs(content: Seq[Any]): JsArray =
		JsArray(content.map { el => value(el) })
		
	def dict(content: Map[String,Any]): String =
		dictJs(content).toString()

	def dict(content: Seq[(String,Any)]): String =
		JsObject(content.map( (x) => x._1.toLowerCase() -> value(x._2))).toString()

  private def dictJs(content: Map[String,Any]): JsObject =
		JsObject(content.map { el => el._1 -> value(el._2) } )
		
	def string(content: String): String = {
		value(content).toString()
	}

	def int(content: Int): String = {
		value(content).toString()
	}

	def double(content: Double): String = {
		value(content).toString()
	}
	
	def boolean(content: Boolean): String = {
		value(content).toString()
	}

	def prim(content: PrimitiveValue) = {
		primJs(content).toString()
	}
	
	private def primJs(content: PrimitiveValue) = {
		content match {
			case StringPrimitive(s) => JsString(s)
			case TypePrimitive(t) => JsString(t.toString())
			case NullPrimitive() => JsNull
      case RowIdPrimitive(s) => JsString(s)
      case IntPrimitive(i) => JsNumber(i)
      case FloatPrimitive(f) => JsNumber(f)
      case BoolPrimitive(b) => JsBoolean(b)
      case TimestampPrimitive(_,_,_,_,_,_,_) => JsString(content.asString)
      case DatePrimitive(_,_,_) => JsString(content.asString)
      case _ =>  JsString(content.toString())
		}
	}
	
	private def value(content: Any): JsValue = {
		content match {
		  case s:String => {
		    try {
		      play.api.libs.json.Json.parse(s)
		    } catch {
		      case t: Throwable => JsString(s)
		    }
		  }
			case null => JsNull
      case i:Int => JsNumber(i)
      case f:Float => JsNumber(f)
      case l:Long => JsNumber(l)
      case d:Double => JsNumber(d)
      case b:Boolean => JsBoolean(b)
      case seq:Seq[Any] => listJs(seq)
      case map:Map[_,_] => dictJs(map.asInstanceOf[Map[String,Any]])
      case jsval:JsValue => jsval
      case prim:PrimitiveValue => primJs(prim)
			case _ =>  JsString(content.toString())
		}
	}
} 
Example 9
Source File: SpotifyMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemMedia, DataFeedItemTitle }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsNumber, JsObject, JsResult, JsSuccess, JsValue, __ }

import scala.util.Try

class SpotifyFeedMapper extends DataEndpointMapper {
  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(EndpointQuery("spotify/feed", None,
        dateFilter(fromDate, untilDate).map(f ⇒ Seq(EndpointQueryFilter("played_at", None, f))), None)), Some("played_at"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      durationSeconds ← Try((content \ "track" \ "duration_ms").as[Int] / 1000)
      title ← Try(
        DataFeedItemTitle("You listened", None, Some(s"${"%02d".format(durationSeconds / 60)}:${"%02d".format(durationSeconds % 60)}")))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "track" \ "name").as[String]},
             |${(content \ "track" \ "artists").as[Seq[JsObject]].map(a ⇒ (a \ "name").as[String]).mkString(", ")},
             |${(content \ "track" \ "album" \ "name").as[String]}""".stripMargin),
        None,
        Some(
          Seq(DataFeedItemMedia((content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String], (content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String]))),
        None))
      date ← Try((content \ "played_at").as[DateTime])
    } yield DataFeedItem("spotify", date, Seq(), Some(title), Some(itemContent), None)
  }
}

class SpotifyProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("spotify/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[JsObject]
    eventualData match {
      case JsSuccess(value, _) =>

        val lastPartOfEndpointString = endpoint.split("/").last
        val maybeTransformedData = transformData(value).flatMap(item => item.validate[Map[String, JsValue]])
        maybeTransformedData match {
          case JsSuccess(data, _) =>

            Seq(StaticDataValues(lastPartOfEndpointString, (data - "images" - "external_urls")))
          case e: JsError =>

            logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
            Seq()
        }
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }

  private def transformData(rawData: JsObject): JsResult[JsValue] = {
    val transformation = __.json.update(
      __.read[JsObject].map(profile => {
        val followers = (profile \ "followers" \ "total").asOpt[JsNumber].getOrElse(JsNumber(0))

        profile ++ JsObject(Map(
          "followers" -> followers))
      }))

    rawData.transform(transformation)
  }
} 
Example 10
Source File: P2PRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.common

import java.net.URI

import org.bitcoins.commons.jsonmodels.bitcoind.RpcOpts.{
  AddNodeArgument,
  SetBanCommand
}
import org.bitcoins.commons.jsonmodels.bitcoind._
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.protocol.blockchain.Block
import play.api.libs.json.{JsBoolean, JsNumber, JsString}

import scala.concurrent.Future


trait P2PRpc { self: Client =>

  def addNode(address: URI, command: AddNodeArgument): Future[Unit] = {
    bitcoindCall[Unit](
      "addnode",
      List(JsString(address.getAuthority), JsString(command.toString)))
  }

  def clearBanned(): Future[Unit] = {
    bitcoindCall[Unit]("clearbanned")
  }

  def disconnectNode(address: URI): Future[Unit] = {
    bitcoindCall[Unit]("disconnectnode", List(JsString(address.getAuthority)))
  }

  def getAddedNodeInfo: Future[Vector[Node]] = getAddedNodeInfo(None)

  private def getAddedNodeInfo(node: Option[URI]): Future[Vector[Node]] = {
    val params =
      if (node.isEmpty) {
        List.empty
      } else {
        List(JsString(node.get.getAuthority))
      }
    bitcoindCall[Vector[Node]]("getaddednodeinfo", params)
  }

  def getAddedNodeInfo(node: URI): Future[Vector[Node]] =
    getAddedNodeInfo(Some(node))

  def getConnectionCount: Future[Int] = {
    bitcoindCall[Int]("getconnectioncount")
  }

  def getNetTotals: Future[GetNetTotalsResult] = {
    bitcoindCall[GetNetTotalsResult]("getnettotals")
  }

  def getNetworkInfo: Future[GetNetworkInfoResult] = {
    bitcoindCall[GetNetworkInfoResult]("getnetworkinfo")
  }

  def getPeerInfo: Future[Vector[Peer]] = {
    bitcoindCall[Vector[Peer]]("getpeerinfo")
  }

  def listBanned: Future[Vector[NodeBan]] = {
    bitcoindCall[Vector[NodeBan]]("listbanned")
  }

  def setBan(
      address: URI,
      command: SetBanCommand,
      banTime: Int = 86400,
      absolute: Boolean = false): Future[Unit] = {
    bitcoindCall[Unit]("setban",
                       List(JsString(address.getAuthority),
                            JsString(command.toString),
                            JsNumber(banTime),
                            JsBoolean(absolute)))
  }

  def setNetworkActive(activate: Boolean): Future[Unit] = {
    bitcoindCall[Unit]("setnetworkactive", List(JsBoolean(activate)))
  }

  def submitBlock(block: Block): Future[Unit] = {
    bitcoindCall[Unit]("submitblock", List(JsString(block.hex)))

  }
} 
Example 11
Source File: MultisigRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.common

import org.bitcoins.commons.jsonmodels.bitcoind.MultiSigResult
import org.bitcoins.commons.jsonmodels.bitcoind.RpcOpts.AddressType
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.commons.serializers.JsonWriters._
import org.bitcoins.core.protocol.P2PKHAddress
import org.bitcoins.crypto.ECPublicKey
import play.api.libs.json.{JsArray, JsNumber, JsString, Json}

import scala.concurrent.Future


trait MultisigRpc { self: Client =>

  private def addMultiSigAddress(
      minSignatures: Int,
      keys: Vector[Either[ECPublicKey, P2PKHAddress]],
      account: String = "",
      addressType: Option[AddressType]): Future[MultiSigResult] = {
    def keyToString(key: Either[ECPublicKey, P2PKHAddress]): JsString =
      key match {
        case Right(k) => JsString(k.value)
        case Left(k)  => JsString(k.hex)
      }

    val params =
      List(JsNumber(minSignatures),
           JsArray(keys.map(keyToString)),
           JsString(account)) ++ addressType.map(Json.toJson(_)).toList

    bitcoindCall[MultiSigResult]("addmultisigaddress", params)
  }

  def addMultiSigAddress(
      minSignatures: Int,
      keys: Vector[Either[ECPublicKey, P2PKHAddress]]): Future[MultiSigResult] =
    addMultiSigAddress(minSignatures, keys, addressType = None)

  def addMultiSigAddress(
      minSignatures: Int,
      keys: Vector[Either[ECPublicKey, P2PKHAddress]],
      account: String): Future[MultiSigResult] =
    addMultiSigAddress(minSignatures, keys, account, None)

  def addMultiSigAddress(
      minSignatures: Int,
      keys: Vector[Either[ECPublicKey, P2PKHAddress]],
      addressType: AddressType): Future[MultiSigResult] =
    addMultiSigAddress(minSignatures, keys, addressType = Some(addressType))

  def addMultiSigAddress(
      minSignatures: Int,
      keys: Vector[Either[ECPublicKey, P2PKHAddress]],
      account: String,
      addressType: AddressType): Future[MultiSigResult] =
    addMultiSigAddress(minSignatures, keys, account, Some(addressType))

  def createMultiSig(
      minSignatures: Int,
      keys: Vector[ECPublicKey]): Future[MultiSigResult] = {
    bitcoindCall[MultiSigResult](
      "createmultisig",
      List(JsNumber(minSignatures), Json.toJson(keys.map(_.hex))))
  }

} 
Example 12
Source File: MiningRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.common

import org.bitcoins.commons.jsonmodels.bitcoind.{
  GetBlockTemplateResult,
  GetMiningInfoResult,
  RpcOpts
}
import org.bitcoins.commons.serializers.JsonReaders._
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.currency.Satoshis
import org.bitcoins.core.protocol.BitcoinAddress
import org.bitcoins.crypto.{DoubleSha256Digest, DoubleSha256DigestBE}
import play.api.libs.json.{JsNumber, JsString, Json}

import scala.concurrent.Future


trait MiningRpc { self: Client =>

  @deprecated("use generateToAddress instead", since = "0.18.0")
  def generate(
      blocks: Int,
      maxTries: Int = 1000000): Future[Vector[DoubleSha256DigestBE]] = {
    bitcoindCall[Vector[DoubleSha256DigestBE]](
      "generate",
      List(JsNumber(blocks), JsNumber(maxTries)))
  }

  def generateToAddress(
      blocks: Int,
      address: BitcoinAddress,
      maxTries: Int = 1000000): Future[Vector[DoubleSha256DigestBE]] = {
    bitcoindCall[Vector[DoubleSha256DigestBE]](
      "generatetoaddress",
      List(JsNumber(blocks), JsString(address.toString), JsNumber(maxTries)))
  }

  def getBlockTemplate(request: Option[RpcOpts.BlockTemplateRequest] =
    None): Future[GetBlockTemplateResult] = {
    val params =
      if (request.isEmpty) {
        List.empty
      } else {
        List(Json.toJson(request.get))
      }
    bitcoindCall[GetBlockTemplateResult]("getblocktemplate", params)
  }

  def getNetworkHashPS(
      blocks: Int = 120,
      height: Int = -1): Future[BigDecimal] = {
    bitcoindCall[BigDecimal]("getnetworkhashps",
                             List(JsNumber(blocks), JsNumber(height)))
  }

  def getMiningInfo: Future[GetMiningInfoResult] = {
    bitcoindCall[GetMiningInfoResult]("getmininginfo")
  }

  def prioritiseTransaction(
      txid: DoubleSha256DigestBE,
      feeDelta: Satoshis): Future[Boolean] = {
    bitcoindCall[Boolean](
      "prioritisetransaction",
      List(JsString(txid.hex), JsNumber(0), JsNumber(feeDelta.toLong)))
  }

  def prioritiseTransaction(
      txid: DoubleSha256Digest,
      feeDelta: Satoshis): Future[Boolean] = {
    prioritiseTransaction(txid.flip, feeDelta)
  }
} 
Example 13
Source File: V17LabelRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.v17

import org.bitcoins.commons.jsonmodels.bitcoind.RpcOpts.LabelPurpose
import org.bitcoins.commons.jsonmodels.bitcoind.{LabelResult, ReceivedLabel}
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.currency.Bitcoins
import org.bitcoins.core.protocol.BitcoinAddress
import org.bitcoins.rpc.client.common.Client
import play.api.libs.json.{JsBoolean, JsNumber, JsString}

import scala.concurrent.Future


trait V17LabelRpc { self: Client =>

  def getAddressesByLabel(
      label: String): Future[Map[BitcoinAddress, LabelResult]] = {
    bitcoindCall[Map[BitcoinAddress, LabelResult]]("getaddressesbylabel",
                                                   List(JsString(label)))
  }

  def getReceivedByLabel(
      account: String,
      confirmations: Int = 1): Future[Bitcoins] = {
    bitcoindCall[Bitcoins]("getreceivedbylabel",
                           List(JsString(account), JsNumber(confirmations)))
  }

  def setLabel(address: BitcoinAddress, label: String): Future[Unit] = {
    bitcoindCall[Unit]("setlabel",
                       List(JsString(address.value), JsString(label)))
  }

  def listLabels(
      purpose: Option[LabelPurpose] = None): Future[Vector[String]] = {
    bitcoindCall[Vector[String]]("listlabels",
                                 List(JsString(purpose.getOrElse("").toString)))
  }

  def listReceivedByLabel(
      confirmations: Int = 1,
      includeEmpty: Boolean = false,
      includeWatchOnly: Boolean = false): Future[Vector[ReceivedLabel]] = {
    bitcoindCall[Vector[ReceivedLabel]]("listreceivedbylabel",
                                        List(JsNumber(confirmations),
                                             JsBoolean(includeEmpty),
                                             JsBoolean(includeWatchOnly)))
  }
} 
Example 14
Source File: V16SendRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.v16

import org.bitcoins.commons.serializers.JsonReaders._
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.currency.{Bitcoins, CurrencyUnit}
import org.bitcoins.core.protocol.BitcoinAddress
import org.bitcoins.crypto.DoubleSha256DigestBE
import org.bitcoins.rpc.client.common.Client
import play.api.libs.json.{JsNumber, JsString, Json}

import scala.concurrent.Future


trait V16SendRpc { self: Client =>

  def move(
      fromAccount: String,
      toAccount: String,
      amount: CurrencyUnit,
      comment: String = ""): Future[Boolean] = {
    bitcoindCall[Boolean]("move",
                          List(JsString(fromAccount),
                               JsString(toAccount),
                               Json.toJson(Bitcoins(amount.satoshis)),
                               JsNumber(6),
                               JsString(comment)))
  }

  def sendFrom(
      fromAccount: String,
      toAddress: BitcoinAddress,
      amount: CurrencyUnit,
      confirmations: Int = 1,
      comment: String = "",
      toComment: String = ""): Future[DoubleSha256DigestBE] = {
    bitcoindCall[DoubleSha256DigestBE](
      "sendfrom",
      List(JsString(fromAccount),
           Json.toJson(toAddress),
           Json.toJson(Bitcoins(amount.satoshis)),
           JsNumber(confirmations),
           JsString(comment),
           JsString(toComment))
    )
  }
} 
Example 15
Source File: V16AccountRpc.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.rpc.client.v16

import org.bitcoins.commons.jsonmodels.bitcoind.ReceivedAccount
import org.bitcoins.commons.serializers.JsonReaders._
import org.bitcoins.commons.serializers.JsonSerializers._
import org.bitcoins.core.currency.Bitcoins
import org.bitcoins.core.protocol.BitcoinAddress
import org.bitcoins.rpc.client.common.Client
import play.api.libs.json.{JsBoolean, JsNumber, JsString}

import scala.concurrent.Future


trait V16AccountRpc { self: Client =>

  def getAccountAddress(account: String): Future[BitcoinAddress] = {
    bitcoindCall[BitcoinAddress]("getaccountaddress", List(JsString(account)))
  }

  def getReceivedByAccount(
      account: String,
      confirmations: Int = 1): Future[Bitcoins] = {
    bitcoindCall[Bitcoins]("getreceivedbyaccount",
                           List(JsString(account), JsNumber(confirmations)))
  }

  def getAccount(address: BitcoinAddress): Future[String] = {
    bitcoindCall[String]("getaccount", List(JsString(address.value)))
  }

  def getAddressesByAccount(account: String): Future[Vector[BitcoinAddress]] = {
    bitcoindCall[Vector[BitcoinAddress]]("getaddressesbyaccount",
                                         List(JsString(account)))
  }

  def listAccounts(
      confirmations: Int = 1,
      includeWatchOnly: Boolean = false): Future[Map[String, Bitcoins]] = {
    bitcoindCall[Map[String, Bitcoins]](
      "listaccounts",
      List(JsNumber(confirmations), JsBoolean(includeWatchOnly)))
  }

  def setAccount(address: BitcoinAddress, account: String): Future[Unit] = {
    bitcoindCall[Unit]("setaccount",
                       List(JsString(address.value), JsString(account)))
  }

  def listReceivedByAccount(
      confirmations: Int = 1,
      includeEmpty: Boolean = false,
      includeWatchOnly: Boolean = false): Future[Vector[ReceivedAccount]] = {
    bitcoindCall[Vector[ReceivedAccount]]("listreceivedbyaccount",
                                          List(JsNumber(confirmations),
                                               JsBoolean(includeEmpty),
                                               JsBoolean(includeWatchOnly)))
  }
} 
Example 16
Source File: BigNumSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.Version4
import com.eclipsesource.schema.test.JsonSpec
import org.specs2.mutable.Specification
import play.api.libs.json.JsNumber

class BigNumSpec extends Specification with JsonSpec {

  import Version4._
  implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
  validate("optional/bignum", "draft4")

  "Bignum" should {

    "be an integer" in {
      val schema = JsonSource.schemaFromString(""" {"type": "integer"} """).get
      val instance = JsNumber(BigDecimal("12345678910111213141516171819202122232425262728293031"))
      val result = SchemaValidator(Some(Version4)).validate(schema)(instance)
      result.asOpt must beSome.which(_ == JsNumber(BigDecimal("12345678910111213141516171819202122232425262728293031")))
    }

  }
} 
Example 17
Source File: OrderingUtilBenchmarkSpec.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.core.benchmark

import org.apache.s2graph.core.OrderingUtil._
import org.apache.s2graph.core.{OrderingUtil, SeqMultiOrdering}
import play.api.libs.json.{JsNumber, JsValue}

import scala.util.Random

class OrderingUtilBenchmarkSpec extends BenchmarkCommon {
  "OrderingUtilBenchmarkSpec" should {

    "performance MultiOrdering any" >> {
      val tupLs = (0 until 10) map { i =>
        Random.nextDouble() -> Random.nextLong()
      }

      val seqLs = tupLs.map { tup =>
        Seq(tup._1, tup._2)
      }

      val sorted1 = duration("TupleOrdering double,long") {
        (0 until 1000) foreach { _ =>
          tupLs.sortBy { case (x, y) =>
            -x -> -y
          }
        }
        tupLs.sortBy { case (x, y) =>
          -x -> -y
        }
      }.map { x => x._1 }

      val sorted2 = duration("MultiOrdering double,long") {
        (0 until 1000) foreach { _ =>
          seqLs.sorted(new SeqMultiOrdering[Any](Seq(false, false)))
        }
        seqLs.sorted(new SeqMultiOrdering[Any](Seq(false, false)))
      }.map { x => x.head }

      sorted1.toString() must_== sorted2.toString()
    }

    "performance MultiOrdering double" >> {
      val tupLs = (0 until 50) map { i =>
        Random.nextDouble() -> Random.nextDouble()
      }

      val seqLs = tupLs.map { tup =>
        Seq(tup._1, tup._2)
      }

      duration("MultiOrdering double") {
        (0 until 1000) foreach { _ =>
          seqLs.sorted(new SeqMultiOrdering[Double](Seq(false, false)))
        }
      }

      duration("TupleOrdering double") {
        (0 until 1000) foreach { _ =>
          tupLs.sortBy { case (x, y) =>
            -x -> -y
          }
        }
      }

      1 must_== 1
    }

    "performance MultiOrdering jsvalue" >> {
      val tupLs = (0 until 50) map { i =>
        Random.nextDouble() -> Random.nextLong()
      }

      val seqLs = tupLs.map { tup =>
        Seq(JsNumber(tup._1), JsNumber(tup._2))
      }

      val sorted1 = duration("TupleOrdering double,long") {
        (0 until 1000) foreach { _ =>
          tupLs.sortBy { case (x, y) =>
            -x -> -y
          }
        }
        tupLs.sortBy { case (x, y) =>
          -x -> -y
        }
      }

      val sorted2 = duration("MultiOrdering jsvalue") {
        (0 until 1000) foreach { _ =>
          seqLs.sorted(new SeqMultiOrdering[JsValue](Seq(false, false)))
        }
        seqLs.sorted(new SeqMultiOrdering[JsValue](Seq(false, false)))
      }

      1 must_== 1
    }
  }
} 
Example 18
Source File: ResolveStringConstraintsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.refs

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.{JsonSource, SchemaType, SchemaValue}
import org.specs2.mutable.Specification
import play.api.libs.json.{JsNumber, JsString}

class ResolveStringConstraintsSpec extends Specification {

  "draft v4" should {

    import Version4._
    val resolver = SchemaRefResolver(Version4)

    "resolve string constraints" in {
      val schema =
        JsonSource.schemaFromString(
          """{
            |  "type": "string",
            |  "minLength": 1,
            |  "maxLength": 10,
            |  "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
            |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minLength", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(1)))
      resolver.resolveFromRoot("#/maxLength", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(10)))
      resolver.resolveFromRoot("#/pattern", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsString("^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$")))
    }
  }

  "draft v7" should {

    import Version7._
    val resolver = SchemaRefResolver(Version7)

    "resolve string constraints" in {
      val schema =
        JsonSource.schemaFromString(
          """{
            |  "type": "string",
            |  "minLength": 1,
            |  "maxLength": 10,
            |  "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
            |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minLength", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(1)))
      resolver.resolveFromRoot("#/maxLength", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(10)))
      resolver.resolveFromRoot("#/pattern", scope)
        .map(_.resolved) must beRight[SchemaType](SchemaValue(JsString("^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$")))
    }
  }
} 
Example 19
Source File: ResolveArrayConstraintsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.refs

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.internal.constraints.Constraints.Minimum
import com.eclipsesource.schema.internal.draft7.constraints.NumberConstraints7
import com.eclipsesource.schema.{JsonSource, SchemaNumber, SchemaType, SchemaValue}
import org.specs2.mutable.Specification
import play.api.libs.json.{JsBoolean, JsNumber}

class ResolveArrayConstraintsSpec extends Specification {

  "draft v4" should {

    import Version4._
    val resolver = SchemaRefResolver(Version4)

    "resolve array constraints" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "items": {
          |    "type": "integer"
          |  },
          |  "minItems": 42,
          |  "maxItems": 99,
          |  "additionalItems": false,
          |  "uniqueItems": false
          |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(42)))
      resolver.resolveFromRoot("#/maxItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(99)))
      resolver.resolveFromRoot("#/additionalItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsBoolean(false)))
      resolver.resolveFromRoot("#/uniqueItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsBoolean(false)))
    }
  }

  "draft v7" should {

    import Version7._
    val resolver = SchemaRefResolver(Version7)

    "resolve array constraints" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "items": {
          |    "type": "integer"
          |  },
          |  "minItems": 42,
          |  "maxItems": 99,
          |  "additionalItems": false,
          |  "uniqueItems": false,
          |  "contains": {
          |    "minimum": 55
          |  }
          |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(42)))
      resolver.resolveFromRoot("#/maxItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(99)))
      resolver.resolveFromRoot("#/additionalItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsBoolean(false)))
      resolver.resolveFromRoot("#/uniqueItems", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsBoolean(false)))
      resolver.resolveFromRoot("#/contains", scope).map(_.resolved) must beRight[SchemaType](
        SchemaNumber(NumberConstraints7(Some(Minimum(BigDecimal(55), Some(false)))))
      )
    }
  }
} 
Example 20
Source File: ResolveNumberConstraintsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.refs

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.{JsonSource, SchemaType, SchemaValue}
import org.specs2.mutable.Specification
import play.api.libs.json.JsNumber

class ResolveNumberConstraintsSpec extends Specification {

  "draft v4" should {

    import Version4._
    val resolver = SchemaRefResolver(Version4)

    "resolve number constraints" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "type": "integer",
          |  "minimum": 0,
          |  "maximum": 10,
          |  "multipleOf": 2
          |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minimum", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(0)))
      resolver.resolveFromRoot("#/maximum", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(10)))
      resolver.resolveFromRoot("#/multipleOf", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(2)))
    }
  }

  "draft v7" should {

    import Version7._
    val resolver = SchemaRefResolver(Version7)

    "resolve number constraints" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "type": "integer",
          |  "minimum": 0,
          |  "maximum": 10,
          |  "multipleOf": 2
          |}""".stripMargin).get

      val scope = SchemaResolutionScope(schema)
      resolver.resolveFromRoot("#/minimum", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(0)))
      resolver.resolveFromRoot("#/maximum", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(10)))
      resolver.resolveFromRoot("#/multipleOf", scope).map(_.resolved) must beRight[SchemaType](SchemaValue(JsNumber(2)))
    }
  }
} 
Example 21
Source File: AdditionalItemsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.test.JsonSpec
import org.specs2.mutable.Specification
import play.api.libs.json.{JsArray, JsNumber}

class AdditionalItemsSpec extends Specification with JsonSpec {

  "validate draft4" in {
    import Version4._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
    validate("additionalItems", "draft4")
  }

  "validate draft7" in {
    import Version7._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version7))
    validate("additionalItems", "draft7")
  }

  "AdditionalItems" should {
    import Version7._
    val schema = JsonSource.schemaFromString(
      """{
        |  "items": [{}, {}, {}],
        |  "additionalItems": false
        |}""".stripMargin).get

    "no additional items present" in {
      val data = JsArray(Seq(JsNumber(1), JsNumber(2), JsNumber(3)))
      SchemaValidator(Some(Version4)).validate(schema, data).isSuccess must beTrue
    }
  }
} 
Example 22
Source File: NumberConstraints7.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft7.constraints

import com.eclipsesource.schema.{SchemaInteger, SchemaNumber, SchemaResolutionContext, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.{Keywords, SchemaUtil, ValidatorMessages}
import com.eclipsesource.schema.internal.constraints.Constraints._
import com.eclipsesource.schema.internal.validation.{Rule, VA}
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsString, JsValue}
import scalaz.Success

case class NumberConstraints7(min: Option[Minimum] = None,
                             max: Option[Maximum] = None,
                             multipleOf: Option[BigDecimal] = None,
                             format: Option[String] = None,
                             any: AnyConstraints = AnyConstraints7()
                            ) extends HasAnyConstraint with NumberConstraints {

  import com.eclipsesource.schema.internal.validators.NumberValidators._

  override def subSchemas: Set[SchemaType] = any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.Number.Min => min.map(m => SchemaValue(JsNumber(m.min)))
    case Keywords.Number.Max => max.map(m => SchemaValue(JsNumber(m.max)))
    case Keywords.Number.MultipleOf => multipleOf.map(m => SchemaValue(JsNumber(m)))
    case Keywords.String.Format => format.map(f => SchemaValue(JsString(f)))
    case other => any.resolvePath(other)
  }

  def isInt(implicit lang: Lang): scalaz.Reader[SchemaResolutionContext, Rule[JsValue, JsValue]] =
    scalaz.Reader { context =>
      Rule.fromMapping {
        case json@JsNumber(number) if number.isWhole => Success(json)
        case other =>
          SchemaUtil.failure(
            Keywords.Any.Type,
            ValidatorMessages("err.expected.type", "integer", SchemaUtil.typeOfAsString(other)),
            context.schemaPath,
            context.instancePath,
            other
          )
      }
    }

  override def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
                       (implicit lang: Lang): VA[JsValue] = {

    val reader = for {
      maxRule <- validateMax(max)
      minRule <- validateMin(min)
      multipleOfRule <- validateMultipleOf(multipleOf)
      format <- validateFormat(format)
    } yield maxRule |+| minRule |+| multipleOfRule |+| format

    schema match {
      case SchemaInteger(_) =>
        isInt.flatMap(x => reader.map(y => x |+| y))
          .run(context)
          .repath(_.compose(context.instancePath))
          .validate(json)
      case SchemaNumber(_) =>
        reader
          .run(context)
          .repath(_.compose(context.instancePath))
          .validate(json)
      case _ => Success(json)
    }
  }
} 
Example 23
Source File: ObjectConstraints7.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft7.constraints

import com.eclipsesource.schema.{SchemaMap, SchemaObject, SchemaProp, SchemaResolutionContext, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.Keywords
import com.eclipsesource.schema.internal.constraints.Constraints.{AnyConstraints, Constraint, HasAnyConstraint, ObjectConstraints}
import com.eclipsesource.schema.internal.validation.VA
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsObject, JsValue}
import scalaz.Success
import scalaz.std.option._
import scalaz.std.set._
import scalaz.syntax.semigroup._
import com.eclipsesource.schema.internal._

case class ObjectConstraints7(additionalProps: Option[SchemaType] = None,
                              dependencies: Option[Map[String, SchemaType]] = None,
                              patternProps: Option[Map[String, SchemaType]] = None,
                              required: Option[Seq[String]] = None,
                              minProperties: Option[Int] = None,
                              maxProperties: Option[Int] = None,
                              propertyNames: Option[SchemaType] = None,
                              any: AnyConstraints = AnyConstraints7()
                             ) extends HasAnyConstraint with ObjectConstraints {

  import com.eclipsesource.schema.internal.validators.ObjectValidators._

   override def subSchemas: Set[SchemaType] =
    (additionalProps.map(Set(_)) |+| dependencies.map(_.values.toSet) |+| patternProps.map(_.values.toSet))
      .getOrElse(Set.empty[SchemaType]) ++ any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.Object.AdditionalProperties => additionalProps
    case Keywords.Object.Dependencies => dependencies.map(entries =>
      SchemaMap(Keywords.Object.Dependencies, entries.toSeq.map(e => SchemaProp(e._1, e._2)))
    )
    case Keywords.Object.PatternProperties => patternProps.map(patternProps =>
      SchemaMap(Keywords.Object.PatternProperties, patternProps.toSeq.map(e => SchemaProp(e._1, e._2)))
    )
    case Keywords.Object.MinProperties => minProperties.map(min => SchemaValue(JsNumber(min)))
    case Keywords.Object.MaxProperties => maxProperties.map(max => SchemaValue(JsNumber(max)))
    case "propertyNames" => propertyNames
    case other => any.resolvePath(other)
  }

  override def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
                       (implicit lang: Lang): VA[JsValue] =
    (schema, json) match {
      case (obj@SchemaObject(_, _, _), jsObject@JsObject(_)) =>
        val validation = for {
          _ <- validateDependencies(schema, dependencies, jsObject)
          remaining <- validateProps(obj.properties, required, jsObject)
          unmatched <- validatePatternProps(patternProps, jsObject.fields.toSeq)
          _ <- validateAdditionalProps(additionalProps, unmatched.intersect(remaining), json)
          _ <- validateMinProperties(minProperties, jsObject)
          _ <- validateMaxProperties(maxProperties, jsObject)
          _ <- validatePropertyNames(propertyNames, jsObject)
        } yield schema

        val (_, _, result) = validation.run(context, Success(json))
        result
      case _ => Success(json)
    }
} 
Example 24
Source File: StringConstraints7.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft7.constraints

import com.eclipsesource.schema.{SchemaResolutionContext, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.Keywords
import com.eclipsesource.schema.internal.constraints.Constraints.{AnyConstraints, HasAnyConstraint, StringConstraints}
import com.eclipsesource.schema.internal.validation.VA
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsString, JsValue}

case class StringConstraints7(minLength: Option[Int] = None,
                             maxLength: Option[Int] = None,
                             pattern: Option[String] = None,
                             format: Option[String] = None,
                             any: AnyConstraints = AnyConstraints7()
                            ) extends HasAnyConstraint with StringConstraints {

  import com.eclipsesource.schema.internal.validators.StringValidators._

  override def subSchemas: Set[SchemaType] = any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.String.MinLength => minLength.map(min => SchemaValue(JsNumber(min)))
    case Keywords.String.MaxLength => maxLength.map(max => SchemaValue(JsNumber(max)))
    case Keywords.String.Pattern => pattern.map(p => SchemaValue(JsString(p)))
    case Keywords.String.Format => format.map(f => SchemaValue(JsString(f)))
    case other => any.resolvePath(other)
  }

  def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
              (implicit lang: Lang): VA[JsValue] = {
    val reader = for {
      minLength <- validateMinLength(minLength)
      maxLength <- validateMaxLength(maxLength)
      pattern <- validatePattern(pattern)
      format <- validateFormat(format)
    } yield minLength |+| maxLength |+| pattern |+| format
    reader.run(context)
      .repath(_.compose(context.instancePath))
      .validate(json)
  }
} 
Example 25
Source File: NumberConstraints4.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft4.constraints

import com.eclipsesource.schema.{SchemaInteger, SchemaNumber, SchemaResolutionContext, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.{Keywords, SchemaUtil, ValidatorMessages}
import com.eclipsesource.schema.internal.constraints.Constraints._
import com.eclipsesource.schema.internal.validation.{Rule, VA}
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsString, JsValue}
import scalaz.Success

case class NumberConstraints4(min: Option[Minimum] = None,
                              max: Option[Maximum] = None,
                              multipleOf: Option[BigDecimal] = None,
                              format: Option[String] = None,
                              any: AnyConstraints = AnyConstraints4()
                             ) extends HasAnyConstraint with NumberConstraints {

  import com.eclipsesource.schema.internal.validators.NumberValidators._

  override def subSchemas: Set[SchemaType] = any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.Number.Min => min.map(m => SchemaValue(JsNumber(m.min)))
    case Keywords.Number.Max => max.map(m => SchemaValue(JsNumber(m.max)))
    case Keywords.Number.MultipleOf => multipleOf.map(m => SchemaValue(JsNumber(m)))
    case Keywords.String.Format => format.map(f => SchemaValue(JsString(f)))
    case other => any.resolvePath(other)
  }

  def isInt(implicit lang: Lang): scalaz.Reader[SchemaResolutionContext, Rule[JsValue, JsValue]] =
    scalaz.Reader { context =>
      Rule.fromMapping {
        case json@JsNumber(number) if number.isWhole => Success(json)
        case other =>
          SchemaUtil.failure(
            Keywords.Any.Type,
            ValidatorMessages("err.expected.type", "integer", SchemaUtil.typeOfAsString(other)),
            context.schemaPath,
            context.instancePath,
            other
          )
      }
    }

  override def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
                       (implicit lang: Lang): VA[JsValue] = {

    val reader = for {
      maxRule <- validateMax(max)
      minRule <- validateMin(min)
      multipleOfRule <- validateMultipleOf(multipleOf)
      format <- validateFormat(format)
    } yield maxRule |+| minRule |+| multipleOfRule |+| format

    schema match {
      case SchemaInteger(_) =>
        isInt.flatMap(x => reader.map(y => x |+| y))
          .run(context)
          .repath(_.compose(context.instancePath))
          .validate(json)
      case SchemaNumber(_) =>
        reader
          .run(context)
          .repath(_.compose(context.instancePath))
          .validate(json)
      case _ => Success(json)
    }
  }
} 
Example 26
Source File: ObjectConstraints4.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft4.constraints

import com.eclipsesource.schema.{SchemaMap, SchemaObject, SchemaProp, SchemaResolutionContext, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.constraints.Constraints._
import com.eclipsesource.schema.internal.validation.VA
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsObject, JsValue}
import scalaz.std.option._
import scalaz.std.set._
import scalaz.syntax.semigroup._
import scalaz.Success
import com.eclipsesource.schema.internal._

case class ObjectConstraints4(additionalProps: Option[SchemaType] = None,
                              dependencies: Option[Map[String, SchemaType]] = None,
                              patternProps: Option[Map[String, SchemaType]] = None,
                              required: Option[Seq[String]] = None,
                              minProperties: Option[Int] = None,
                              maxProperties: Option[Int] = None,
                              any: AnyConstraints = AnyConstraints4()
                             ) extends HasAnyConstraint with ObjectConstraints {

  type A = ObjectConstraints4

  import com.eclipsesource.schema.internal.validators.ObjectValidators._

  override def subSchemas: Set[SchemaType] =
    (additionalProps.map(Set(_)) |+| dependencies.map(_.values.toSet) |+| patternProps.map(_.values.toSet))
      .getOrElse(Set.empty[SchemaType]) ++ any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.Object.AdditionalProperties => additionalProps
    case Keywords.Object.Dependencies => dependencies.map(entries =>
      SchemaMap(Keywords.Object.Dependencies, entries.toSeq.map(e => SchemaProp(e._1, e._2)))
    )
    case Keywords.Object.PatternProperties => patternProps.map(patternProps => SchemaMap(
      Keywords.Object.PatternProperties,
      patternProps.toSeq.map(e => SchemaProp(e._1, e._2)))
    )
    case Keywords.Object.MinProperties => minProperties.map(min => SchemaValue(JsNumber(min)))
    case Keywords.Object.MaxProperties => maxProperties.map(max => SchemaValue(JsNumber(max)))
    case other => any.resolvePath(other)
  }

  override def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
                       (implicit lang: Lang): VA[JsValue] =
    (schema, json) match {
      case (obj@SchemaObject(_, _, _), jsObject@JsObject(_)) =>
        val validation = for {
          _ <- validateDependencies(schema, dependencies, jsObject)
          remaining <- validateProps(obj.properties, required, jsObject)
          unmatched <- validatePatternProps(patternProps, jsObject.fields.toSeq)
          _ <- validateAdditionalProps(additionalProps, unmatched.intersect(remaining), json)
          _ <- validateMinProperties(minProperties, jsObject)
          _ <- validateMaxProperties(maxProperties, jsObject)
        } yield schema

        val (_, _, result) = validation.run(context, Success(json))
        result
      case _ => Success(json)
    }
}

object ObjectConstraints4 {
  def emptyObject: SchemaType = SchemaObject(Seq.empty, ObjectConstraints4())
} 
Example 27
Source File: ArrayConstraints4.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft4.constraints

import com.eclipsesource.schema.internal.Keywords
import com.eclipsesource.schema.{SchemaArray, SchemaResolutionContext, SchemaTuple, SchemaType, SchemaValue}
import com.eclipsesource.schema.internal.constraints.Constraints.{AnyConstraints, ArrayConstraints, Constraint}
import com.eclipsesource.schema.internal.validation.VA
import com.eclipsesource.schema.internal.validators.TupleValidators
import com.osinka.i18n.Lang
import play.api.libs.json.{JsBoolean, JsNumber, JsValue}
import scalaz.Success

case class ArrayConstraints4(maxItems: Option[Int] = None,
                             minItems: Option[Int] = None,
                             additionalItems: Option[SchemaType] = None,
                             unique: Option[Boolean] = None,
                             any: AnyConstraints = AnyConstraints4()
                            ) extends ArrayConstraints with Constraint {

  import com.eclipsesource.schema.internal.validators.ArrayConstraintValidators._

  override def subSchemas: Set[SchemaType] =
    additionalItems.map(Set(_)).getOrElse(Set.empty) ++ any.subSchemas

  override def validate(schema: SchemaType, json: JsValue, resolutionContext: SchemaResolutionContext)
                       (implicit lang: Lang): VA[JsValue] = {

    val reader = for {
      minItemsRule <- validateMinItems(minItems)
      maxItemsRule <- validateMaxItems(maxItems)
      uniqueRule <- validateUniqueness(unique)
    } yield {
      minItemsRule |+| maxItemsRule |+| uniqueRule
    }

    schema match {
      case t: SchemaTuple =>
        TupleValidators
          .validateTuple(additionalItems, t)
          .flatMap(x => reader.map(f => f |+| x))
          .run(resolutionContext)
          .repath(_.compose(resolutionContext.instancePath))
          .validate(json)
      case _: SchemaArray =>
        reader.run(resolutionContext)
          .repath(_.compose(resolutionContext.instancePath))
          .validate(json)
      case _ => Success(json)
    }
  }

  def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.Array.MinItems => minItems.map(min => SchemaValue(JsNumber(min)))
    case Keywords.Array.MaxItems => maxItems.map(max => SchemaValue(JsNumber(max)))
    case Keywords.Array.AdditionalItems => additionalItems
    case Keywords.Array.UniqueItems => unique.map(u => SchemaValue(JsBoolean(u)))
    case other => any.resolvePath(other)
  }
} 
Example 28
Source File: StringConstraints4.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.draft4.constraints

import com.eclipsesource.schema.internal.Keywords
import com.eclipsesource.schema.internal.constraints.Constraints.{AnyConstraints, HasAnyConstraint, StringConstraints}
import com.eclipsesource.schema.internal.validation.VA
import com.eclipsesource.schema.{SchemaResolutionContext, SchemaType, SchemaValue}
import com.osinka.i18n.Lang
import play.api.libs.json.{JsNumber, JsString, JsValue}

case class StringConstraints4(minLength: Option[Int] = None,
                              maxLength: Option[Int] = None,
                              pattern: Option[String] = None,
                              format: Option[String] = None,
                              any: AnyConstraints
                             ) extends HasAnyConstraint with StringConstraints {

  import com.eclipsesource.schema.internal.validators.StringValidators._

  override def subSchemas: Set[SchemaType] = any.subSchemas

  override def resolvePath(path: String): Option[SchemaType] = path match {
    case Keywords.String.MinLength => minLength.map(min => SchemaValue(JsNumber(min)))
    case Keywords.String.MaxLength => maxLength.map(max => SchemaValue(JsNumber(max)))
    case Keywords.String.Pattern => pattern.map(p => SchemaValue(JsString(p)))
    case Keywords.String.Format => format.map(f => SchemaValue(JsString(f)))
    case other => any.resolvePath(other)
  }

  def validate(schema: SchemaType, json: JsValue, context: SchemaResolutionContext)
              (implicit lang: Lang): VA[JsValue] = {
    val reader = for {
      minLength <- validateMinLength(minLength)
      maxLength <- validateMaxLength(maxLength)
      pattern <- validatePattern(pattern)
      format <- validateFormat(format)
    } yield minLength |+| maxLength |+| pattern |+| format
    reader.run(context)
      .repath(_.compose(context.instancePath))
      .validate(json)
  }
} 
Example 29
Source File: TlpAttributeFormat.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.models

import play.api.libs.json.{JsNumber, JsValue}

import org.scalactic.{Every, Good, One, Or}

import org.elastic4play.{AttributeError, InvalidFormatAttributeError}
import org.elastic4play.controllers.{InputValue, JsonInputValue, StringInputValue}
import org.elastic4play.models.{Attribute, AttributeDefinition, NumberAttributeFormat}
import org.elastic4play.services.DBLists

object TlpAttributeFormat extends NumberAttributeFormat {

  def isValidValue(value: Long): Boolean = 0 <= value && value <= 3

  override def definition(dblists: DBLists, attribute: Attribute[Long]): Seq[AttributeDefinition] =
    Seq(
      AttributeDefinition(
        attribute.attributeName,
        name,
        attribute.description,
        Seq(JsNumber(0), JsNumber(1), JsNumber(2), JsNumber(3)),
        Seq("white", "green", "amber", "red")
      )
    )

  override def checkJson(subNames: Seq[String], value: JsValue): Or[JsValue, One[InvalidFormatAttributeError]] = value match {
    case JsNumber(v) if subNames.isEmpty && isValidValue(v.toLong) ⇒ Good(value)
    case _                                                         ⇒ formatError(JsonInputValue(value))
  }

  override def fromInputValue(subNames: Seq[String], value: InputValue): Long Or Every[AttributeError] =
    value match {
      case StringInputValue(Seq(v)) if subNames.isEmpty ⇒
        try {
          val longValue = v.toLong
          if (isValidValue(longValue)) Good(longValue)
          else formatError(value)
        } catch {
          case _: Throwable ⇒ formatError(value)
        }
      case JsonInputValue(JsNumber(v)) ⇒ Good(v.longValue)
      case _                           ⇒ formatError(value)
    }
} 
Example 30
Source File: Organization.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.models

import javax.inject.{Inject, Provider, Singleton}

import scala.concurrent.{ExecutionContext, Future}

import play.api.Logger
import play.api.libs.json.{JsNumber, JsObject, JsString, Json}

import org.elastic4play.models.JsonFormat.enumFormat
import org.elastic4play.models.{AttributeDef, BaseEntity, EntityDef, HiveEnumeration, ModelDef, AttributeFormat ⇒ F, AttributeOption ⇒ O}
import org.elastic4play.services.FindSrv

object OrganizationStatus extends Enumeration with HiveEnumeration {
  type Type = Value
  val Active, Locked = Value
  implicit val reads = enumFormat(this)
}

trait OrganizationAttributes { _: AttributeDef ⇒
  val name        = attribute("name", F.stringFmt, "Organization name", O.form)
  val _id         = attribute("_id", F.stringFmt, "Organization name", O.model)
  val description = attribute("description", F.textFmt, "Organization description")
  val status      = attribute("status", F.enumFmt(OrganizationStatus), "Status of the organization", OrganizationStatus.Active)
}

@Singleton
class OrganizationModel @Inject()(
    findSrv: FindSrv,
    userModelProvider: Provider[UserModel],
    workerModelProvider: Provider[WorkerModel],
    implicit val ec: ExecutionContext
) extends ModelDef[OrganizationModel, Organization]("organization", "Organization", "/organization")
    with OrganizationAttributes
    with AuditedModel {

  private lazy val logger      = Logger(getClass)
  lazy val userModel           = userModelProvider.get
  lazy val workerModel         = workerModelProvider.get
  override def removeAttribute = Json.obj("status" → "Locked")

  override def creationHook(parent: Option[BaseEntity], attrs: JsObject): Future[JsObject] =
    Future.successful {
      (attrs \ "name").asOpt[JsString].fold(attrs) { orgName ⇒
        attrs - "name" + ("_id" → orgName)
      }
    }

  private def buildUserStats(organization: Organization): Future[JsObject] = {
    import org.elastic4play.services.QueryDSL._
    findSrv(userModel, "organization" ~= organization.id, groupByField("status", selectCount))
      .map { userStatsJson ⇒
        val (userCount, userStats) = userStatsJson.value.foldLeft((0L, JsObject.empty)) {
          case ((total, s), (key, value)) ⇒
            val count = (value \ "count").as[Long]
            (total + count, s + (key → JsNumber(count)))
        }
        Json.obj("users" → (userStats + ("total" → JsNumber(userCount))))
      }
  }

  private def buildWorkerStats(organization: Organization): Future[JsObject] = {
    import org.elastic4play.services.QueryDSL._
    findSrv(workerModel, withParent(organization), groupByField("status", selectCount))
      .map { workerStatsJson ⇒
        val (workerCount, workerStats) = workerStatsJson.value.foldLeft((0L, JsObject.empty)) {
          case ((total, s), (key, value)) ⇒
            val count = (value \ "count").as[Long]
            (total + count, s + (key → JsNumber(count)))
        }
        Json.obj("workers" → (workerStats + ("total" → JsNumber(workerCount))))
      }
  }

  override def getStats(entity: BaseEntity): Future[JsObject] =
    entity match {
      case organization: Organization ⇒
        for {
          userStats   ← buildUserStats(organization)
          workerStats ← buildWorkerStats(organization)
        } yield userStats ++ workerStats
      case other ⇒
        logger.warn(s"Request caseStats from a non-case entity ?! ${other.getClass}:$other")
        Future.successful(Json.obj())
    }

}

class Organization(model: OrganizationModel, attributes: JsObject)
    extends EntityDef[OrganizationModel, Organization](model, attributes)
    with OrganizationAttributes {
  override def toJson: JsObject = super.toJson + ("name" → JsString(id))
} 
Example 31
Source File: Migration.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.models

import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

import play.api.Logger
import play.api.libs.json.{JsNull, JsNumber, JsString, JsValue, Json}

import org.thp.cortex.services.{OrganizationSrv, UserSrv, WorkerSrv}

import org.elastic4play.controllers.Fields
import org.elastic4play.services.Operation._
import org.elastic4play.services.{DatabaseState, IndexType, MigrationOperations, Operation}
import org.elastic4play.utils.Hasher

@Singleton
class Migration @Inject()(userSrv: UserSrv, organizationSrv: OrganizationSrv, workerSrv: WorkerSrv, implicit val ec: ExecutionContext)
    extends MigrationOperations {

  lazy val logger                                = Logger(getClass)
  def beginMigration(version: Int): Future[Unit] = Future.successful(())

  def endMigration(version: Int): Future[Unit] =
    userSrv.inInitAuthContext { implicit authContext ⇒
      organizationSrv
        .create(Fields(Json.obj("name" → "cortex", "description" → "Default organization", "status" → "Active")))
        .transform(_ ⇒ Success(())) // ignore errors (already exist)
    }

  override def indexType(version: Int): IndexType.Value = if (version > 3) IndexType.indexWithoutMappingTypes else IndexType.indexWithMappingTypes

  val operations: PartialFunction[DatabaseState, Seq[Operation]] = {
    case DatabaseState(1) ⇒
      val hasher = Hasher("MD5")
      Seq(
        // add type to analyzer
        addAttribute("analyzer", "type" → JsString("analyzer")),
        renameAttribute("job", "workerDefinitionId", "analyzerDefinitionId"),
        renameAttribute("job", "workerId", "analyzerId"),
        renameAttribute("job", "workerName", "analyzerName"),
        addAttribute("job", "type"          → JsString(WorkerType.analyzer.toString)),
        addAttribute("report", "operations" → JsString("[]")),
        renameEntity("analyzer", "worker"),
        renameAttribute("worker", "workerDefinitionId", "analyzerDefinitionId"),
        addAttribute("worker", "type" → JsString(WorkerType.analyzer.toString)),
        mapEntity("worker") { worker ⇒
          val id = for {
            organizationId ← (worker \ "_parent").asOpt[String]
            name           ← (worker \ "name").asOpt[String]
            tpe            ← (worker \ "type").asOpt[String]
          } yield hasher.fromString(s"${organizationId}_${name}_$tpe").head.toString
          worker + ("_id" → JsString(id.getOrElse("<null>")))
        },
        renameEntity("analyzerConfig", "workerConfig"),
        addAttribute("workerConfig", "type" → JsString(WorkerType.analyzer.toString))
      )

    case DatabaseState(2) ⇒
      Seq(mapEntity("worker") { worker ⇒
        val definitionId = (worker \ "workerDefinitionId").asOpt[String]
        definitionId
          .flatMap(workerSrv.getDefinition(_).toOption)
          .fold {
            logger.warn(s"no definition found for worker ${definitionId.getOrElse(worker)}. You should probably have to disable and re-enable it")
            worker
          } { definition ⇒
            worker +
              ("version"     → JsString(definition.version)) +
              ("author"      → JsString(definition.author)) +
              ("url"         → JsString(definition.url)) +
              ("license"     → JsString(definition.license)) +
              ("command"     → definition.command.fold[JsValue](JsNull)(c ⇒ JsString(c.toString))) +
              ("dockerImage" → definition.dockerImage.fold[JsValue](JsNull)(JsString.apply)) +
              ("baseConfig"  → definition.baseConfiguration.fold[JsValue](JsNull)(JsString.apply))
          }
      })

    case DatabaseState(3) ⇒
      Seq(
        mapEntity("sequence") { seq ⇒
          val oldId   = (seq \ "_id").as[String]
          val counter = (seq \ "counter").as[JsNumber]
          seq - "counter" - "_routing" +
            ("_id"             → JsString("sequence_" + oldId)) +
            ("sequenceCounter" → counter)
        }
      )
  }
}