• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala JsNumber类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中spray.json.JsNumber的典型用法代码示例。如果您正苦于以下问题:Scala JsNumber类的具体用法?Scala JsNumber怎么用?Scala JsNumber使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了JsNumber类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: SendTweet

//设置package包名称以及导入依赖的类
package main.scala

import scala.collection.mutable.ArrayBuffer

import spray.json.DefaultJsonProtocol
import spray.json.DeserializationException
import spray.json.JsArray
import spray.json.JsNumber
import spray.json.JsObject
import spray.json.JsString
import spray.json.JsValue
import spray.json.JsonFormat
import spray.json.pimpAny

trait JsonFormats extends DefaultJsonProtocol {
  case class SendTweet(userId: Int, time: Long, msg: String)
  case class UserProfile(id: Int, name: String, statusCount: Int, favoritesCount: Int, followersCount: Int, followingCount: Int)
  case class SendMsg(senderId: Int, time: Long, msg: String, recepientId: Int)

  implicit val tweetFormat = jsonFormat3(SendTweet)
  implicit val userProfileFormat = jsonFormat6(UserProfile)
  implicit val reTweetFormat = jsonFormat4(SendMsg)

  implicit object TimelineJsonFormat extends JsonFormat[Project4Server.Tweets] {
    def write(c: Project4Server.Tweets) = JsObject(
      "authorId" -> JsNumber(c.authorId),
      "message" -> JsString(c.message),
      "timeStamp" -> JsString(c.timeStamp.toString),
      "tweetId" -> JsString(c.tweetId),
      "mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
      "hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector))
    def read(value: JsValue) = {
      value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags") match {
        case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags)) =>
          new Project4Server.Tweets(tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
        case _ => throw new DeserializationException("Tweets expected")
      }
    }
  }

  implicit object MessagesJsonFormat extends JsonFormat[Project4Server.Messages] {
    def write(c: Project4Server.Messages) = JsObject(
      "authorId" -> JsNumber(c.authorId),
      "message" -> JsString(c.message),
      "timeStamp" -> JsString(c.timeStamp.toString),
      "tweetId" -> JsString(c.tweetId),
      "mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
      "hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector),
      "recepientId" -> JsNumber(c.recepientId))
    def read(value: JsValue) = {
      value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags", "recepientId") match {
        case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags), JsNumber(recepientId)) =>
          new Project4Server.Messages(recepientId.toInt, tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
        case _ => throw new DeserializationException("Tweets expected")
      }
    }
  }
} 
开发者ID:abhinavrungta,项目名称:MineBitcoin,代码行数:59,代码来源:Formats.scala


示例2: PlotXY

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.component.ppl

import akka.actor.Props
import spray.json.JsNumber
import thinkbayes.extensions.Plotting._

import net.ruippeixotog.scalafbp.component._
import net.ruippeixotog.scalafbp.thinkbayes.Implicits._
import net.ruippeixotog.scalafbp.thinkbayes.PVar

