org.json4s.native.Serialization Scala Examples

The following examples show how to use org.json4s.native.Serialization. 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: ApiCache.scala    From twitter-stream-ml   with GNU General Public License v3.0 5 votes vote down vote up
package com.giorgioinf.twtml.web

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{write,read}
import org.mashupbots.socko.infrastructure.Logger
import scala.io.Source
import scala.tools.nsc.io.File
import scala.util.{Properties,Try}

object ApiCache extends Logger {

  private val backupFile = Properties.tmpDir + "/twtml-web.json"

  private var typeStats = Stats()

  private var typeConfig = Config()

  implicit val formats = Serialization.formats(
    ShortTypeHints(List(classOf[Config], classOf[Stats])))

  private def cacheStats(data:Stats) = {
    log.debug("caching stats")
    typeStats = data
  }

  private def cacheConfig(data:Config) = {
    log.debug("caching config")
    typeConfig = data
    backup
  }

  def config():String = {
    write(typeConfig)
  }

  def stats():String = {
    write(typeStats)
  }

  def cache(json:String) = {
    val data = read[TypeData](json)
    data match {
      case stat:Stats => cacheStats(stat)
      case conf:Config => cacheConfig(conf)
      case _ => log.error("json not recognized: {}", json)
    }
  }

  def restore() = {
    Try(cache(Source.fromFile(backupFile).mkString))
  }

  def backup() = {
    File(backupFile).writeAll(config)
  }
} 
Example 2
Source File: OrderBookSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.specs2.mutable.Specification
import stellar.sdk._
import stellar.sdk.model.op.JsonSnippets
import stellar.sdk.model.{Order, OrderBook, OrderBookDeserializer}

class OrderBookSpec extends Specification with ArbitraryInput with JsonSnippets {

  implicit val formats = Serialization.formats(NoTypeHints) + OrderBookDeserializer

  "order book" should {
    "parse from json" >> prop { ob: OrderBook =>
      val doc =
        s"""
           |{
           |  "bids": [${ob.bids.map(order).mkString(",")}],
           |  "asks": [${ob.asks.map(order).mkString(",")}],
           |  "base": {${asset(ob.selling)}}
           |  "counter": {${asset(ob.buying)}}
           |}
        """.stripMargin

      parse(doc).extract[OrderBook] mustEqual ob
    }
  }

  private def order(o: Order) =
    s"""{
       |  "price_r": {
       |    "n": ${o.price.n},
       |    "d": ${o.price.d}
       |  },
       |  "price": "${o.price.asDecimalString}",
       |  "amount": "${o.quantity / math.pow(10, 7)}"
       |}
     """.stripMargin

} 
Example 3
Source File: OfferResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.specs2.mutable.Specification
import stellar.sdk.model.{Amount, Asset, NonNativeAsset}
import stellar.sdk.ArbitraryInput

class OfferResponseSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + OfferRespDeserializer
  private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneId.of("UTC"))

  "an offer response document" should {
    "parse to an offer response" >> prop { or: OfferResponse =>
      val json =
        s"""
           |{
           |  "_links": {
           |    "self": {
           |      "href": "https://horizon-testnet.stellar.org/offers/101542"
           |    },
           |    "offer_maker": {
           |      "href": "https://horizon-testnet.stellar.org/accounts/GCXYKQF35XWATRB6AWDDV2Y322IFU2ACYYN5M2YB44IBWAIITQ4RYPXK"
           |    }
           |  },
           |  "id": ${or.id},
           |  "paging_token": "101542",
           |  "seller": "${or.seller.accountId}",
           |  "selling": {
           |    ${assetJson(or.selling.asset)}
           |  },
           |  "buying": {
           |    ${assetJson(or.buying)}
           |  },
           |  "amount": "${amountString(or.selling)}",
           |  "price_r": {
           |    "n": ${or.price.n},
           |    "d": ${or.price.d}
           |  },
           |  "price": "3.0300000",
           |  "last_modified_ledger": ${or.lastModifiedLedger},
           |  "last_modified_time": "${formatter.format(or.lastModifiedTime)}"
           |}
           |
        """.stripMargin

      parse(json).extract[OfferResponse] mustEqual or
    }
  }

  def assetJson(asset: Asset) = asset match {
    case nn: NonNativeAsset =>
      s"""
         |"asset_type": "${nn.typeString}",
         |"asset_code": "${nn.code}",
         |"asset_issuer": "${nn.issuer.accountId}"
        """.stripMargin.trim

    case _ => """"asset_type": "native""""
  }

  def amountString(a: Amount): String = "%.7f".formatLocal(Locale.ROOT, a.units / math.pow(10, 7))


} 
Example 4
Source File: TrustLineEffectResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.util.Locale

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.scalacheck.Gen
import org.specs2.mutable.Specification
import stellar.sdk._
import stellar.sdk.model.{Amount, IssuedAmount, NonNativeAsset}

class TrustLineEffectResponseSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + EffectResponseDeserializer

  "a trustline created effect document" should {
    "parse to a trustline created effect" >> prop {
      (id: String, accn: KeyPair, asset: NonNativeAsset, limit: Long) =>
        val json = doc(id, "trustline_created", accn, asset, limit)
        parse(json).extract[EffectResponse] mustEqual EffectTrustLineCreated(id, accn.asPublicKey, IssuedAmount(limit, asset))
    }.setGen1(Gen.identifier).setGen4(Gen.posNum[Long])
  }

  "a trustline updated effect document" should {
    "parse to a trustline updated effect" >> prop {
      (id: String, accn: KeyPair, asset: NonNativeAsset, limit: Long) =>
        val json = doc(id, "trustline_updated", accn, asset, limit)
        parse(json).extract[EffectResponse] mustEqual EffectTrustLineUpdated(id, accn.asPublicKey, IssuedAmount(limit, asset))
    }.setGen1(Gen.identifier).setGen4(Gen.posNum[Long])
  }

  "a trustline removed effect document" should {
    "parse to a trustline removed effect" >> prop { (id: String, accn: KeyPair, asset: NonNativeAsset) =>
      val json = doc(id, "trustline_removed", accn, asset, 0)
      parse(json).extract[EffectResponse] mustEqual EffectTrustLineRemoved(id, accn.asPublicKey, asset)
    }.setGen1(Gen.identifier)
  }

  def doc(id: String, tpe: String, accn: PublicKeyOps, asset: NonNativeAsset, limit: Long) = {
    s"""
       |{
       |  "_links": {
       |    "operation": {
       |      "href": "https://horizon-testnet.stellar.org/operations/10157597659144"
       |    },
       |    "succeeds": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144-2"
       |    },
       |    "precedes": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144-2"
       |    }
       |  },
       |  "id": "$id",
       |  "paging_token": "10157597659144-2",
       |  "account": "${accn.accountId}",
       |  "type": "$tpe",
       |  "type_i": 20,
       |  "asset_type": "${asset.typeString}",
       |  "asset_code": "${asset.code}",
       |  "asset_issuer": "${asset.issuer.accountId}",
       |  "limit": "${limit / math.pow(10, 7)}"
       |}
    """.stripMargin
  }


  def amountString(a: Amount): String = "%.7f".formatLocal(Locale.ROOT, a.units / math.pow(10, 7))

} 
Example 5
Source File: TrustLineAuthEffectResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.scalacheck.Gen
import org.specs2.mutable.Specification
import stellar.sdk._
import stellar.sdk.model.NonNativeAsset

class TrustLineAuthEffectResponseSpec extends Specification with ArbitraryInput {

  implicit val formats: Formats = Serialization.formats(NoTypeHints) + EffectResponseDeserializer

  "an authorize trustline effect document" should {
    "parse to an authorize trustline effect" >> prop { (id: String, accn: KeyPair, asset: NonNativeAsset) =>
      val json = doc(id, "trustline_authorized", accn, asset, 0.0)
      parse(json).extract[EffectResponse] mustEqual EffectTrustLineAuthorized(id, accn.asPublicKey, asset)
    }.setGen1(Gen.identifier)
  }

  "an authorize to maintain liabilities effect document" should {
    "parse to an authorize to maintain liabilities effect" >> prop { (id: String, accn: KeyPair, asset: NonNativeAsset) =>
      val json = doc(id, "trustline_authorized_to_maintain_liabilities", accn, asset, 0.0)
      parse(json).extract[EffectResponse] mustEqual EffectTrustLineAuthorizedToMaintainLiabilities(id, accn.asPublicKey, asset)
    }.setGen1(Gen.identifier)
  }

  "a deauthorize trustline effect document" should {
    "parse to a deauthorize trustline effect" >> prop { (id: String, accn: KeyPair, asset: NonNativeAsset) =>
      val json = doc(id, "trustline_deauthorized", accn, asset, 0.0)
      parse(json).extract[EffectResponse] mustEqual EffectTrustLineDeauthorized(id, accn.asPublicKey, asset)
    }.setGen1(Gen.identifier)
  }

  def doc(id: String, tpe: String, accn: PublicKeyOps, asset: NonNativeAsset, limit: Double) = {
    s"""
       |{
       |  "_links": {
       |    "operation": {
       |      "href": "https://horizon-testnet.stellar.org/operations/10157597659144"
       |    },
       |    "succeeds": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144-2"
       |    },
       |    "precedes": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144-2"
       |    }
       |  },
       |  "id": "$id",
       |  "paging_token": "10157597659144-2",
       |  "account": "${asset.issuer.accountId}",
       |  "type": "$tpe",
       |  "type_i": 23,
       |  "asset_type": "${asset.typeString}",
       |  "asset_code": "${asset.code}",
       |  "trustor": "${accn.accountId}"
       |}
    """.stripMargin
  }
} 
Example 6
Source File: TradeAggregationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model

import org.json4s.NoTypeHints
import org.json4s.native.{JsonMethods, Serialization}
import org.specs2.mutable.Specification
import stellar.sdk.ArbitraryInput

class TradeAggregationSpec extends Specification with ArbitraryInput {
  implicit val formats = Serialization.formats(NoTypeHints) + TradeAggregationDeserializer

