play.api.libs.json.JsBoolean Scala Examples

The following examples show how to use play.api.libs.json.JsBoolean. 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: HttpMarketStatusSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import cats.syntax.option._
import com.wavesplatform.dex.domain.order.OrderType
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{JsBoolean, JsString, Json}

class HttpMarketStatusSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "lastPrice" : 1000,
      |  "lastAmount" : 2000,
      |  "lastSide" : "sell",
      |  "bid" : 2222,
      |  "bidAmount" : 1111,
      |  "ask" : 4444,
      |  "askAmount" : 3333,
      |  "success" : true,
      |  "status" : "SimpleResponse"
      |}""".stripMargin

  private val marketStatus =
    HttpMarketStatus(
      lastPrice = 1000L.some,
      lastAmount = 2000L.some,
      lastSide = OrderType.SELL.some,
      bid = 2222L.some,
      bidAmount = 1111L.some,
      ask = 4444L.some,
      askAmount = 3333L.some
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpMarketStatus] should matchTo(marketStatus)
    }

    "serialization" in {
      val marketStatusJson = Json.toJsObject(marketStatus) + ("success" -> JsBoolean(true)) + ("status" -> JsString("SimpleResponse"))
      Json.prettyPrint(marketStatusJson) should matchTo(json)
    }
  }
} 
Example 2
Source File: User.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.models

import scala.concurrent.Future

import play.api.libs.json.{JsArray, JsBoolean, JsObject, JsString}

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

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

trait UserAttributes { _: AttributeDef ⇒
  val login        = attribute("login", F.userFmt, "Login of the user", O.form)
  val userId       = attribute("_id", F.stringFmt, "User id (login)", O.model)
  val key          = optionalAttribute("key", F.stringFmt, "API key", O.sensitive, O.unaudited)
  val userName     = attribute("name", F.stringFmt, "Full name (Firstname Lastname)")
  val roles        = multiAttribute("roles", RoleAttributeFormat, "Comma separated role list (READ, WRITE and ADMIN)")
  val status       = attribute("status", F.enumFmt(UserStatus), "Status of the user", UserStatus.Ok)
  val password     = optionalAttribute("password", F.stringFmt, "Password", O.sensitive, O.unaudited)
  val avatar       = optionalAttribute("avatar", F.rawFmt, "Base64 representation of user avatar image", O.unaudited)
  val preferences  = attribute("preferences", F.rawFmt, "User preferences", "{}", O.sensitive, O.unaudited)
  val organization = attribute("organization", F.stringFmt, "User organization")
}

class UserModel extends ModelDef[UserModel, User]("user", "User", "/user") with UserAttributes with AuditedModel {

  private def setUserId(attrs: JsObject) = (attrs \ "login").asOpt[JsString].fold(attrs) { login ⇒
    attrs - "login" + ("_id" → login)
  }

  override def creationHook(parent: Option[BaseEntity], attrs: JsObject): Future[JsObject] = Future.successful(setUserId(attrs))
}

class User(model: UserModel, attributes: JsObject) extends EntityDef[UserModel, User](model, attributes) with UserAttributes with EUser {
  override def getUserName = userName()
  override def getRoles    = roles()

  override def toJson: JsObject =
    super.toJson +
      ("roles"       → JsArray(roles().map(r ⇒ JsString(r.name.toLowerCase())))) +
      ("hasKey"      → JsBoolean(key().isDefined)) +
      ("hasPassword" → JsBoolean(password().isDefined))
} 
Example 3
Source File: StatusCtrl.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.controllers

import scala.concurrent.ExecutionContext

import play.api.Configuration
import play.api.http.Status
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.json.{JsBoolean, JsString, Json}
import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents}

import com.sksamuel.elastic4s.http.ElasticDsl
import javax.inject.{Inject, Singleton}
import org.elasticsearch.client.Node
import org.thp.cortex.models.Worker

import org.elastic4play.database.DBIndex
import org.elastic4play.services.AuthSrv
import org.elastic4play.services.auth.MultiAuthSrv

@Singleton
class StatusCtrl @Inject()(
    configuration: Configuration,
    authSrv: AuthSrv,
    dbIndex: DBIndex,
    components: ControllerComponents,
    implicit val ec: ExecutionContext
) extends AbstractController(components)
    with Status {

  private[controllers] def getVersion(c: Class[_]) = Option(c.getPackage.getImplementationVersion).getOrElse("SNAPSHOT")

  def get: Action[AnyContent] = Action {
    Ok(
      Json.obj(
        "versions" → Json.obj(
          "Cortex"               → getVersion(classOf[Worker]),
          "Elastic4Play"         → getVersion(classOf[AuthSrv]),
          "Play"                 → getVersion(classOf[AbstractController]),
          "Elastic4s"            → getVersion(classOf[ElasticDsl]),
          "ElasticSearch client" → getVersion(classOf[Node])
        ),
        "config" → Json.obj(
          "protectDownloadsWith" → configuration.get[String]("datastore.attachment.password"),
          "authType" → (authSrv match {
            case multiAuthSrv: MultiAuthSrv ⇒
              multiAuthSrv.authProviders.map { a ⇒
                JsString(a.name)
              }
            case _ ⇒ JsString(authSrv.name)
          }),
          "capabilities" → authSrv.capabilities.map(c ⇒ JsString(c.toString)),
          "ssoAutoLogin" → JsBoolean(configuration.getOptional[Boolean]("auth.sso.autologin").getOrElse(false))
        )
      )
    )
  }

  def health: Action[AnyContent] = TODO
} 
Example 4
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 5
Source File: SchemaReadsSpec.scala    From play-json-schema-validator   with Apache License 2.0 5 votes vote down vote up
package com.eclipsesource.schema.internal.serialization

import com.eclipsesource.schema._
import com.eclipsesource.schema.{JsonSource, SchemaType, SchemaValue}
import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.internal.draft7.constraints.{AnyConstraints7, NumberConstraints7, StringConstraints7}
import org.specs2.mutable.Specification
import play.api.libs.json.{JsArray, JsBoolean, JsString, Json}

class SchemaReadsSpec extends Specification {


  "Schema Reads for draft 4" should {

    import Version4._

    "not fail with match error (#104)" in {
      val schema = JsonSource.schemaFromString("""
        |{
        |  "someProp": {"type": "sting"}
        |}""".stripMargin)

      schema.isSuccess must beTrue
    }

    "not be able to read boolean schema" in {
      Json.fromJson[SchemaType](JsBoolean(true)).isError must beTrue
    }

    "fail if exclusiveMinimum is not a boolean" in {
      val result = JsonSource.schemaFromString(
        """{ "exclusiveMinimum": 3 }""".stripMargin
      )
      result.asEither must beLeft.like { case error => (error.toJson(0) \ "msgs").get.as[JsArray].value.head ==
        JsString("error.expected.jsboolean")
      }
    }
  }

  "Schema Reads for draft 7" should {

    import Version7._

    "read boolean schema" in {
      val booleanSchema = Json.fromJson[SchemaType](JsBoolean(true)).get
      booleanSchema must beEqualTo(SchemaValue(JsBoolean(true)))
    }

    "read compound type with error" in {
      val schema = JsonSource.schemaFromString("""
                                                 |{
                                                 |  "type": ["number", "string"]
                                                 |}""".stripMargin)

      schema.isSuccess must beTrue
      schema.asOpt must beSome.which(
        _ == CompoundSchemaType(
          Seq(
            SchemaNumber(NumberConstraints7().copy(any = AnyConstraints7().copy(schemaType = Some("number")))),
            SchemaString(StringConstraints7().copy(any = AnyConstraints7().copy(schemaType = Some("string"))))
          )
        )
      )
    }
  }
} 
Example 6
Source File: ResolveObjectConstraintsSpec.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.{JsonSource, SchemaString, SchemaType}
import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.internal.draft7.constraints.StringConstraints7
import org.specs2.mutable.Specification
import play.api.libs.json.{JsBoolean, JsObject, JsString, JsValue}

class ResolveObjectConstraintsSpec extends Specification {

  "draft v4" should {

    import Version4._
    val resolver = SchemaRefResolver(Version4)

    "resolve dependencies constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |"dependencies": {
          |    "a": "b",
          |    "c": ["d", "e"]
          |  }
          |}""".stripMargin).get

      val resolved = resolver.resolveFromRoot("#/dependencies/c/1", SchemaResolutionScope(schema))
      resolved.right.map(_.toJson) must beRight[JsValue](JsString("e"))
    }

    "resolve patternProperties constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "patternProperties": {
          |        "^(/[^/]+)+$": {}
          |  }
          |}""".stripMargin).get
      val result = resolver.resolveFromRoot("#/patternProperties", SchemaResolutionScope(schema))
      result.map(_.toJson).right.get must beAnInstanceOf[JsObject]
    }

    "should resolve additionalProperties constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "additionalProperties": false
          |}""".stripMargin).get

      val result = resolver.resolveFromRoot("#/additionalProperties", SchemaResolutionScope(schema))
      result.map(_.toJson) must beRight[JsValue](JsBoolean(false))
    }
  }

  "draft v7" should {

    import Version7._
    val resolver = SchemaRefResolver(Version7)

    "resolve dependencies constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |"dependencies": {
          |    "a": "b",
          |    "c": ["d", "e"]
          |  }
          |}""".stripMargin).get

      val resolved = resolver.resolveFromRoot("#/dependencies/c/1", SchemaResolutionScope(schema))
      resolved.right.map(_.toJson) must beRight[JsValue](JsString("e"))
    }

    "resolve patternProperties constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "patternProperties": {
          |        "^(/[^/]+)+$": {}
          |  }
          |}""".stripMargin).get
      val result = resolver.resolveFromRoot("#/patternProperties", SchemaResolutionScope(schema))
      result.map(_.toJson).right.get must beAnInstanceOf[JsObject]
    }

    "should resolve additionalProperties constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "additionalProperties": false
          |}""".stripMargin).get

      val result = resolver.resolveFromRoot("#/additionalProperties", SchemaResolutionScope(schema))
      result.map(_.toJson) must beRight[JsValue](JsBoolean(false))
    }

    "should resolve additionalProperties constraint" in {
      val schema = JsonSource.schemaFromString(
        """{
          |  "propertyNames": {"maxLength": 3}
          |}""".stripMargin).get

      val result = resolver.resolveFromRoot("#/propertyNames", SchemaResolutionScope(schema))
      result.map(_.resolved) must beRight[SchemaType](SchemaString(StringConstraints7().copy(maxLength = Some(3))))
    }
  }
} 
Example 7
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 8
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 9
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 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: AboutController.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import javax.inject.Inject

import de.frosner.broccoli.auth.Account
import de.frosner.broccoli.services._
import de.frosner.broccoli.conf
import de.frosner.broccoli.models.AboutInfo.aboutInfoWrites
import jp.t2v.lab.play2.auth.BroccoliSimpleAuthorization
import play.api.Environment
import play.api.cache.CacheApi
import play.api.libs.json.{JsBoolean, JsObject, JsString, Json}
import play.api.mvc.{Action, AnyContent, Controller}

case class AboutController @Inject()(
    aboutInfoService: AboutInfoService,
    override val securityService: SecurityService,
    override val cacheApi: CacheApi,
    override val playEnv: Environment
) extends Controller
    with BroccoliSimpleAuthorization {

  def about = StackAction(parse.empty) { implicit request =>
    Ok(Json.toJson(AboutController.about(aboutInfoService, loggedIn)))
  }

}

object AboutController {

  def about(aboutInfoService: AboutInfoService, loggedIn: Account) =
    aboutInfoService.aboutInfo(loggedIn)

} 
Example 12
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())
		}
	}
}