case object PlotXY extends Component {
  val name = "ppl/PlotXY"
  val description = "Plots in a line chart the PMF of a numeric random variable"
  val icon = Some("line-chart")

  val varPort = InPort[PVar[JsNumber]]("var", "The random variable to plot. Must be numeric")
  val titlePort = InPort[String]("title", "The chart title")
  val inPorts = List(varPort, titlePort)

  val varOutPort = OutPort[PVar[JsNumber]]("var", "The input random variable")
  val outPorts = List(varOutPort)

  val instanceProps = Props(new ComponentActor(this) {
    override val terminationPolicy = Nil

    val chart = emptyPlotXY()
    val controls = chart.showControls

    controls.show()
    controls.onHide(Option(context).foreach(_.stop(self)))
    override def postStop() = controls.dispose()

    titlePort.stream.foreach(chart.title = _)

    varPort.stream
      .doOnEach(_.toPmf.mapKeys(_.value).plotXYOn(chart, "var"))
      .pipeTo(varOutPort)
  })
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:40,代码来源:PlotXY.scala


示例3: Mean

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.component.ppl.stat

import akka.actor.Props
import spray.json.JsNumber

import net.ruippeixotog.scalafbp.component._
import net.ruippeixotog.scalafbp.thinkbayes.Implicits._
import net.ruippeixotog.scalafbp.thinkbayes.PVar

case object Mean extends Component {
  val name = "ppl/stat/Mean"
  val description = "Emits the mean of a numeric random variable"
  val icon = None

  val varPort = InPort[PVar[JsNumber]]("var", "The random variable. Must be numeric")
  val inPorts = List(varPort)

  val meanPort = OutPort[Double]("mean", "The mean value")
  val outPorts = List(meanPort)

  val instanceProps = Props(new ComponentActor(this) {
    varPort.stream.map(_.toPmf.mean).pipeTo(meanPort)
  })
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:25,代码来源:Mean.scala


示例4: Status

//设置package包名称以及导入依赖的类
// Copyright (c) Microsoft.All rights reserved.

package com.microsoft.azure.iot.iothub2cassandra.webservice

import java.lang.management.ManagementFactory

import spray.json.{JsNumber, JsObject, JsString, JsValue}

object Status {
  def get: JsValue = {
    val runtimeMXB = ManagementFactory.getRuntimeMXBean
    val osMXB = ManagementFactory.getOperatingSystemMXBean

    val runtime = JsObject(
      "startTime" ? JsNumber(runtimeMXB.getStartTime),
      "uptimeMsecs" ? JsNumber(runtimeMXB.getUptime),
      "name" ? JsString(runtimeMXB.getName),
      "vmName" ? JsString(runtimeMXB.getVmName)
    )

    val os = JsObject(
      "arch" ? JsString(osMXB.getArch),
      "name" ? JsString(osMXB.getName),
      "version" ? JsString(osMXB.getVersion),
      "processors" ? JsNumber(osMXB.getAvailableProcessors),
      "systemLoadAvg" ? JsNumber(osMXB.getSystemLoadAverage)
    )

    JsObject(
      "runtime" ? runtime,
      "os" ? os
    )
  }
} 
开发者ID:Azure,项目名称:toketi-iothub-to-cassandra,代码行数:35,代码来源:Status.scala


示例5: CoordinateFormat

//设置package包名称以及导入依赖的类
package model

import akka.http.scaladsl.unmarshalling.Unmarshaller
import base.CaseObjectSerializationSupport
import mapdomain.graph.Coordinate
import mapdomain.sidewalk.Ramp
import spray.json.{ DefaultJsonProtocol, DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait ModelFormatter extends DefaultJsonProtocol with CaseObjectSerializationSupport {

  implicit object CoordinateFormat extends RootJsonFormat[Coordinate] {
    def write(c: Coordinate) = JsObject(
      "lat" -> JsNumber(c.latitude),
      "lng" -> JsNumber(c.longitude))

    def read(value: JsValue) = value.asJsObject.getFields("lat", "lng") match {
      case Seq(JsNumber(latitude), JsNumber(longitude)) ?
        Coordinate(latitude.toDouble, longitude.toDouble)
      case _ ? throw DeserializationException("Coordinate expected")
    }
  }

  implicit object PathCoordinateFormat extends RootJsonFormat[PathCoordinate] {
    def write(pc: PathCoordinate) =
      if (pc.street.isDefined)
        JsObject(
          "lat" -> JsNumber(pc.coordinate.latitude),
          "lng" -> JsNumber(pc.coordinate.longitude),
          "street" -> JsString(pc.street.get))
      else
        JsObject(
          "lat" -> JsNumber(pc.coordinate.latitude),
          "lng" -> JsNumber(pc.coordinate.longitude))

    def read(value: JsValue) = value.asJsObject.getFields("lat", "lng", "street") match {
      case Seq(JsNumber(latitude), JsNumber(longitude), JsString(street)) ?
        PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble), Some(street))
      case Seq(JsNumber(latitude), JsNumber(longitude)) ?
        PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble))
      case _ ? throw DeserializationException("PathCoordinate expected")
    }
  }

  implicit val EdgeTypeFormat = caseObjectJsonFormat[EdgeType](StreetEdgeType, SidewalkEdgeType, StreetCrossingEdgeType)
  implicit val VertexTypeFormat = caseObjectJsonFormat[VertexType](StreetVertexType, SidewalkVertexType)
  implicit val ReportableElementTypeFormat = caseObjectJsonFormat[ReportableElementType](RAMP, SIDEWALK)
  implicit val RampFormat = jsonFormat4(Ramp.apply)
  implicit val EdgeFormat = jsonFormat4(Edge.apply)
  implicit val VertexFormat = jsonFormat3(Vertex.apply)
  implicit val MapContainerFormat = jsonFormat2(MapContainer.apply)
  implicit val StreetFormat = jsonFormat3(Street.apply)
  implicit val SidewalkFormat = jsonFormat2(Sidewalk.apply)
  implicit val ReportableElementFormat = jsonFormat6(ReportableElement.apply)
  implicit val StopFormat = jsonFormat4(Stop.apply)
  implicit val PublicTransportPathFormat = jsonFormat4(PublicTransportPath)
  implicit val StopCombinationFormat = jsonFormat6(PTCombination.apply)

  implicit val EdgeTypeUnmarshaller = Unmarshaller.strict[String, EdgeType](EdgeTypeFormat.mapping)
} 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:60,代码来源:ModelFormatter.scala