  "a payment path response document" should {
    "parse to a payment path" >> prop { ta: TradeAggregation =>
      val json =
        s"""
          |{
          |  "timestamp": ${ta.instant.toEpochMilli.toString},
          |  "trade_count": ${ta.tradeCount},
          |  "base_volume": "${ta.baseVolume}",
          |  "counter_volume": "${ta.counterVolume}",
          |  "avg": "${ta.average}",
          |  "high": "${ta.high.asDecimalString}",
          |  "high_r": {
          |    "N": ${ta.high.n},
          |    "D": ${ta.high.d}
          |  },
          |  "low": "${ta.low.asDecimalString}",
          |  "low_r": {
          |    "N": ${ta.low.n},
          |    "D": ${ta.low.d}
          |  },
          |  "open": "${ta.open.asDecimalString}",
          |  "open_r": {
          |    "N": ${ta.open.n},
          |    "D": ${ta.open.d}
          |  },
          |  "close": "${ta.close.asDecimalString}",
          |  "close_r": {
          |    "N": ${ta.close.n},
          |    "D": ${ta.close.d.toString}
          |  }
          |}
        """.stripMargin

      JsonMethods.parse(json).extract[TradeAggregation] mustEqual ta
    }
  }
} 
Example 7
Source File: TnCmd.scala    From TopNotch   with Apache License 2.0 5 votes vote down vote up
package com.bfm.topnotch.tnengine

import java.io.{PrintWriter, StringWriter}

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.writePretty

/**
 * A command for TnEngine to run
 */
abstract class TnCmd {
  
  val outputKey: String
  /** Whether to cache the resulting dataframe in memory. This should be a boolean defaulting to false,
    * but json4s has a problem with default values other than None for option. Change it to a default value if json4s
    * solves the bug. */
  val cache: Option[Boolean]
  
  val outputPath: Option[String]
  /** If writing the output in hdfs, the name of the table to mount, otherwise none. Note: this will be ignored if
    * outputPath is not specified. */
  val tableName: Option[String]

  implicit val formats = Serialization.formats(NoTypeHints)
  /**
    * Overriding toString to making output of unit tests that have cmds in error logs easier to understand
    */
  override def toString = writePretty(this)
}

/**
 * The input to a command
 * @param ref The reference to the data set, either the path on hdfs or the name in the lookup table
 * @param onDisk Whether the input data set is stored on disk
 * @param delimiter The delimiter for plain text, delimited files. Leave to empty string for parquet.
 */
case class Input(ref: String, onDisk: Boolean, delimiter: Option[String] = None)

/**
 * The strings used for converting a config file into a TnCmd
 */
object TnCmdStrings {
  val ioNamespace = "io"
  val commandListStr = "commands"
  val writerStr = "writer"
  val commandStr = "command"
  val paramsStr = "params"
  val externalParamsStr = "externalParamsFile"
  val outputKeyStr = "outputKey"
  val writeToDiskStr = "writeToDisk"
  val outputPathStr = "outputPath"
}

/**
 * The class indicating that there was at least one error in the configuration for this command
 * @param cmdString The JSON string for the command.
 * @param errorStr The errors encountered in creating this command.
 * @param cmdIdx The index of the command in the plan that failed
 * @param outputKey This is meaningless in this class. This exists only so that TnErrorCmd can extend TnCmd.
 * @param writeToDisk This is meaningless in this class. This exists only so that TnErrorCmd can extend TnCmd.
 * @param outputPath This is meaningless in this class. This exists only so that TnErrorCmd can extend TnCmd.
 */
case class TnErrorCmd (
                            cmdString: String,
                            errorStr: String,
                            cmdIdx: Int,
                            outputKey: String = "",
                            cache: Option[Boolean] = None,
                            writeToDisk: Boolean = false,
                            outputPath: Option[String] = None,
                            tableName: Option[String] = None
                            ) extends TnCmd {
  override def toString: String = {
    s"There was an error with the command in position ${cmdIdx} in its plan. The command was: \n ${cmdString} \n " +
      s"The message was: \n ${errorStr} \n\n END OF ERROR MESSAGE FOR COMMAND IN POSITION ${cmdIdx} \n\n"
  }
}

object TnErrorCmd {
  /**
    * Helper method for easily getting the stack trace of an exception as a string
    * @param e The exception
    * @return The exception's stack trace
    */
  def getExceptionStackTrace(e: Exception): String = {
    val sw = new StringWriter
    e.printStackTrace(new PrintWriter(sw))
    sw.toString
  }
} 
Example 8
Source File: TnReaderTest.scala    From TopNotch   with Apache License 2.0 5 votes vote down vote up
package com.bfm.topnotch.tnengine

import org.json4s._
import org.json4s.native.Serialization
import com.bfm.topnotch.SparkApplicationTester
import org.scalatest.{Matchers, Tag}

/**
 * The tests for [[com.bfm.topnotch.tnengine.TnReader TnReader]].
  * Note that most testing is done by the tests for [[com.bfm.topnotch.tnengine.TnEngine TnEngine]]
 */
class TnReaderTest extends SparkApplicationTester with Matchers {

  object getReaderTag extends Tag("getReader")
  object readerVariableTag extends Tag("readerVariables")
  object jarReaderTag extends Tag("jarReader")
  implicit val formats = Serialization.formats(NoTypeHints)

  "getReader" should "throw an IllegalArgumentException when the plan doesn't exist" taggedAs(getReaderTag) in {
    intercept[IllegalArgumentException] {
      val fileReader = new TnFileReader
      fileReader.readConfiguration("src/test/resources/com/bfm/DOESNTEXIST")
    }
  }

  it should "replace variables in a configuration" taggedAs(readerVariableTag) in {
    val fileReader = new TnFileReader(Map("var1" -> "true", "var2" -> "false"))
    val replacedAST = fileReader.readConfiguration("src/test/resources/com/bfm/topnotch/tnengine/cliReplacementTest.json")
    replacedAST \ "trueToBeReplaced" should not equal(JNothing)
    (replacedAST \ "replaceThisValue").extract[String] should equal("false")
  }
} 
Example 9
Source File: PowerBIReportClient.scala    From spark-powerbi-connector   with Apache License 2.0 5 votes vote down vote up
package com.microsoft.azure.powerbi.clients

import com.microsoft.azure.powerbi.common._
import com.microsoft.azure.powerbi.exceptions._
import com.microsoft.azure.powerbi.models._
import org.apache.http.client.methods._
import org.apache.http.impl.client.CloseableHttpClient
import org.json4s.native.Serialization
import org.json4s.native.Serialization._
import org.json4s.ShortTypeHints

object PowerBIReportClient {

  def get(dashboardId: String,
          authenticationToken: String,
          groupId: String = null): PowerBIReportDetailsList = {

    implicit val formats = Serialization.formats(
      ShortTypeHints(
        List()
      )
    )

    var getRequestURL: String = null

    if(groupId == null || groupId.trim.isEmpty) {
      getRequestURL = PowerBIURLs.ReportsBeta
    } else {
      getRequestURL = PowerBIURLs.GroupsBeta + f"/$groupId/reports"
    }

    val getRequest: HttpGet = new HttpGet(getRequestURL)

    getRequest.addHeader("Authorization", f"Bearer $authenticationToken")

    val httpClient: CloseableHttpClient = HttpClientUtils.getCustomHttpClient

    var responseContent: String = null
    var statusCode: Int = -1
    var exceptionMessage: String = null

    try {
      val httpResponse = httpClient.execute(getRequest)
      statusCode = httpResponse.getStatusLine.getStatusCode

      val responseEntity = httpResponse.getEntity

      if (responseEntity != null) {

        val inputStream = responseEntity.getContent
        responseContent = scala.io.Source.fromInputStream(inputStream).getLines.mkString
        inputStream.close()
      }
    }
    catch {
      case e: Exception => exceptionMessage = e.getMessage
    }
    finally {
      httpClient.close()
    }

    if (statusCode == 200) {
      return read[PowerBIReportDetailsList](responseContent)
    }

    throw PowerBIClientException(statusCode, responseContent, exceptionMessage)
  }
} 
Example 10
Source File: PowerBIGroupClient.scala    From spark-powerbi-connector   with Apache License 2.0 5 votes vote down vote up
package com.microsoft.azure.powerbi.clients

import com.microsoft.azure.powerbi.common._
import com.microsoft.azure.powerbi.exceptions._
import com.microsoft.azure.powerbi.models._
import org.apache.http.client.methods._
import org.apache.http.impl.client.CloseableHttpClient
import org.json4s.ShortTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization._

object PowerBIGroupClient {

  def get(datasetId: String, authenticationToken: String): PowerBIGroupDetailsList = {

    implicit val formats = Serialization.formats(
      ShortTypeHints(
        List()
      )
    )

    val getRequest: HttpGet = new HttpGet(PowerBIURLs.Groups)

    getRequest.addHeader("Authorization", f"Bearer $authenticationToken")

    val httpClient: CloseableHttpClient = HttpClientUtils.getCustomHttpClient

    var responseContent: String = null
    var statusCode: Int = -1
    var exceptionMessage: String = null

    try {

      val httpResponse = httpClient.execute(getRequest)
      statusCode = httpResponse.getStatusLine.getStatusCode

      val responseEntity = httpResponse.getEntity

      if (responseEntity != null) {
        val inputStream = responseEntity.getContent
        responseContent = scala.io.Source.fromInputStream(inputStream).getLines.mkString
        inputStream.close()
      }
    }
    catch {
      case e: Exception => exceptionMessage = e.getMessage
    }
    finally {
      httpClient.close()
    }

    if (statusCode == 200) {
      return read[PowerBIGroupDetailsList](responseContent)
    }

    throw PowerBIClientException(statusCode, responseContent, exceptionMessage)
  }
} 
Example 11
Source File: PowerBIDashboardClient.scala    From spark-powerbi-connector   with Apache License 2.0 5 votes vote down vote up
package com.microsoft.azure.powerbi.clients

import com.microsoft.azure.powerbi.common._
import com.microsoft.azure.powerbi.exceptions._
import com.microsoft.azure.powerbi.models._
import org.apache.http.client.methods._
import org.apache.http.impl.client.CloseableHttpClient
import org.json4s.native.Serialization
import org.json4s.native.Serialization._
import org.json4s.ShortTypeHints

object PowerBIDashboardClient {

  def get(authenticationToken: String): PowerBIDashboardDetailsList = {
    get(authenticationToken, null)
  }

  def get(authenticationToken: String, groupId: String): PowerBIDashboardDetailsList = {

    implicit val formats = Serialization.formats(
      ShortTypeHints(
        List()
      )
    )

    var getRequestURL: String = null

    if (groupId == null || groupId.trim.isEmpty) {
      getRequestURL = PowerBIURLs.DashboardsBeta
    } else {
      getRequestURL = PowerBIURLs.GroupsBeta + f"/$groupId/dashboards"
    }

    val getRequest: HttpGet = new HttpGet(getRequestURL)

    getRequest.addHeader("Authorization", f"Bearer $authenticationToken")

    val httpClient: CloseableHttpClient = HttpClientUtils.getCustomHttpClient

    var responseContent: String = null
    var statusCode: Int = -1
    var exceptionMessage: String = null

    try {
      val httpResponse = httpClient.execute(getRequest)

      statusCode = httpResponse.getStatusLine.getStatusCode

      val responseEntity = httpResponse.getEntity

      if (responseEntity != null) {
        val inputStream = responseEntity.getContent
        responseContent = scala.io.Source.fromInputStream(inputStream).getLines.mkString
        inputStream.close()
      }
    }
    catch {
      case e: Exception => exceptionMessage = e.getMessage
    }
    finally {
      httpClient.close()
    }

    if (statusCode == 200) {
      return read[PowerBIDashboardDetailsList](responseContent)
    }

    throw PowerBIClientException(statusCode, responseContent, exceptionMessage)
  }
} 
Example 12
Source File: JsonProtocol.scala    From midas   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
//See LICENSE for license details.

package midas.passes.fame

import midas.widgets.SerializableBridgeAnnotation

import firrtl.annotations._

import scala.util.{Try, Failure}

import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, writePretty}

case class DeserializationTypeHintsAnnotation(typeTags: Seq[String]) extends NoTargetAnnotation

trait HasSerializationHints {
  // For serialization of complicated constuctor arguments, let the bridge
  // designer specify additional type hints for relevant classes that might be
  // contained within
  def typeHints(): Seq[Class[_]]
}

object JsonProtocol {
  import firrtl.annotations.JsonProtocol._

  
  def serialize(annos: Seq[Annotation]): String = serializeTry(annos).get

  def serializeTry(annos: Seq[Annotation]): Try[String] = {
    val tags = annos.flatMap({
      case anno: HasSerializationHints => anno.getClass +: anno.typeHints
      case other => Seq(other.getClass)
    }).distinct

    implicit val formats = jsonFormat(classOf[DeserializationTypeHintsAnnotation] +: tags)
    Try(writePretty(DeserializationTypeHintsAnnotation(tags.map(_.getName)) +: annos))
  }

  def deserialize(in: JsonInput): Seq[Annotation] = deserializeTry(in).get

  def deserializeTry(in: JsonInput): Try[Seq[Annotation]] = Try({
    val parsed = parse(in)
    val annos = parsed match {
      case JArray(objs) => objs
      case x => throw new InvalidAnnotationJSONException(
        s"Annotations must be serialized as a JArray, got ${x.getClass.getSimpleName} instead!")
    }
    // Gather classes so we can deserialize arbitrary Annotations
    val classes = annos.flatMap({
      case JObject(("class", JString(typeHintAnnoName)) :: ("typeTags", JArray(classes)) :: Nil) =>
          typeHintAnnoName +: classes.collect({ case JString(className) => className })
      case JObject(("class", JString(c)) :: tail) => Seq(c)
      case obj => throw new InvalidAnnotationJSONException(s"Expected field 'class' not found! $obj")
    }).distinct
    val loaded = classes.map(Class.forName(_).asInstanceOf[Class[_ <: Annotation]])

    implicit val formats = jsonFormat(loaded)
    read[List[Annotation]](in)
  }).recoverWith {
    // Translate some generic errors to specific ones
    case e: java.lang.ClassNotFoundException =>
      Failure(new AnnotationClassNotFoundException(e.getMessage))
    case e: org.json4s.ParserUtil.ParseException =>
      Failure(new InvalidAnnotationJSONException(e.getMessage))
  }.recoverWith { // If the input is a file, wrap in InvalidAnnotationFileException
    case e => in match {
      case FileInput(file) =>
        Failure(new InvalidAnnotationFileException(file, e))
      case _ => Failure(e)
    }
  }
} 
Example 13
Source File: SignerEffectResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.util.Locale

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.scalacheck.Gen
import org.specs2.mutable.Specification
import stellar.sdk._
import stellar.sdk.model.Amount

class SignerEffectResponseSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + EffectResponseDeserializer

  "a signer created effect document" should {
    "parse to a signer created effect" >> prop { (id: String, kp: KeyPair, weight: Short, pubKey: String) =>
      val json = doc(id, kp, "signer_created", weight, "public_key" -> pubKey)
      parse(json).extract[EffectResponse] mustEqual EffectSignerCreated(id, kp.asPublicKey, weight, pubKey)
    }.setGen1(Gen.identifier).setGen4(Gen.identifier)
  }

  "a signer updated effect document" should {
    "parse to a signer updated effect" >> prop { (id: String, kp: KeyPair, weight: Short, pubKey: String) =>
      val json = doc(id, kp, "signer_updated", weight, "public_key" -> pubKey)
      parse(json).extract[EffectResponse] mustEqual EffectSignerUpdated(id, kp.asPublicKey, weight, pubKey)
    }.setGen1(Gen.identifier).setGen4(Gen.identifier)
  }

  "a signer removed effect document" should {
    "parse to a signer removed effect" >> prop { (id: String, kp: KeyPair, pubKey: String) =>
      val json = doc(id, kp, "signer_removed", 0, "public_key" -> pubKey)
      parse(json).extract[EffectResponse] mustEqual EffectSignerRemoved(id, kp.asPublicKey, pubKey)
    }.setGen1(Gen.identifier).setGen3(Gen.identifier)
  }

  def doc(id: String, kp: KeyPair, tpe: String, weight: Short, extra: (String, Any)*) =
    s"""
       |{
       |  "_links": {
       |    "operation": {
       |      "href": "https://horizon-testnet.stellar.org/operations/10157597659144"
       |    },
       |    "succeeds": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144-2"
       |    },
       |    "precedes": {
       |      "href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144-2"
       |    }
       |  },
       |  "id": "$id",
       |  "paging_token": "10157597659144-2",
       |  "account": "${kp.accountId}",
       |  "weight": $weight
       |  "type": "$tpe",
       |  "type_i": 10,
       |  ${
      extra.map {
        case (k, v: String) => s""""$k": "$v"""".trim
        case (k, v) => s""""$k": $v""".trim
      }.mkString(", ")
    }
       |}
    """.stripMargin

  def amountString(a: Amount): String = "%.7f".formatLocal(Locale.ROOT, a.units / math.pow(10, 7))

} 
Example 14
Source File: WebClient.scala    From twitter-stream-ml   with GNU General Public License v3.0 5 votes vote down vote up
package com.giorgioinf.twtml.web

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{write,read}
import scala.reflect.Manifest
import scalaj.http.{Http,HttpRequest}

class WebClient (val server:String) {

    implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[Config], classOf[Stats])))

    def this() = this("http://localhost:8888")

    private def request(kind:String = ""):HttpRequest = {
      Http(server + "/api" + kind)
        .header("content-type", "application/json")
        .header("accept", "application/json")
    }

    private def post(data:TypeData) {
      val json = write(data)
      request().postData(json).asString
    }

    private def get[A:Manifest](kind:String):A = {
      val json = request(kind).asString.body
      read[A](json)
    }

    def config(id:String, host:String, viz:List[String]) = {
      post(Config(id, host, viz))
    }

    def stats(count:Long, batch:Long, mse:Long,
        realStddev:Long, predStddev:Long) = {
      post(Stats(count, batch, mse, realStddev, predStddev))
    }

    def config():Config = {
      get[Config]("/config")
    }

    def stats():Stats = {
      get[Stats]("/stats")
    }
}

object WebClient {
    def apply(host: String = ""): WebClient = {
    host match {
      case "" => new WebClient()
      case _ => new WebClient(host)
    }
  }
} 
Example 15
Source File: WebClient.scala    From twitter-stream-ml   with GNU General Public License v3.0 5 votes vote down vote up
package com.giorgioinf.twtml.web

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{write,read}
import scala.reflect.Manifest
import scalaj.http.{Http,HttpRequest}

class WebClient (val server:String) {

    implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[Config], classOf[Stats])))

    def this() = this("http://localhost:8888")

    private def request(kind:String = ""):HttpRequest = {
      Http(server + "/api" + kind)
        .header("content-type", "application/json")
        .header("accept", "application/json")
    }

    private def post(data:TypeData) {
      val json = write(data)
      request().postData(json).asString
    }

    private def get[A:Manifest](kind:String):A = {
      val json = request(kind).asString.body
      read[A](json)
    }

    def config(id:String, host:String, viz:List[String]) = {
      post(Config(id, host, viz))
    }

    def stats(count:Long, batch:Long, mse:Long,
        realStddev:Long, predStddev:Long) = {
      post(Stats(count, batch, mse, realStddev, predStddev))
    }

    def config():Config = {
      get[Config]("/config")
    }

    def stats():Stats = {
      get[Stats]("/stats")
    }
}

object WebClient {
    def apply(host: String = ""): WebClient = {
    host match {
      case "" => new WebClient()
      case _ => new WebClient(host)
    }
  }
} 
Example 16
Source File: Visualization.scala    From lightning-scala   with MIT License 5 votes vote down vote up
package org.viz.lightning

import org.json4s.DefaultFormats
import org.json4s.native.Serialization
import scala.language.dynamics
import scalaj.http._

class Visualization(val lgn: Lightning, val id: String, val name: String) {

  if (lgn.isNotebook) {
    //implicit val HTMLViz = org.refptr.iscala.display.HTMLDisplay[Visualization] { viz =>
    //  viz.getHTML
    //}
    //org.refptr.iscala.display.display_html(this)
  }

  def formatURL(url: String): String = {
    val out = url.last.toString match {
      case "/" => url
      case _ => url + "/"
    }
    out + "?host=" + lgn.host
  }

  def getPermalinkURL: String = {
    lgn.host + "/visualizations/" + id
  }

  def getEmbedLink: String = {
    formatURL(this.getPermalinkURL + "/embed")
  }

  def getIframeLink: String = {
    formatURL(this.getPermalinkURL + "/iframe")
  }

  def getPymLink: String = {
    formatURL(this.getPermalinkURL + "/pym")
  }

  def getDataLink: String = {
    formatURL(lgn.host + "/sessions/" + lgn.session + "/visualizations/" + id + "/data/")
  }

  def getHTML: String = {
    val url = getEmbedLink
    var request = Http(url).method("GET")
    if (lgn.auth.nonEmpty) {
      request = request.auth(lgn.auth.get._1, lgn.auth.get._2)
    }
    request.asString.body
  }

  def append(payload: Map[String, Any]) : Visualization = {
    val url = lgn.host + "/sessions/" + lgn.session + "/visualizations/" + this.id + "/data/"
    implicit val formats = DefaultFormats
    val blob = Map("data" -> payload)
    lgn.post(url, Serialization.write(blob))
    this
  }
	
  def getPublicLink: String = {
    this.getPermalinkURL + "/public/"
  }
  
} 
Example 17
Source File: PersistenceRecord.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.persistence

import java.time.OffsetDateTime

import io.vamp.common.json.{ OffsetDateTimeSerializer, SerializationFormat }
import io.vamp.common.notification.NotificationProvider
import io.vamp.common.{ Artifact, Config, Namespace, NamespaceProvider }
import io.vamp.model.Model
import io.vamp.persistence.notification.UnknownDataFormatException
import org.json4s.Formats
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write

import scala.util.Try

object PersistenceRecord {

  def apply(name: String, kind: String): PersistenceRecord = PersistenceRecord(Model.version, Model.uuid, OffsetDateTime.now(), name, kind, None)

  def apply(name: String, kind: String, artifact: String): PersistenceRecord = PersistenceRecord(Model.version, Model.uuid, OffsetDateTime.now(), name, kind, Option(artifact))
}

case class PersistenceRecord(version: String, instance: String, timestamp: OffsetDateTime, name: String, kind: String, artifact: Option[String])

abstract class PersistenceRecordTransformer(namespace: Namespace) {

  def timeDependent: Boolean = false

  def read(input: String): String

  def write(input: String): String

}

trait PersistenceRecordMarshaller {
  this: NamespaceProvider ⇒

  protected val transformersPath = "vamp.persistence.transformers.classes"

  private lazy val transformers = {
    val transformerClasses = if (Config.has(transformersPath)(namespace)()) Config.stringList(transformersPath)() else Nil
    transformerClasses.map { clazz ⇒
      Class.forName(clazz).getConstructor(classOf[Namespace]).newInstance(namespace).asInstanceOf[PersistenceRecordTransformer]
    }
  }

  lazy val timeDependent: Boolean = transformers.exists(_.timeDependent)

  def marshallRecord(record: PersistenceRecord): String = {
    val content = write(record)(SerializationFormat(OffsetDateTimeSerializer))
    transformers.foldLeft[String](content)((input, transformer) ⇒ transformer.write(input))
  }

  def unmarshallRecord(source: String): PersistenceRecord = {
    val input = transformers.foldRight[String](source)((transformer, source) ⇒ transformer.read(source))
    implicit val format: Formats = SerializationFormat(OffsetDateTimeSerializer)
    Serialization.read[PersistenceRecord](input)
  }
}

trait PersistenceDataReader extends PersistenceRecordMarshaller with PersistenceMarshaller {
  this: PersistenceApi with NamespaceProvider with NotificationProvider ⇒

  protected def dataSet(artifact: Artifact, kind: String): Artifact

  protected def dataDelete(name: String, kind: String): Unit

  protected def dataRead(data: String): PersistenceRecord = {
    val record = Try(unmarshallRecord(data)).getOrElse(throwException(UnknownDataFormatException("")))
    record.artifact match {
      case Some(content) ⇒ unmarshall(record.kind, content).map(a ⇒ dataSet(a, record.kind)).getOrElse(throwException(UnknownDataFormatException(record.kind)))
      case None          ⇒ dataDelete(record.name, record.kind)
    }
    record
  }
} 
Example 18
Source File: S3ConfigManager.scala    From teamcity-s3-plugin   with Apache License 2.0 5 votes vote down vote up
package com.gu.teamcity

import java.io.{File, PrintWriter}

import com.amazonaws.auth.{BasicAWSCredentials, AWSCredentialsProvider, AWSCredentials}
import jetbrains.buildServer.serverSide.ServerPaths
import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization._

case class S3Config(
  artifactBucket: Option[String], buildManifestBucket: Option[String], tagManifestBucket: Option[String],
  awsAccessKey: Option[String], awsSecretKey: Option[String]
)

class S3ConfigManager(paths: ServerPaths) extends AWSCredentialsProvider {
  implicit val formats = Serialization.formats(NoTypeHints)

  val configFile = new File(s"${paths.getConfigDir}/s3.json")

  private[teamcity] var config: Option[S3Config] = {
    if (configFile.exists()) {
      parse(configFile).extractOpt[S3Config]
    } else None
  }

  def artifactBucket: Option[String] = config.flatMap(_.artifactBucket)
  def buildManifestBucket: Option[String] = config.flatMap(_.buildManifestBucket)
  def tagManifestBucket: Option[String] = config.flatMap(_.tagManifestBucket)

  private[teamcity] def update(config: S3Config): Unit = {
    this.config = Some(if (config.awsSecretKey.isEmpty && config.awsAccessKey == this.config.flatMap(_.awsAccessKey)) {
      config.copy(awsSecretKey = this.config.flatMap(_.awsSecretKey))
    } else config)
  }

  def updateAndPersist(newConfig: S3Config): Unit = {
    synchronized {
      update(newConfig)
      val out = new PrintWriter(configFile, "UTF-8")
      try { writePretty(config, out) }
      finally { out.close }
    }
  }

  def details: Map[String, Option[String]] = Map(
    "artifactBucket" -> artifactBucket,
    "buildManifestBucket" -> buildManifestBucket,
    "tagManifestBucket" -> tagManifestBucket,
    "accessKey" -> config.flatMap(_.awsAccessKey)
  )

  override def getCredentials: AWSCredentials = (for {
    c <- config
    accessKey <- c.awsAccessKey
    secretKey <- c.awsSecretKey
  } yield new BasicAWSCredentials(accessKey, secretKey)).getOrElse(null) // Yes, this is sad

  override def refresh(): Unit = ()
}

object S3ConfigManager {
  val bucketElement = "bucket"
  val s3Element = "S3"
} 
Example 19
Source File: FunctionCalls.scala    From aardpfark   with Apache License 2.0 5 votes vote down vote up
package com.ibm.aardpfark.pfa.expression

import com.ibm.aardpfark.pfa.document.{PFAExpressionSerializer, ParamSerializer, SchemaSerializer}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write
import org.json4s.{JDouble, JField, JInt, JObject, JString, JValue, NoTypeHints}


class FunctionCall(name: String, args: Any*) extends PFAExpression {
  import com.ibm.aardpfark.pfa.dsl._
  import org.json4s.JsonDSL._

  override def json: JValue = {
    val jArgs = args.map {
      case n: Double =>
        JDouble(n)
      case i: Int =>
        JInt(i)
      case s: String =>
        JString(s)
      case expr: PFAExpression =>
        expr.json
      case fnDef: FunctionDef =>
        implicit val formats = Serialization.formats(NoTypeHints) +
          new SchemaSerializer +
          new PFAExpressionSerializer +
          new ParamSerializer
        parse(write(fnDef))
    }
    JObject(JField(name, jArgs) :: Nil)
  }
} 
Example 20
Source File: PFADocument.scala    From aardpfark   with Apache License 2.0 5 votes vote down vote up
package com.ibm.aardpfark.pfa.document

import com.ibm.aardpfark.pfa.dsl._
import com.ibm.aardpfark.pfa.expression.PFAExpression
import com.ibm.aardpfark.pfa.utils.Utils
import org.apache.avro.Schema
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{write, writePretty}
import org.json4s.{FieldSerializer, NoTypeHints}

trait ToPFA {
  def pfa: PFADocument
}

trait HasAction {
  protected def action: PFAExpression
}

trait HasModelCell {
  protected def modelCell: NamedCell[_]
}

case class PFADocument(
  name: Option[String] = None,
  version: Option[Long] = Some(1L),
  doc: Option[String] = Some(s"Auto-generated by Aardpfark at ${Utils.getCurrentDate}"),
  metadata: Map[String, String] = Map(),
  // options,
  input: Schema,
  output: Schema,
  // begin: Seq[String] = Seq(),
  // end: Seq[String] = Seq(),
  // method: String = "map",
  action: Seq[PFAExpression],
  cells: Map[String, Cell[_]] = Map(),
  // pools
  fcns: Map[String, FunctionDef] = Map()
  // randseed
  // zero
  // merge
  ) {

  implicit val formats = Serialization.formats(NoTypeHints) +
    new SchemaSerializer +
    new PFAExpressionSerializer +
    new ParamSerializer +
    new FieldSerializer[Cell[_]] +
    new TreeSerializer

  def toJSON(pretty: Boolean = false) = {
    if (pretty) writePretty(this) else write(this)
  }
} 
Example 21
Source File: CommonClient.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.http.clients

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpEntity, HttpRequest, HttpResponse}
import akka.stream.Materializer
import com.danielasfregola.twitter4s.exceptions.{Errors, TwitterException}
import com.danielasfregola.twitter4s.http.serializers.JsonSupport
import com.typesafe.scalalogging.LazyLogging
import org.json4s.native.Serialization

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.Try

private[twitter4s] trait CommonClient extends JsonSupport with LazyLogging {

  def withLogRequest: Boolean
  def withLogRequestResponse: Boolean

  protected def connection(implicit request: HttpRequest, system: ActorSystem) = {
    val scheme = request.uri.scheme
    val host = request.uri.authority.host.toString
    val port = request.uri.effectivePort
    if (scheme == "https") Http().outgoingConnectionHttps(host, port)
    else Http().outgoingConnection(host, port)
  }

  protected def unmarshal[T](requestStartTime: Long, f: HttpResponse => Future[T])(implicit request: HttpRequest,
                                                                                   response: HttpResponse,
                                                                                   materializer: Materializer) = {
    implicit val ec = materializer.executionContext
    if (withLogRequestResponse) logRequestResponse(requestStartTime)

    if (response.status.isSuccess) f(response)
    else parseFailedResponse(response).flatMap(Future.failed)
  }

  protected def parseFailedResponse(response: HttpResponse)(implicit materializer: Materializer) = {
    implicit val ec = materializer.executionContext
    response.entity.toStrict(50 seconds).map { sink =>
      val body = sink.data.utf8String
      val errors = Try {
        Serialization.read[Errors](body)
      } getOrElse Errors(body)
      TwitterException(response.status, errors)
    }
  }

  // TODO - logRequest, logRequestResponse customisable?
  def logRequest(implicit request: HttpRequest, materializer: Materializer): HttpRequest = {
    implicit val ec = materializer.executionContext
    logger.info(s"${request.method.value} ${request.uri}")
    if (logger.underlying.isDebugEnabled) {
      for {
        requestBody <- toBody(request.entity)
      } yield logger.debug(s"${request.method.value} ${request.uri} | $requestBody")
    }
    request
  }

  def logRequestResponse(requestStartTime: Long)(implicit request: HttpRequest,
                                                 materializer: Materializer): HttpResponse => HttpResponse = {
    response =>
      implicit val ec = materializer.executionContext
      val elapsed = System.currentTimeMillis - requestStartTime
      logger.info(s"${request.method.value} ${request.uri} (${response.status}) | ${elapsed}ms")
      if (logger.underlying.isDebugEnabled) {
        for {
          responseBody <- toBody(response.entity)
        } yield
          logger.debug(
            s"${request.method.value} ${request.uri} (${response.status}) | ${response.headers.mkString(", ")} | $responseBody")
      }
      response
  }

  private def toBody(entity: HttpEntity)(implicit materializer: Materializer): Future[String] = {
    implicit val ec = materializer.executionContext
    entity.toStrict(5 seconds).map(_.data.decodeString("UTF-8"))
  }
} 
Example 22
Source File: SerializationRoundtripSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.entities

import java.time.Instant

import com.danielasfregola.randomdatagenerator.RandomDataGenerator
import com.danielasfregola.twitter4s.http.serializers.JsonSupport
import org.json4s.native.Serialization
import org.scalacheck.Gen.alphaChar
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragment

import scala.reflect._

class SerializationRoundtripSpec extends Specification with RandomDataGenerator with JsonSupport {

  "JSON serialization" should {

    def roundtripTest[T <: AnyRef: Manifest: Arbitrary]: Fragment = {

      val className = classTag[T].runtimeClass.getSimpleName

      s"round-trip successfully for $className" in {
        val randomEntity = random[T]

        val serializedJson = Serialization.write[T](randomEntity)

        val deserializedEntity = Serialization.read[T](serializedJson)

        deserializedEntity === randomEntity
      }
    }

    roundtripTest[User]
  }

  // We serialize dates to second precision
  implicit val arbitraryDate: Arbitrary[Instant] = Arbitrary {
    for {
      timeInSeconds: Long <- Gen.chooseNum(1142899200L, 1512442349L)
    } yield Instant.ofEpochSecond(timeInSeconds)
  }

  implicit val arbitraryProfileImage: Arbitrary[ProfileImage] = Arbitrary {
    for {
      prefix: String <- Gen.nonEmptyListOf(alphaChar).map(_.mkString)
      suffix: String <- Gen.oneOf("_mini", "_normal", "_bigger", "")
    } yield ProfileImage(s"${prefix}_$suffix.jpg")
  }
} 
Example 23
Source File: DeserializationRoundtripSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.entities

import com.danielasfregola.twitter4s.helpers.{FixturesSupport, JsonDiffSupport}
import org.json4s.native.Serialization.writePretty
import org.json4s.native.{JsonParser, Serialization}
import org.json4s.{JNothing, JValue}
import org.specs2.matcher.{Expectable, Matcher}
import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragment

import scala.reflect._

class DeserializationRoundtripSpec extends Specification with FixturesSupport with JsonDiffSupport {

  "JSON deserialization" should {

    def roundtripTest[T <: AnyRef: Manifest](jsonFile: String): Fragment = {

      val className = classTag[T].runtimeClass.getSimpleName

      s"round-trip successfully for $className in $jsonFile" in {
        val originalJson = load(jsonFile)

        val deserializedEntity = Serialization.read[T](originalJson)

        val serializedJson = Serialization.writePretty[T](deserializedEntity)

        originalJson must beASubsetOfJson(serializedJson)
      }
    }

    roundtripTest[User]("/twitter/rest/users/user.json")
  }

  def beASubsetOfJson(otherJson: String): Matcher[String] = new Matcher[String] {

    def apply[S <: String](t: Expectable[S]) = {
      val alpha: JValue = JsonParser.parse(t.value)
      val beta: JValue = JsonParser.parse(otherJson)

      jsonDiff(alpha, beta) match {
        case diff @ JsonDiff(JNothing, _, JNothing) =>
          success(s"""${t.value}
               |is a subset of
               |$otherJson
               |${renderDiff(diff)}
             """.stripMargin,
                  t)
        case diff =>
          failure(s"""${t.value}
               |is not a subset of
               |$otherJson
               |${renderDiff(diff)}
             """.stripMargin,
                  t)
      }
    }

    private def renderDiff(diff: JsonDiff) = {
      val changed = diff.changed.toOption.map { c =>
        s"""Changed:
           |${writePretty(c)}
          """.stripMargin
      }
      val deleted = diff.deleted.toOption.map { d =>
        s"""Deleted:
           |${writePretty(d)}
          """.stripMargin
      }
      val added = diff.added.toOption.map { a =>
        s"""Added:
           |${writePretty(a)}
          """.stripMargin
      }

      (changed ++ deleted ++ added).mkString
    }
  }
} 
Example 24
Source File: InflationOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class InflationOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[InflationOperation]] = Arbitrary(genTransacted(genInflationOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "the inflation operation" should {
    "serde via xdr string" >> prop { actual: InflationOperation =>
      Operation.decodeXDR(base64(actual.encode)) mustEqual actual
    }

    "serde via xdr bytes" >> prop { actual: InflationOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[InflationOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "inflation",
           |  "type_i": 9,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[InflationOperation]] mustEqual op
    }.setGen(genTransacted(genInflationOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 25
Source File: Json4sHttpRequestResponseFormatsSpec.scala    From reliable-http-client   with Apache License 2.0 5 votes vote down vote up
package rhttpc.akkahttp.json4s

import java.util.UUID

import akka.http.scaladsl.model._
import org.json4s.native.Serialization
import org.scalatest._
import org.scalatest.prop.TableDrivenPropertyChecks
import rhttpc.client.protocol.{Correlated, Exchange, FailureExchange, SuccessExchange}
import rhttpc.client.proxy.{ExhaustedRetry, NonSuccessResponse}

class Json4sHttpRequestResponseFormatsSpec extends FlatSpec with TableDrivenPropertyChecks with Matchers {
  implicit val formats = Json4sHttpRequestResponseFormats.formats

  val requestsData = Table[Correlated[HttpRequest]](
    "request",
    Correlated(HttpRequest().withMethod(HttpMethods.POST).withEntity("foo"), UUID.randomUUID().toString)
  )

  // FIXME: unignore tests when json4s problem with classloaders will be fixed (test fail only from cmd, from IDE work)
  ignore should "work round-trip for requests" in {
    forAll(requestsData) { request =>
      val serialized = Serialization.writePretty(request)
      println("Serialized: " + serialized)
      withClue("Serialized: " + serialized) {
        val deserialized = Serialization.read[Correlated[HttpRequest]](serialized)
        println("Deserialized: " + deserialized)
        deserialized shouldEqual request
      }
    }
  }

  val responsesData = Table[Correlated[Exchange[HttpRequest, HttpResponse]]](
    "responses",
    Correlated(SuccessExchange(HttpRequest(), HttpResponse().withEntity("bar")), UUID.randomUUID().toString),
    Correlated(FailureExchange(HttpRequest(), ExhaustedRetry(NonSuccessResponse)), UUID.randomUUID().toString)
  )

  ignore should "work round-trip for responses" in {
    forAll(responsesData) { response =>
      val serialized = Serialization.writePretty(response)
      println("Serialized: " + serialized)
      withClue("Serialized: " + serialized) {
        val deserialized = Serialization.read[Correlated[Exchange[HttpRequest, HttpResponse]]](serialized)
        println("Deserialized: " + deserialized)
        deserialized shouldEqual response
      }
    }
  }
} 
Example 26
Source File: Json4sSerializer.scala    From reliable-http-client   with Apache License 2.0 5 votes vote down vote up
package rhttpc.transport.json4s

import org.json4s.Formats
import org.json4s.native.Serialization
import rhttpc.transport.{Deserializer, Serializer}

import scala.util.Try

class Json4sSerializer[Msg <: AnyRef](implicit formats: Formats) extends Serializer[Msg] {
  override def serialize(msg: Msg): String = {
    Serialization.write(msg)(formats)
  }
}

class Json4sDeserializer[Msg: Manifest](implicit formats: Formats) extends Deserializer[Msg] {
  override def deserialize(value: String): Try[Msg] = {
    Try(Serialization.read[Msg](value))
  }
} 
Example 27
Source File: VatReturnDeclaration.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.json4s.JsonAST._
import org.json4s.native.Serialization
import org.json4s.{CustomSerializer, DefaultFormats}
import uk.gov.hmrc.vatapi.models.Amount

object VatReturnDeclaration {
}

case class VatReturnDeclaration(
                                 periodKey: String,
                                 vatDueSales: Amount,
                                 vatDueAcquisitions: Amount,
                                 vatDueTotal: Amount,
                                 vatReclaimedCurrPeriod: Amount,
                                 vatDueNet: Amount,
                                 totalValueSalesExVAT: Amount,
                                 totalValuePurchasesExVAT: Amount,
                                 totalValueGoodsSuppliedExVAT: Amount,
                                 totalAllAcquisitionsExVAT: Amount,
                                 agentReferenceNumber: Option[String] = None,
                                 receivedAt: DateTime
                               ) {
  def toJsonString: String = {
    implicit val formats = DefaultFormats ++ Seq(BigDecimalSerializer) ++ Seq(JodaSerializer)
    Serialization.write(this)
  }
}


private object BigDecimalSerializer extends CustomSerializer[Amount](format => ( {
  case jde: JDecimal => jde.num
}, {
  case bd: Amount => JDecimal(bd.setScale(2))
}
))

private object JodaSerializer extends CustomSerializer[DateTime](format => ( {
  case js: JString => DateTime.parse(js.s)
}, {
  case dt: DateTime => {
    val fmt = ISODateTimeFormat.dateTime()
    JString(dt.toString(fmt))
  }
}
)) 
Example 28
Source File: scalaUse.scala    From tscfg   with Apache License 2.0 5 votes vote down vote up
package tscfg.example

import java.io.File

import com.typesafe.config.{ConfigRenderOptions, ConfigFactory}


object scalaUse {

  def main(args: Array[String]): Unit = {
    val configFilename = args.headOption.getOrElse("src/main/tscfg/example/example.conf")
    println(s"Loading $configFilename")
    val configFile = new File(configFilename)

    // usual Typesafe Config mechanism to load the file
    val tsConfig = ConfigFactory.parseFile(configFile).resolve

    // create instance of the tscfg generated main class. This will
    // perform all validations according to required properties and types:
    val cfg = ScalaExampleCfg(tsConfig)

    // access the configuration properties in a type-safe fashion while also
    // enjoying your IDE features for code completion, navigation, etc:
    val path: String         = cfg.endpoint.path
    val url: String          = cfg.endpoint.url
    val serial: Option[Int]  = cfg.endpoint.serial
    val port: Int            = cfg.endpoint.interface.port
    val typ : Option[String] = cfg.endpoint.interface.`type`

    println("\n*** tscfg case class structure: *** ")
    println("  " + cfg.toString.replaceAll("\n", "\n  "))
    println("\n  *** in JSON format: *** ")
    println("  " + toJson(cfg).toString.replaceAll("\n", "\n  "))

    println("\n*** Typesafe rendering of input Config object: *** ")
    val options: ConfigRenderOptions = ConfigRenderOptions.defaults
      .setFormatted(true).setComments(true).setOriginComments(false)
    println("  " + tsConfig.root.render(options).replaceAll("\n", "\n  "))
  }

  def toJson(cfg: ScalaExampleCfg): String = {
    import org.json4s._
    import org.json4s.native.Serialization
    import org.json4s.native.Serialization.writePretty
    implicit val formats = Serialization.formats(NoTypeHints)
    writePretty(cfg)
  }
} 
Example 29
Source File: FederationServer.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk

import java.net.HttpURLConnection.HTTP_NOT_FOUND

import com.typesafe.scalalogging.LazyLogging
import okhttp3.{Headers, HttpUrl, OkHttpClient, Request}
import org.json4s.native.{JsonMethods, Serialization}
import org.json4s.{Formats, NoTypeHints}
import stellar.sdk.inet.RestException
import stellar.sdk.model.response.{FederationResponse, FederationResponseDeserialiser}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}

case class FederationServer(base: HttpUrl) extends LazyLogging {

  implicit val formats: Formats = Serialization.formats(NoTypeHints) + FederationResponseDeserialiser
  private val client = new OkHttpClient()
  private val headers = Headers.of(
    "X-Client-Name", BuildInfo.name,
    "X-Client-Version", BuildInfo.version)

  def byName(name: String)(implicit ec: ExecutionContext): Future[Option[FederationResponse]] =
    fetchFederationResponse(base.newBuilder()
      .addQueryParameter("q", name)
      .addQueryParameter("type", "name")
      .build(),  _.copy(address = name))

  def byAccount(account: PublicKey)(implicit ec: ExecutionContext): Future[Option[FederationResponse]] =
    fetchFederationResponse(base.newBuilder()
      .addQueryParameter("q", account.accountId)
      .addQueryParameter("type", "id")
      .build(), _.copy(account = account))


  private def fetchFederationResponse(url: HttpUrl, fillIn: FederationResponse => FederationResponse)
                                     (implicit ec: ExecutionContext): Future[Option[FederationResponse]] =
    Future(client.newCall(new Request.Builder().url(url).headers(headers).build()).execute())
      .map { response =>
        response.code() match {
          case HTTP_NOT_FOUND => None
          case e if e >= 500 => throw RestException(response.body().string())
          case _ =>
            Try(response.body().string())
              .map(JsonMethods.parse(_))
              .map(_.extract[FederationResponse])
              .map(fillIn)
              .map(validate) match {
              case Success(fr) => Some(fr)
              case Failure(t) => throw RestException("Could not parse document as FederationResponse.", t)
            }
        }
      }


  private def validate(fr: FederationResponse): FederationResponse = {
    if (fr.account == null) throw RestException(s"Document did not contain account_id")
    if (fr.address == null) throw RestException(s"Document did not contain stellar_address")
    fr
  }
}

object FederationServer {
  def apply(uriString: String): FederationServer = new FederationServer(HttpUrl.parse(uriString))
} 
Example 30
Source File: PaymentPathSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model

import org.json4s.NoTypeHints
import org.json4s.native.{JsonMethods, Serialization}
import org.specs2.mutable.Specification
import stellar.sdk.ArbitraryInput

class PaymentPathSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + PaymentPathDeserializer

  "a payment path response document" should {
    "parse to a payment path" >> prop { path: PaymentPath =>

      def amountJson(prefix: String, amount: Amount) =
        s"""
           |"${prefix}amount": "${amount.toDisplayUnits}",
           |${assetJson(prefix, amount.asset)}
         """.stripMargin

      def assetJson(prefix: String, asset: Asset) = {
        asset match {
          case NativeAsset => s""""${prefix}asset_type": "native""""
          case issuedAsset: NonNativeAsset =>
            s"""
               |"${prefix}asset_type": "${issuedAsset.typeString}",
               |"${prefix}asset_code": "${issuedAsset.code}",
               |"${prefix}asset_issuer": "${issuedAsset.issuer.accountId}"
            """.stripMargin
        }
      }

      val json =
        s"""
           |{
           |  ${amountJson("source_", path.source)},
           |  ${amountJson("destination_", path.destination)},
           |  "path": ${path.path.map(j => s"{${assetJson("", j)}}").mkString("[", ",", "]")}
           |}
         """.stripMargin

      JsonMethods.parse(json).extract[PaymentPath] mustEqual path
    }
  }

  "the underlying amount parser" should {
    "not parse unrecognised asset type" >> {
      val doc = """{"foo_asset_type":"bananas"}"""
      AmountParser.parseAsset("foo_", JsonMethods.parse(doc)) must throwA[RuntimeException]
    }
  }

} 
Example 31
Source File: TradeSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.specs2.mutable.Specification
import stellar.sdk.ArbitraryInput
import stellar.sdk.model.op.JsonSnippets

class TradeSpec extends Specification with ArbitraryInput with JsonSnippets {

  implicit val formats = Serialization.formats(NoTypeHints) + TradeDeserializer

  "trade" should {
    "parse from json" >> prop { trade: Trade =>

      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": ""},
           |    "base": {"href": "https://horizon.stellar.org/accounts/GCI7ILB37OFVHLLSA74UCXZFCTPEBJOZK7YCNBI7DKH7D76U4CRJBL2A"},
           |    "counter": {"href": "https://horizon.stellar.org/accounts/GDRFRGR2FDUFF2RI6PQE5KFSCJHGSEIOGET22R66XSATP3BYHZ46BPLO"},
           |    "operation": {"href": "https://horizon.stellar.org/operations/38583306127675393"}
           |  },
           |  "id": "${trade.id}",
           |  "paging_token": "38583306127675393-2",
           |  "ledger_close_time": "${formatter.format(trade.ledgerCloseTime)}",
           |  "offer_id": "${trade.offerId}",
           |  "base_offer_id": "${trade.baseOfferId}",
           |  "base_account": "${trade.baseAccount.accountId}",
           |  ${amountDocPortion(trade.baseAmount, "base_amount", "base_")}
           |  ${amountDocPortion(trade.counterAmount, "counter_amount", "counter_")}
           |  "counter_account": "${trade.counterAccount.accountId}",
           |  "counter_offer_id": "${trade.counterOfferId}",
           |  "base_is_seller": ${trade.baseIsSeller}
           |}
         """.stripMargin

      parse(doc).extract[Trade] mustEqual trade
    }
  }

} 
Example 32
Source File: AccountMergeOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, KeyPair}

class AccountMergeOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[AccountMergeOperation]] = Arbitrary(genTransacted(genAccountMergeOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "account merge operation" should {
    "serde via xdr string" >> prop { actual: AccountMergeOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: AccountMergeOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[AccountMergeOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account":"${op.operation.sourceAccount.get.accountId}",
           |  "type_i": 8,
           |  "type": "account_merge"
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "account": "${op.operation.sourceAccount.get.accountId}",
           |  "into": "${KeyPair.fromPublicKey(op.operation.destination.hash).accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[AccountMergeOperation]] mustEqual op
    }.setGen(genTransacted(genAccountMergeOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 33
Source File: SetOptionsOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class SetOptionsOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[SetOptionsOperation]] = Arbitrary(genTransacted(genSetOptionsOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "set options operation" should {
    "serde via xdr string" >> prop { actual: SetOptionsOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: SetOptionsOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded must beEquivalentTo(actual)
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[SetOptionsOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${opt("inflation_dest", op.operation.inflationDestination.map(_.accountId))}
           |  ${opt("home_domain", op.operation.homeDomain)}
           |  ${opt("master_key_weight", op.operation.masterKeyWeight)}
           |  ${opt("signer_key", op.operation.signer.map(_.key.encodeToChars.mkString))}
           |  ${opt("signer_weight", op.operation.signer.map(_.weight))}
           |  ${opt("set_flags", op.operation.setFlags.map(_.map(_.i)))}
           |  ${opt("set_flags_s", op.operation.setFlags.map(_.map(_.s)))}
           |  ${opt("clear_flags", op.operation.clearFlags.map(_.map(_.i)))}
           |  ${opt("clear_flags_s", op.operation.clearFlags.map(_.map(_.s)))}
           |  ${opt("low_threshold", op.operation.lowThreshold)}
           |  ${opt("med_threshold", op.operation.mediumThreshold)}
           |  ${opt("high_threshold", op.operation.highThreshold)}
           |  "type": "set_options",
           |  "type_i": 5,
           |}
         """.stripMargin

      parse(doc).extract[Transacted[SetOptionsOperation]] must beEquivalentTo(op)
    }.setGen(genTransacted(genSetOptionsOperation.suchThat(_.sourceAccount.nonEmpty)))
  }
} 
Example 34
Source File: PathPaymentStrictReceiveOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PathPaymentStrictReceiveOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PathPaymentStrictReceiveOperation]] = Arbitrary(genTransacted(genPathPaymentStrictReceiveOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "path payment operation" should {
    "serde via xdr string" >> prop { actual: PathPaymentStrictReceiveOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PathPaymentStrictReceiveOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PathPaymentStrictReceiveOperation] =>
      val doc =
        s"""
           |{
           |  "_links":{
           |    "self":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713"},
           |    "transaction":{"href":"https://horizon-testnet.stellar.org/transactions/a995af17837d1b53fb5782269250a36e9dbe74170260b46f2708e5f23f7c864a"},
           |    "effects":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713/effects"},
           |    "succeeds":{"href":"https://horizon-testnet.stellar.org/effects?order=desc&cursor=940258535411713"},
           |    "precedes":{"href":"https://horizon-testnet.stellar.org/effects?order=asc&cursor=940258535411713"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type":"path_payment",
           |  "type_i":2,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.destinationAmount)}
           |  ${amountDocPortion(op.operation.sendMax, "source_max", "source_")}
           |  "from":"${op.operation.sourceAccount.get.accountId}",
           |  "to":"${op.operation.destinationAccount.publicKey.accountId}",
           |  "path":[${if (op.operation.path.isEmpty) "" else op.operation.path.map(asset(_)).mkString("{", "},{", "}")}]
           |}
         """.stripMargin

      parse(doc).extract[Transacted[Operation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPathPaymentStrictReceiveOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PathPaymentStrictReceiveOperation]): Transacted[PathPaymentStrictReceiveOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 35
Source File: CreateAccountOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class CreateAccountOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[CreateAccountOperation]] = Arbitrary(genTransacted(genCreateAccountOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer + OperationDeserializer

  "create account operation" should {
    "serde via xdr string" >> prop { actual: CreateAccountOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: CreateAccountOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "be parsed from json " >> prop { op: Transacted[CreateAccountOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "create_account",
           |  "type_i": 0,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "starting_balance": "${amountString(op.operation.startingBalance)}",
           |  "funder": "${op.operation.sourceAccount.get.accountId}",
           |  "account": "${op.operation.destinationAccount.publicKey.accountId}"
           |}
         """.stripMargin

      parse(doc).extract[Transacted[CreateAccountOperation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genCreateAccountOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[CreateAccountOperation]): Transacted[CreateAccountOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 36
Source File: JsonSerializer.scala    From akka-serialization-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.serializer.json

import akka.serialization.Serializer
import com.github.dnvriend.domain.OrderDomain
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization._
import org.json4s.{ DefaultFormats, Formats, NoTypeHints }

case class EventWrapper(manifest: String, payload: String)

class JsonSerializer extends Serializer {

  implicit val formats: Formats = DefaultFormats + OrderDomain.DirectDebitTypeSerializer

  override def identifier: Int = Int.MaxValue

  override def includeManifest: Boolean = true

  override def toBinary(o: AnyRef): Array[Byte] =
    write(EventWrapper(o.getClass.getName, write(o))).getBytes()

  override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = {
    val wrapper: EventWrapper = parse(new String(bytes)).extract[EventWrapper]
    implicit val mf = Manifest.classType(Class.forName(wrapper.manifest))
    read(wrapper.payload)
  }
} 
Example 37
Source File: BumpSequenceOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class BumpSequenceOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[BumpSequenceOperation]] = Arbitrary(genTransacted(genBumpSequenceOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "bump sequence operation" should {
    "serde via xdr bytes" >> prop { actual: BumpSequenceOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "serde via xdr string" >> prop { actual: BumpSequenceOperation =>
      Operation.decodeXDR(ByteArrays.base64(actual.encode)) mustEqual actual
    }

    "parse from json" >> prop { op: Transacted[BumpSequenceOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "bump_sequence",
           |  "type_i": 11,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "bump_to": ${op.operation.bumpTo}
           |}
         """.stripMargin

      parse(doc).extract[Transacted[BumpSequenceOperation]] mustEqual op
    }.setGen(genTransacted(genBumpSequenceOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 38
Source File: CreatePassiveSellOfferOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class CreatePassiveSellOfferOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[CreatePassiveSellOfferOperation]] = Arbitrary(genTransacted(genCreatePassiveSellOfferOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer + OperationDeserializer

  "create passive offer operation" should {
    "serde via xdr string" >> prop { actual: CreatePassiveSellOfferOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: CreatePassiveSellOfferOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[CreatePassiveSellOfferOperation] =>
      val doc =
        s"""
           |{
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659137/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659137"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659137"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "create_passive_sell_offer",
           |  "type_i": 4,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.selling, assetPrefix = "selling_")},
           |  ${asset(op.operation.buying, "buying_")},
           |  "offer_id": 0,
           |  "price": "1.0",
           |  "price_r": {
           |    "d": ${op.operation.price.d},
           |    "n": ${op.operation.price.n}
           |  }
           |}
         """.stripMargin

      parse(doc).extract[Transacted[CreatePassiveSellOfferOperation]] mustEqual op
    }.setGen(genTransacted(genCreatePassiveSellOfferOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 39
Source File: PathPaymentStrictSendOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PathPaymentStrictSendOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PathPaymentStrictSendOperation]] = Arbitrary(genTransacted(genPathPaymentStrictSendOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "path payment operation" should {
    "serde via xdr string" >> prop { actual: PathPaymentStrictSendOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PathPaymentStrictSendOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PathPaymentStrictSendOperation] =>
      val doc =
        s"""
           |{
           |  "_links":{
           |    "self":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713"},
           |    "transaction":{"href":"https://horizon-testnet.stellar.org/transactions/a995af17837d1b53fb5782269250a36e9dbe74170260b46f2708e5f23f7c864a"},
           |    "effects":{"href":"https://horizon-testnet.stellar.org/operations/940258535411713/effects"},
           |    "succeeds":{"href":"https://horizon-testnet.stellar.org/effects?order=desc&cursor=940258535411713"},
           |    "precedes":{"href":"https://horizon-testnet.stellar.org/effects?order=asc&cursor=940258535411713"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type":"path_payment_strict_send",
           |  "type_i":13,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.sendAmount, assetPrefix = "source_")}
           |  ${amountDocPortion(op.operation.destinationMin, "destination_min")}
           |  "from":"${op.operation.sourceAccount.get.accountId}",
           |  "to":"${op.operation.destinationAccount.publicKey.accountId}",
           |  "path":[${if (op.operation.path.isEmpty) "" else op.operation.path.map(asset(_)).mkString("{", "},{", "}")}]
           |}
         """.stripMargin

      parse(doc).extract[Transacted[Operation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPathPaymentStrictSendOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PathPaymentStrictSendOperation]): Transacted[PathPaymentStrictSendOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 40
Source File: AllowTrustOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, KeyPair}

class AllowTrustOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[AllowTrustOperation]] = Arbitrary(genTransacted(genAllowTrustOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "allow trust operation" should {
    "serde via xdr string" >> prop { actual: AllowTrustOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: AllowTrustOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[AllowTrustOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "allow_trust",
           |  "type_i": 7,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  "asset_type": "${if (op.operation.assetCode.length <= 4) "credit_alphanum4" else "credit_alphanum12"}",
           |  "asset_code": "${op.operation.assetCode}",
           |  "asset_issuer": "${op.operation.sourceAccount.get.accountId}"
           |  "trustor": "${op.operation.trustor.accountId}",
           |  "trustee": "${op.operation.sourceAccount.get.accountId}",
           |  "authorize": ${op.operation.trustLineFlags.contains(TrustLineAuthorized)}
           |  "authorize_to_maintain_liabilities": ${op.operation.trustLineFlags.contains(TrustLineCanMaintainLiabilities)}
           |}
         """.stripMargin

      val parsed = parse(doc).extract[Transacted[AllowTrustOperation]]
      parsed mustEqual op
      parsed.operation.authorize mustEqual op.operation.authorize
      parsed.operation.authorizeToMaintainLiabilities mustEqual op.operation.authorizeToMaintainLiabilities
    }.setGen(genTransacted(genAllowTrustOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 41
Source File: ChangeTrustOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class ChangeTrustOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[ChangeTrustOperation]] = Arbitrary(genTransacted(genChangeTrustOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "change trust operation" should {
    "serde via xdr string" >> prop { actual: ChangeTrustOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: ChangeTrustOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[ChangeTrustOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "change_trust",
           |  "type_i": 6,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.limit, "limit")},
           |  "trustee": "${op.operation.limit.asset.issuer.accountId}",
           |  "trustor": "${op.operation.sourceAccount.get.accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[ChangeTrustOperation]] mustEqual op
    }.setGen(genTransacted(genChangeTrustOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 42
Source File: ManageDataOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.apache.commons.codec.binary.Base64
import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers, PublicKey}

class ManageDataOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arbDelete: Arbitrary[Transacted[DeleteDataOperation]] = Arbitrary(genTransacted(genDeleteDataOperation))
  implicit val arbWrite: Arbitrary[Transacted[WriteDataOperation]] = Arbitrary(genTransacted(genWriteDataOperation))
  implicit val formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  def doc[O <: ManageDataOperation](op: Transacted[O]) = {
    val dataValue = op.operation match {
      case WriteDataOperation(_, value, _) => Base64.encodeBase64String(value.toArray)
      case _ => ""
    }

    s"""
      |{
      |  "_links": {
      |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
      |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
      |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
      |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
      |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
      |  },
      |  "id": "${op.id}",
      |  "paging_token": "10157597659137",
      |  "source_account": "${op.operation.sourceAccount.get.accountId}",
      |  "type": "manage_data",
      |  "type_i": 1,
      |  "created_at": "${formatter.format(op.createdAt)}",
      |  "transaction_hash": "${op.txnHash}",
      |  "name": "${op.operation.name}",
      |  "value": "$dataValue"
      |}""".stripMargin
  }

  "a write data operation" should {
    "serde via xdr string" >> prop { actual: WriteDataOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: WriteDataOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded must beEquivalentTo(actual)
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[WriteDataOperation] =>
      parse(doc(op)).extract[Transacted[ManageDataOperation]] must beEquivalentTo(op)
    }.setGen(genTransacted(genWriteDataOperation.suchThat(_.sourceAccount.nonEmpty)))

    "encode a string payload as UTF-8 in base64" >> prop { (s: String, source: PublicKey) =>
      val value = new String(s.take(64).getBytes("UTF-8").take(60), "UTF-8")
      WriteDataOperation("name", value).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
      WriteDataOperation("name", value, None).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
      WriteDataOperation("name", value, Some(source)).value.toSeq mustEqual value.getBytes("UTF-8").toSeq
    }.setGen1(Arbitrary.arbString.arbitrary.suchThat(_.nonEmpty))

    "fail if the key is greater than 64 bytes" >> prop { s: String =>
      WriteDataOperation(s, "value") must throwAn[IllegalArgumentException]
    }.setGen(Gen.identifier.suchThat(_.getBytes("UTF-8").length > 64))

    "fail if the value is greater than 64 bytes" >> prop { s: String =>
      WriteDataOperation("name", s) must throwAn[IllegalArgumentException]
    }.setGen(Gen.identifier.suchThat(_.getBytes("UTF-8").length > 64))
  }

  "a delete data operation" should {
    "serde via xdr string" >> prop { actual: DeleteDataOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: DeleteDataOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[DeleteDataOperation] =>
      parse(doc(op)).extract[Transacted[ManageDataOperation]] mustEqual op
    }.setGen(genTransacted(genDeleteDataOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

} 
Example 43
Source File: PaymentOperationSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import org.json4s.{Formats, NoTypeHints}
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Arbitrary
import org.specs2.mutable.Specification
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{ArbitraryInput, DomainMatchers}

class PaymentOperationSpec extends Specification with ArbitraryInput with DomainMatchers with JsonSnippets {

  implicit val arb: Arbitrary[Transacted[PaymentOperation]] = Arbitrary(genTransacted(genPaymentOperation))
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + TransactedOperationDeserializer

  "payment operation" should {
    "serde via xdr string" >> prop { actual: PaymentOperation =>
      Operation.decodeXDR(base64(actual.encode)) must beEquivalentTo(actual)
    }

    "serde via xdr bytes" >> prop { actual: PaymentOperation =>
      val (remaining, decoded) = Operation.decode.run(actual.encode).value
      decoded mustEqual actual
      remaining must beEmpty
    }

    "parse from json" >> prop { op: Transacted[PaymentOperation] =>
      val doc =
        s"""
           | {
           |  "_links": {
           |    "self": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144"},
           |    "transaction": {"href": "https://horizon-testnet.stellar.org/transactions/17a670bc424ff5ce3b386dbfaae9990b66a2a37b4fbe51547e8794962a3f9e6a"},
           |    "effects": {"href": "https://horizon-testnet.stellar.org/operations/10157597659144/effects"},
           |    "succeeds": {"href": "https://horizon-testnet.stellar.org/effects?order=desc\u0026cursor=10157597659144"},
           |    "precedes": {"href": "https://horizon-testnet.stellar.org/effects?order=asc\u0026cursor=10157597659144"}
           |  },
           |  "id": "${op.id}",
           |  "paging_token": "10157597659137",
           |  "source_account": "${op.operation.sourceAccount.get.accountId}",
           |  "type": "payment",
           |  "type_i": 1,
           |  "created_at": "${formatter.format(op.createdAt)}",
           |  "transaction_hash": "${op.txnHash}",
           |  ${amountDocPortion(op.operation.amount)},
           |  "from": "${op.operation.sourceAccount.get.accountId}",
           |  "to": "${op.operation.destinationAccount.publicKey.accountId}",
           |}
         """.stripMargin

      parse(doc).extract[Transacted[PaymentOperation]] mustEqual removeDestinationSubAccountId(op)
    }.setGen(genTransacted(genPaymentOperation.suchThat(_.sourceAccount.nonEmpty)))
  }

  // Because sub accounts are not yet supported in Horizon JSON.
  private def removeDestinationSubAccountId(op: Transacted[PaymentOperation]): Transacted[PaymentOperation] = {
    op.copy(operation = op.operation.copy(destinationAccount = op.operation.destinationAccount.copy(subAccountId = None)))
  }
} 
Example 44
Source File: FeeStatsResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.specs2.mutable.Specification
import stellar.sdk.ArbitraryInput

class FeeStatsResponseSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + FeeStatsRespDeserializer

  "a fee stats response document" should {
    "parse to a fee stats response" >> prop { r: FeeStatsResponse =>
      val json =
        s"""
           |{
           |  "last_ledger": "${r.lastLedger}",
           |  "last_ledger_base_fee": "${r.lastLedgerBaseFee.units}",
           |  "ledger_capacity_usage": "${r.ledgerCapacityUsage}",
           |  "fee_charged": {
           |    "max": "${r.chargedFees.max.units}",
           |    "min": "${r.chargedFees.min.units}",
           |    "mode": "${r.chargedFees.mode.units}",
           |    "p10": "${r.chargedFees.percentiles(10).units}",
           |    "p20": "${r.chargedFees.percentiles(20).units}",
           |    "p30": "${r.chargedFees.percentiles(30).units}",
           |    "p40": "${r.chargedFees.percentiles(40).units}",
           |    "p50": "${r.chargedFees.percentiles(50).units}",
           |    "p60": "${r.chargedFees.percentiles(60).units}",
           |    "p70": "${r.chargedFees.percentiles(70).units}",
           |    "p80": "${r.chargedFees.percentiles(80).units}",
           |    "p90": "${r.chargedFees.percentiles(90).units}",
           |    "p95": "${r.chargedFees.percentiles(95).units}",
           |    "p99": "${r.chargedFees.percentiles(99).units}"
           |  },
           |  "max_fee": {
           |    "max": "${r.maxFees.max.units}",
           |    "min": "${r.maxFees.min.units}",
           |    "mode": "${r.maxFees.mode.units}",
           |    "p10": "${r.maxFees.percentiles(10).units}",
           |    "p20": "${r.maxFees.percentiles(20).units}",
           |    "p30": "${r.maxFees.percentiles(30).units}",
           |    "p40": "${r.maxFees.percentiles(40).units}",
           |    "p50": "${r.maxFees.percentiles(50).units}",
           |    "p60": "${r.maxFees.percentiles(60).units}",
           |    "p70": "${r.maxFees.percentiles(70).units}",
           |    "p80": "${r.maxFees.percentiles(80).units}",
           |    "p90": "${r.maxFees.percentiles(90).units}",
           |    "p95": "${r.maxFees.percentiles(95).units}",
           |    "p99": "${r.maxFees.percentiles(99).units}"
           |  }
           |}
         """.stripMargin

      val actual = parse(json).extract[FeeStatsResponse]
      actual mustEqual r
      actual.acceptedFeePercentiles mustEqual actual.chargedFees.percentiles
      actual.minAcceptedFee mustEqual actual.chargedFees.min
      actual.modeAcceptedFee mustEqual actual.chargedFees.mode
    }
  }

} 
Example 45
Source File: LedgerResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.time.ZoneId
import java.time.format.DateTimeFormatter

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.specs2.mutable.Specification
import stellar.sdk.ArbitraryInput

class LedgerResponseSpec extends Specification with ArbitraryInput {

  val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneId.of("UTC"))

  implicit val formats = Serialization.formats(NoTypeHints) + LedgerRespDeserializer

  "a ledger response document" should {
    "parse to a ledger response" >> prop { lr: LedgerResponse =>

      val json =
        s"""
           |{
           |  "_links": {
           |    "self": {
           |      "href": "http://horizon-testnet.stellar.org/ledgers/11"
           |    },
           |    "transactions": {
           |      "href": "http://horizon-testnet.stellar.org/ledgers/11/transactions{?cursor,limit,order}",
           |      "templated": true
           |    },
           |    "operations": {
           |      "href": "http://horizon-testnet.stellar.org/ledgers/11/operations{?cursor,limit,order}",
           |      "templated": true
           |    },
           |    "payments": {
           |      "href": "http://horizon-testnet.stellar.org/ledgers/11/payments{?cursor,limit,order}",
           |      "templated": true
           |    },
           |    "effects": {
           |      "href": "http://horizon-testnet.stellar.org/ledgers/11/effects{?cursor,limit,order}",
           |      "templated": true
           |    }
           |  },
           |  "id": "${lr.id}",
           |  "paging_token": "47244640256",
           |  "hash": "${lr.hash}",
           |  ${lr.previousHash.map(h => s""""prev_hash": "$h",""").getOrElse("")}
           |  "sequence": ${lr.sequence},
           |  "successful_transaction_count": ${lr.successTransactionCount},
           |  "failed_transaction_count": ${lr.failureTransactionCount},
           |  "operation_count": ${lr.operationCount},
           |  "closed_at": "${formatter.format(lr.closedAt)}",
           |  "total_coins": "${lr.totalCoins.toDisplayUnits}",
           |  "fee_pool": "${lr.feePool.toDisplayUnits}",
           |  "base_fee_in_stroops": ${lr.baseFee.units},
           |  "base_reserve_in_stroops": ${lr.baseReserve.units},
           |  "max_tx_set_size": ${lr.maxTxSetSize},
           |  "protocol_version": 4
           |}
        """.stripMargin

      parse(json).extract[LedgerResponse] must beLike { case actual: LedgerResponse =>
        actual.copy(closedAt = lr.closedAt) mustEqual lr
        actual.closedAt.toInstant.toEpochMilli mustEqual lr.closedAt.toInstant.toEpochMilli
      }
    }

    "calculate transaction count as sum of failed and successful transactions" >> prop { lr: LedgerResponse =>
      lr.transactionCount mustEqual lr.failureTransactionCount + lr.successTransactionCount
    }
  }

} 
Example 46
Source File: TradeEffectResponseSpec.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.util.Locale

import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods.parse
import org.json4s.native.Serialization
import org.scalacheck.Gen
import org.specs2.mutable.Specification
import stellar.sdk._
import stellar.sdk.model.{Amount, NonNativeAsset}

class TradeEffectResponseSpec extends Specification with ArbitraryInput {

  implicit val formats = Serialization.formats(NoTypeHints) + EffectResponseDeserializer

  "a trade effect document" should {
    "parse to a trade effect" >> prop {
      (id: String, offerId: Long, buyer: KeyPair, bought: Amount, seller: KeyPair, sold: Amount) =>
        val json = doc(id, offerId, buyer, bought, seller, sold)
        parse(json).extract[EffectResponse] mustEqual EffectTrade(id, offerId, buyer, bought, seller, sold)
    }.setGen1(Gen.identifier).setGen2(Gen.posNum[Long])
  }

  def doc(id: String, offerId: Long, buyer: PublicKeyOps, bought: Amount, seller: PublicKeyOps, sold: Amount) = {
    s""" {
        "_links": {
          "operation": {
            "href": "https://horizon-testnet.stellar.org/operations/31161168848490497"
          },
          "succeeds": {
            "href": "https://horizon-testnet.stellar.org/effects?order=desc&cursor=31161168848490497-2"
          },
          "precedes": {
            "href": "https://horizon-testnet.stellar.org/effects?order=asc&cursor=31161168848490497-2"
          }
        },
        "id": "$id",
        "paging_token": "31161168848490497-2",
        "account": "${buyer.accountId}",
        "type": "trade",
        "type_i": 33,
        "seller": "${seller.accountId}",
        "offer_id": $offerId,
        ${amountDocPortion(sold, sold = true)},
        ${amountDocPortion(bought, sold = false)}
      }"""
  }

  def amountDocPortion(amount: Amount, sold: Boolean): String = {
    val bs = if (sold) "sold" else "bought"
    amount.asset match {
      case nn: NonNativeAsset =>
        s""""${bs}_amount": "${amountString(amount)}",
           |"${bs}_asset_type": "${nn.typeString}",
           |"${bs}_asset_code": "${nn.code}",
           |"${bs}_asset_issuer": "${nn.issuer.accountId}"
        """.stripMargin.trim

      case _ =>
        s""""${bs}_amount": "${amountString(amount)}",
           |"${bs}_asset_type": "native"
        """.stripMargin.trim
    }
  }

  def amountString(a: Amount): String = "%.7f".formatLocal(Locale.ROOT, a.units / math.pow(10, 7))
}