示例6: JSON

//设置package包名称以及导入依赖的类
package falkner.jayson.metrics.io

import java.nio.file.{Files, Path}

import falkner.jayson.metrics._
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue}

import scala.util.{Failure, Success, Try}


object JSON {

  def apply(out: Path, ml: Metrics): Path = apply(out, Seq(ml))

  def apply(out: Path, mls: Seq[Metrics]): Path = Files.write(mkdir(out), JsObject(mls.map(export): _*).prettyPrint.getBytes)

  def export(o: Metrics): (String, JsValue) = (o.namespace, JsObject(export(o.values): _*))

  def export(o: List[Metric]): List[(String, JsValue)] = o.flatMap(_ match {
    case n: Num => noneIfError[JsNumber]((n.name, JsNumber(n.value)))
    case s: Str => noneIfError[JsString]((s.name, JsString(s.value)))
    case b: Bool => noneIfError[JsBoolean]((b.name, JsBoolean(b.value)))
    case n: NumArray => noneIfError[JsArray]((n.name, JsArray(n.values.asInstanceOf[Seq[Int]].map(m => JsNumber(m)).toVector)))
    // flatten out categorical distributions and keep key order
    case cd: CatDist => noneIfError[JsObject](
      (cd.name, JsObject(
        List(("Name", JsString(cd.name)), ("Samples", JsNumber(cd.samples))) ++
          cd.bins.keys.map(k => cd.bins(k) match {
            case s: Short => (k, JsNumber(s))
            case i: Int => (k, JsNumber(i))
            case l: Long => (k, JsNumber(l))
            case f: Float => (k, JsNumber(f))
            case d: Double => (k, JsNumber(d))
          }): _*))
    )
    case d: Metrics => noneIfError[JsObject]((d.name, JsObject(export(d.values): _*)))
  })

  def noneIfError[A](f: => (String, A)): Option[(String, A)] = Try(f) match {
    case Success(s) => Some(s)
    case Failure(t) => None
  }
} 
开发者ID:jfalkner,项目名称:metrics,代码行数:44,代码来源:JSON.scala


示例7: StandardJsonProtocol

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.json

import java.nio.file.{Path, Paths}
import java.time.Instant

import spray.json.{DeserializationException, JsFalse, JsNumber, JsString, JsTrue, JsValue, RootJsonFormat}

object StandardJsonProtocol {
  implicit val instantJson = InstantJsonFormat
  implicit val pathJson = PathJsonFormat
  implicit val anyJson = PathJsonFormat
}

object InstantJsonFormat extends RootJsonFormat[Instant] {
  def write(obj: Instant): JsValue = JsNumber(obj.toEpochMilli)

  def read(json: JsValue): Instant = json match {
    case JsNumber(number) => Instant.ofEpochMilli(number.toLong)
    case _ => throw DeserializationException("JsNumber expected")
  }
}

object PathJsonFormat extends RootJsonFormat[Path] {
  def write(obj: Path): JsValue = JsString(obj.toString)

  def read(json: JsValue): Path = json match {
    case JsString(str) => Paths.get(str)
    case _ => throw DeserializationException("JsString expected")
  }
}

object AnyJsonFormat extends RootJsonFormat[Any] {
  def write(x: Any): JsValue = x match {
    case n: Int => JsNumber(n)
    case n: Long => JsNumber(n)
    case n: Double => JsNumber(n)
    case n: BigDecimal => JsNumber(n)
    case s: String => JsString(s)
    case b: Boolean if b => JsTrue
    case b: Boolean if !b => JsFalse
  }
  
  def read(value: JsValue): Any = value match {
    case JsNumber(n) => n.doubleValue
    case JsString(s) => s
    case JsTrue => true
    case JsFalse => false
  }
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:50,代码来源:StandardJsonProtocol.scala


示例8: SmtpApiJsonProtocol

//设置package包名称以及导入依赖的类
package org.miszkiewicz.model.json

import org.miszkiewicz.model.smtpapi.{SendAt, SendEachAt, SmtpApi}
import spray.json.{DefaultJsonProtocol, JsNumber, JsObject, JsValue, RootJsonFormat, _}

import scala.collection.mutable

object SmtpApiJsonProtocol extends DefaultJsonProtocol {

  import FilterJsonProtocol._
  import SendTimeJsonProtocol._

  implicit object SmtpApiJsonFormat extends RootJsonFormat[SmtpApi] {
    def write(c: SmtpApi) = {
      val fields: mutable.MutableList[JsField] = mutable.MutableList()
      if (c.recipients.nonEmpty) {
        fields += ("to" -> c.recipients.toJson)
      }
      if (c.categories.nonEmpty) {
        fields += ("category" -> c.categories.toJson)
      }
      if (c.uniqueArguments.nonEmpty) {
        fields += ("unique_args" -> c.uniqueArguments.toJson)
      }
      if (c.sections.nonEmpty) {
        fields += ("section" -> c.sections.toJson)
      }
      if (c.substitutions.nonEmpty) {
        fields += ("sub" -> c.substitutions.toJson)
      }
      if (c.filters.nonEmpty) {
        fields += ("filters" -> JsObject(c.filters.map(filter => filter.name -> filter.toJson): _*))
      }
      c.asmGroupId.foreach(asmGroupId => fields += ("asm_group_id" -> JsNumber(asmGroupId)))
      c.scheduled.foreach(scheduled => fields += (scheduled.name -> scheduled.toJson))
      JsObject(fields: _*)
    }

    def read(value: JsValue) = ???
  }

} 
开发者ID:dmiszkiewicz,项目名称:sendgrid-scala,代码行数:43,代码来源:SmtpApiJsonProtocol.scala


示例9: SubmissionStatusJsonFormat

//设置package包名称以及导入依赖的类
package hmda.api.protocol.processing

import hmda.model.fi._
import hmda.api.model.institutions.submissions.{ ContactSummary, FileSummary, RespondentSummary, SubmissionSummary }
import hmda.api.model.{ Receipt, Submissions }
import hmda.api.protocol.validation.ValidationResultProtocol
import spray.json.{ DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait SubmissionProtocol extends ValidationResultProtocol {

  implicit object SubmissionStatusJsonFormat extends RootJsonFormat[SubmissionStatus] {
    override def write(status: SubmissionStatus): JsValue = {
      JsObject(
        "code" -> JsNumber(status.code),
        "message" -> JsString(status.message),
        "description" -> JsString(status.description)
      )
    }

    override def read(json: JsValue): SubmissionStatus = {
      json.asJsObject.getFields("code").head match {
        case JsNumber(s) => s.toInt match {
          case 1 => Created
          case 2 => Uploading
          case 3 => Uploaded
          case 4 => Parsing
          case 5 => ParsedWithErrors
          case 6 => Parsed
          case 7 => Validating
          case 8 => ValidatedWithErrors
          case 9 => Validated
          case 10 => Signed
          case -1 =>
            val message = json.asJsObject.getFields("message").head.toString()
            Failed(message.substring(1, message.length - 1))
          case _ => throw DeserializationException("Submission Status expected")
        }
        case _ => throw DeserializationException("Unable to deserialize")

      }
    }
  }

  implicit val submissionIdProtocol = jsonFormat3(SubmissionId.apply)
  implicit val submissionFormat = jsonFormat5(Submission.apply)
  implicit val submissionsFormat = jsonFormat1(Submissions.apply)
  implicit val receiptFormat = jsonFormat3(Receipt.apply)

  implicit val fileSummaryFormat = jsonFormat3(FileSummary.apply)
  implicit val contactSummaryFormat = jsonFormat3(ContactSummary.apply)
  implicit val respondentSummaryFormat = jsonFormat5(RespondentSummary.apply)
  implicit val submissionSummaryFormat = jsonFormat2(SubmissionSummary.apply)
} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:54,代码来源:SubmissionProtocol.scala


示例10: FilingStatusJsonFormat

//设置package包名称以及导入依赖的类
package hmda.api.protocol.processing

import hmda.api.model.{ FilingDetail, Filings }
import hmda.model.fi._
import spray.json.{ DefaultJsonProtocol, DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait FilingProtocol extends DefaultJsonProtocol with SubmissionProtocol {
  implicit object FilingStatusJsonFormat extends RootJsonFormat[FilingStatus] {
    override def read(json: JsValue): FilingStatus = {
      json.asJsObject.getFields("message").head match {
        case JsString(s) => s match {
          case "not-started" => NotStarted
          case "in-progress" => InProgress
          case "completed" => Completed
          case "cancelled" => Cancelled
        }
        case _ => throw new DeserializationException("Filing Status expected")
      }
    }

    override def write(status: FilingStatus): JsValue = {
      JsObject(
        "code" -> JsNumber(status.code),
        "message" -> JsString(status.message)
      )
    }
  }

  implicit val filingFormat = jsonFormat6(Filing.apply)
  implicit val filingsFormat = jsonFormat1(Filings.apply)
  implicit val filingDetailFormat = jsonFormat2(FilingDetail.apply)
} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:33,代码来源:FilingProtocol.scala


示例11: InMemorySessionHandler

//设置package包名称以及导入依赖的类
package in.lambda_hc.furious_cyclist.rest.controllers.session

import in.lambda_hc.furious_cyclist.utils.SecurityUtils
import org.slf4j.{LoggerFactory, Logger}
import spray.json.{JsNumber, JsObject}


object InMemorySessionHandler extends SessionHandler {
  // String Token Key (userId, Expiration Time)
  val cache: scala.collection.mutable.HashMap[String, (Long, Long)] = scala.collection.mutable.HashMap[String, (Long, Long)]()

  private val LOG: Logger = LoggerFactory.getLogger(this.getClass)

  override def getUserIdForSession(sessionToken: String): Long = {
    LOG.debug("gettingUserFor Session " + sessionToken)
    InMemorySessionHandler.cache.get(sessionToken) match {
      case Some(obj) => obj._1
      case None => 0
    }
  }

  override def createSessionTokenForUser(userId: Long): String = {

    val token = SecurityUtils.generateSHAToken(userId.toString)
    val filteredSessions = InMemorySessionHandler.cache.filter(i => i._2._1 == userId)
    if (filteredSessions.isEmpty) {
      InMemorySessionHandler.cache.put(token, (userId, System.currentTimeMillis()))
    } else {
      filteredSessions.foreach(session => InMemorySessionHandler.cache.remove(session._1))
      InMemorySessionHandler.cache.put(token, (userId, System.currentTimeMillis()))
    }
    LOG.debug("createSessionTokenForUser " + userId + " " + token)
    token
  }

  override def clearAllSessions: Boolean = {
    InMemorySessionHandler.cache.clear()
    true
  }

  override def getAllSessions: JsObject = {
    val response = new JsObject(InMemorySessionHandler.cache.map(i => i._1 -> JsNumber(i._2._1)).toMap)
    println(response)
    response
  }

  override def clearSessionToken(token: String): Unit = {
    InMemorySessionHandler.cache.remove(token)
  }
} 
开发者ID:lambda-hc,项目名称:furious-cyclist,代码行数:51,代码来源:InMemorySessionHandler.scala


示例12: DiagramLabel

//设置package包名称以及导入依赖的类
package org.allenai.dqa.labeling

import scala.io.Source

import spray.json.DefaultJsonProtocol._
import spray.json.JsArray
import spray.json.JsNumber
import spray.json.JsObject
import spray.json.deserializationError
import spray.json.pimpString
import scala.util.Random


case class DiagramLabel(diagramType: String, partLabels: Vector[String])

object Diagram {
  
  def fromJsonFile(filename: String, features: Map[String, DiagramFeatures]
    ): Array[(Diagram, DiagramLabel)] = {
    val lines = Source.fromFile(filename).getLines
    lines.map(fromJsonLine(_, features)).toArray
  }

  def fromJsonLine(line: String, features: Map[String, DiagramFeatures]
    ): (Diagram, DiagramLabel) = {
    val js = line.parseJson.asJsObject
    val diagramLabel = js.fields("label").convertTo[String]
    val diagramId = js.fields("id").convertTo[String]
    val imageId = js.fields("imageId").convertTo[String]
    val width = js.fields("width").convertTo[Int]
    val height = js.fields("height").convertTo[Int]
    
    // val pointJsons = Random.shuffle(js.fields("points").asInstanceOf[JsArray].elements)
    val pointJsons = js.fields("points").asInstanceOf[JsArray].elements

    val labeledParts = for {
      (pointJson, i) <- pointJsons.zipWithIndex
      p = pointJson.asJsObject
      id = p.fields("textId").convertTo[String]
      label = p.fields("label").convertTo[String]
      xy = p.fields("xy") match {
        case JsArray(Vector(JsNumber(x), JsNumber(y))) => Point(x.toInt, y.toInt)
        case _ => deserializationError("Array of x/y coordinates expected")
      }
    } yield {
      (Part(id, i, xy),  label)
    }

    val f = features(imageId)

    (Diagram(diagramId, imageId, width, height, labeledParts.map(_._1), f),
        (DiagramLabel(diagramLabel, labeledParts.map(_._2))))
  }
} 
开发者ID:allenai,项目名称:pnp,代码行数:55,代码来源:Diagram.scala


示例13: CoreErrorMarshaller

//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers

import org.bitcoins.rpc.bitcoincore.CoreError
import spray.json.{DefaultJsonProtocol, JsNumber, JsObject, JsString, JsValue, RootJsonFormat}


object CoreErrorMarshaller extends DefaultJsonProtocol {
  val codeKey = "code"
  val messageKey = "message"
  implicit object CoreErrorFormatter extends RootJsonFormat[CoreError] {

    override def read(value: JsValue): CoreError = {
      val f = value.asJsObject.fields
      val code = f(codeKey).convertTo[Int]
      val message = f(messageKey).convertTo[String]
      CoreError(code,message)
    }

    override def write(error: CoreError): JsValue = {
      val m = Map(
        codeKey -> JsNumber(error.code),
        messageKey -> JsString(error.message)
      )
      JsObject(m)
    }
  }
} 
开发者ID:bitcoin-s,项目名称:bitcoin-s-rpc-client,代码行数:28,代码来源:CoreErrorMarshaller.scala


示例14: UTXOMarshaller

//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers.wallet

import org.bitcoins.core.crypto.DoubleSha256Digest
import org.bitcoins.core.currency.{Bitcoins, CurrencyUnits, Satoshis}
import org.bitcoins.core.number.Int64
import org.bitcoins.core.protocol.BitcoinAddress
import org.bitcoins.core.protocol.script.ScriptPubKey
import org.bitcoins.rpc.bitcoincore.wallet.UTXO
import spray.json.{DefaultJsonProtocol, JsBoolean, JsNumber, JsObject, JsString, JsValue, RootJsonFormat}


object UTXOMarshaller extends DefaultJsonProtocol {

  val txIdKey = "txid"
  val voutKey = "vout"
  val addressKey = "address"
  val scriptPubKeyKey = "scriptPubKey"
  val amountKey = "amount"
  val confirmationsKey = "confirmations"
  val spendableKey = "spendable"
  val solvableKey = "solvable"
  implicit object UTXOFormatter extends RootJsonFormat[UTXO]  {

    override def read(value: JsValue): UTXO = {
      val f = value.asJsObject.fields
      val txId = DoubleSha256Digest(f(txIdKey).convertTo[String])
      val vout = f(voutKey).convertTo[Int]
      val address = BitcoinAddress(f(addressKey).convertTo[String])
      val scriptPubKey = ScriptPubKey(f(scriptPubKeyKey).convertTo[String])
      val amount = Bitcoins(f(amountKey).convertTo[Double])
      val confirmations = f(confirmationsKey).convertTo[Int]
      val spendable = f(spendableKey).convertTo[Boolean]
      val solvable = f(solvableKey).convertTo[Boolean]
      UTXO(txId, vout, address, scriptPubKey, amount, confirmations, spendable, solvable)
    }

    override def write(utxo: UTXO): JsValue = {
      val m: Map[String,JsValue] = Map(
        txIdKey -> JsString(utxo.txId.hex),
        voutKey -> JsNumber(utxo.vout),
        scriptPubKeyKey -> JsString(utxo.scriptPubKey.hex),
        amountKey -> JsNumber(-1),
        confirmationsKey -> JsNumber(utxo.confirmations),
        spendableKey -> JsBoolean(utxo.spendable),
        solvableKey -> JsBoolean(utxo.solvable)
      )
      JsObject(m)
    }
  }
} 
开发者ID:bitcoin-s,项目名称:bitcoin-s-rpc-client,代码行数:51,代码来源:UTXOMarshaller.scala


示例15: FundRawTransactionOptionsMarshaller

//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers.wallet

import org.bitcoins.rpc.bitcoincore.wallet.FundRawTransactionOptions
import spray.json.{DefaultJsonProtocol, JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue, RootJsonFormat}


object FundRawTransactionOptionsMarshaller extends DefaultJsonProtocol {
  val changeAddressKey = "changeAddress"
  val changePositionKey = "changePosition"
  val includeWatchingKey = "includeWatching"
  val lockUnspentKey = "lockUnspent"
  val reserveChangeKeyKey = "reserveChangeKey"
  val feeRateKey = "feeRate"
  val subtractFeeFromOutputsKey = "subtractFeeFromOutputs"

  implicit object FundRawTransactionOptionsFormatter extends RootJsonFormat[FundRawTransactionOptions] {
    override def read(value: JsValue): FundRawTransactionOptions = {
      //TODO: implement
      ???
    }

    override def write(options: FundRawTransactionOptions): JsValue = {
      val withChangeAddress: Map[String,JsValue] = if (options.changeAddress.isDefined) {
        Map(changeAddressKey -> JsString(options.changeAddress.get.value))
      } else Map()

      val withChangePos = if (options.changePosition.isDefined) {
        withChangeAddress.updated(changePositionKey, JsNumber(options.changePosition.get))
      } else withChangeAddress

      val withIncludeWatchingKey = if (options.includeWatching.isDefined) {
        withChangePos.updated(includeWatchingKey,JsBoolean(options.includeWatching.get))
      } else withChangePos

      val withLockUnspent = if (options.lockUnspent.isDefined) {
        withIncludeWatchingKey.updated(lockUnspentKey,JsBoolean(options.lockUnspent.get))
      } else withIncludeWatchingKey

      val withReserveChangeKey = if (options.reserveChangeKey.isDefined) {
        withLockUnspent.updated(reserveChangeKeyKey, JsBoolean(options.reserveChangeKey.get))
      } else withLockUnspent

      val withFeeRate = if (options.feeRate.isDefined) {
        withReserveChangeKey.updated(feeRateKey, JsNumber(options.feeRate.get.underlying))
      } else withReserveChangeKey

      val withSubtractFeeFromOutputs = {
        val arr = JsArray(options.subtractFeeFromOutputs.map(JsNumber(_)).toVector)
        withFeeRate.updated(subtractFeeFromOutputsKey, arr)
      }
      JsObject(withSubtractFeeFromOutputs)
    }
  }
} 
开发者ID:bitcoin-s,项目名称:bitcoin-s-rpc-client,代码行数:55,代码来源:FundRawTransactionOptionsMarshaller.scala


示例16: sendRequest

//设置package包名称以及导入依赖的类
package org.bitcoins.rpc

import akka.http.javadsl.model.headers.HttpCredentials
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import org.bitcoins.rpc.config.DaemonInstance
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue}

import scala.concurrent.Future


sealed trait RPCHandler {

  def sendRequest(instance: DaemonInstance, jsObject: JsObject)(implicit m: ActorMaterializer): Future[HttpResponse] = {
    val username = instance.authCredentials.username
    val password = instance.authCredentials.password
    val req = HttpRequest(method = HttpMethods.POST, uri = instance.rpcUri,
      entity = HttpEntity(ContentTypes.`application/json`,jsObject.toString()))
      .addCredentials(HttpCredentials.createBasicHttpCredentials(username,password))
    sendRequest(req)
  }

  def sendRequest(req: HttpRequest)(implicit m: ActorMaterializer): Future[HttpResponse] = {
    Http(m.system).singleRequest(req)
  }

  def buildRequest(methodName: String, param: Int): JsObject = {
    buildRequest(methodName, JsArray(JsNumber(param)))
  }

  def buildRequest(methodName: String, param: String): JsObject = {
    buildRequest(methodName,JsArray(JsString(param)))
  }

  def buildRequest(methodName: String, param: Boolean): JsObject = {
    buildRequest(methodName, JsArray(JsBoolean(param)))
  }

  def buildRequest(methodName: String, params: JsArray): JsObject = {
    val m : Map[String,JsValue] = Map(
      "method" -> JsString(methodName),
      "params" -> params,
      "id" -> JsString(""))
    JsObject(m)
  }

  def buildRequest(methodName: String): JsObject = {
    buildRequest(methodName,JsArray(Vector()))
  }

  def buildRequest(methodName: String, param1: String, opt: JsObject): JsObject = {
    val arr = JsArray(JsString(param1),opt)
    buildRequest(methodName,arr)
  }
}

object RPCHandler extends RPCHandler 
开发者ID:bitcoin-s,项目名称:bitcoin-s-rpc-client,代码行数:59,代码来源:RPCHandler.scala


示例17: InMemorySessionHandler

//设置package包名称以及导入依赖的类
package com.donoroncall.server.rest.controllers.authentication.session

import com.donoroncall.server.utils.TokenGenerator
import com.google.inject.Inject
import com.typesafe.config.Config
import org.slf4j.{Logger, LoggerFactory}
import spray.json.{JsNumber, JsObject}



object InMemorySessionHandler {
  // String Token Key (userId, Expiration Time)
  val cache: scala.collection.mutable.HashMap[String, (Long, Long)] = scala.collection.mutable.HashMap[String, (Long, Long)]()
}

class InMemorySessionHandler @Inject()(config: Config) extends SessionHandler {
  private val LOG: Logger = LoggerFactory.getLogger(this.getClass)

  override def getUserIdForSession(sessionToken: String): Long = {
    LOG.debug("gettingUserFor Session " + sessionToken)
    val sessions = InMemorySessionHandler.cache.get(sessionToken)
    if (sessions.isEmpty) 0 else sessions.head._1
  }

  override def createSessionTokenForUser(userId: Long): String = {

    val token = TokenGenerator.generateSHAToken(userId.toString)
    val filteredSessions = InMemorySessionHandler.cache.filter(i => i._2._1 == userId)
    if (filteredSessions.isEmpty) {
      InMemorySessionHandler.cache.put(token, (userId, System.currentTimeMillis()))
    } else {
      filteredSessions.foreach(session => InMemorySessionHandler.cache.remove(session._1))
      InMemorySessionHandler.cache.put(token, (userId, System.currentTimeMillis()))
    }
    LOG.debug("createSessionTokenForUser " + userId + " " + token)
    token
  }

  override def clearAllSessions: Boolean = {
    InMemorySessionHandler.cache.clear()
    true
  }

  override def getAllSessions: JsObject = {
    val response = new JsObject(InMemorySessionHandler.cache.map(i => i._1 -> JsNumber(i._2._1)).toMap)
    println(response)
    response
  }

  override def clearSessionToken(token: String): Unit = {
    InMemorySessionHandler.cache.remove(token)
  }
} 
开发者ID:donorcall01,项目名称:DonorOnCall_Server,代码行数:54,代码来源:InMemorySessionHandler.scala


示例18: MyJsonProtocol

//设置package包名称以及导入依赖的类
package com.mpakhomov.json

import java.sql.Timestamp
import java.time.ZoneOffset

import com.mpakhomov.model.Candlestick
import spray.json.{DefaultJsonProtocol, DeserializationException, JsNumber, JsString, JsValue, JsonFormat}

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit object TimestampFormat extends JsonFormat1653282838 {
    def write(obj: Timestamp) = JsString(obj.toLocalDateTime.atZone(ZoneOffset.UTC).toString)

    def read(json: JsValue) = json match {
      case JsNumber(time) => new Timestamp(time.toLong)
      case _ => throw new DeserializationException("Date expected")
    }
  }

  implicit val candlestickFormat = jsonFormat7(Candlestick)
} 
开发者ID:mpakhomov,项目名称:akka-io-demo,代码行数:21,代码来源:MyJsonProtocol.scala



注:本文中的spray.json.JsNumber类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala AppCompatActivity类代码示例发布时间:2022-05-23
下一篇:
Scala SourceMapper类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap