com.fasterxml.jackson.core.JsonProcessingException Scala Examples

The following examples show how to use com.fasterxml.jackson.core.JsonProcessingException. 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: CustomJson.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.json

import java.io.IOException

import akka.http.scaladsl.model.MediaType
import akka.http.scaladsl.model.MediaTypes.`application/json`
import com.fasterxml.jackson.core.io.SegmentedStringWriter
import com.fasterxml.jackson.core.util.BufferRecyclers
import com.fasterxml.jackson.core.{JsonGenerator, JsonProcessingException}
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonMappingException, JsonSerializer, ObjectMapper, SerializerProvider}
import play.api.libs.json._

object NumberAsStringSerializer extends JsonSerializer[JsValue] {

  private val fieldNamesToTranslate = Set(
    "amount",
    "available",
    "balance",
    "buyMatcherFee",
    "currentReward",
    "desiredReward",
    "effective",
    "fee",
    "feeAmount",
    "generating",
    "in",
    "matcherFee",
    "minIncrement",
    "minSponsoredAssetFee",
    "out",
    "price",
    "quantity",
    "regular",
    "reward",
    "sellMatcherFee",
    "sponsorBalance",
    "totalAmount",
    "totalFee",
    "totalWavesAmount",
    "value"
  )

  override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = {
    value match {
      case JsNumber(v)  => json.writeNumber(v.bigDecimal)
      case JsString(v)  => json.writeString(v)
      case JsBoolean(v) => json.writeBoolean(v)

      case JsArray(elements) =>
        json.writeStartArray()
        elements.foreach { t =>
          serialize(t, json, provider)
        }
        json.writeEndArray()

      case JsObject(values) =>
        json.writeStartObject()
        values.foreach {
          case (name, JsNumber(v)) if fieldNamesToTranslate(name) =>
            json.writeStringField(name, v.bigDecimal.toPlainString)
          case (name, jsv) =>
            json.writeFieldName(name)
            serialize(jsv, json, provider)
        }
        json.writeEndObject()

      case JsNull => json.writeNull()
    }
  }
}

object CustomJson {

  val jsonWithNumbersAsStrings: MediaType.WithFixedCharset = `application/json`.withParams(Map("large-significand-format" -> "string"))

  private lazy val mapper = (new ObjectMapper)
    .registerModule(new SimpleModule("WavesJson").addSerializer(classOf[JsValue], NumberAsStringSerializer))
    .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)

  def writeValueAsString(value: JsValue): String = {
    val sw = new SegmentedStringWriter(BufferRecyclers.getBufferRecycler)
    try mapper.writeValue(sw, value)
    catch {
      case e: JsonProcessingException =>
        throw e
      case e: IOException =>
        // shouldn't really happen, but is declared as possibility so:
        throw JsonMappingException.fromUnexpectedIOE(e)
    }
    sw.getAndClear
  }
} 
Example 2
Source File: ThirdPartyOverridesReaderTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.bazel

import com.fasterxml.jackson.core.JsonProcessingException
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class ThirdPartyOverridesReaderTest extends SpecificationWithJUnit {
  "ThirdPartyOverridesReader" should {
    trait ctx extends Scope{
      def someRuntimeOverrides = someOverrides("runtime")
      def someCompileTimeOverrides = someOverrides("compile")
      def someOverrides(classifier: String) = Some({
        {1 to 10}
          .map(index => OverrideCoordinates("com.example", s"some-artifact$index-$classifier") -> Set(s"label$index-$classifier"))
          .toMap
      })
    }

    "throw parse exception given invalid overrides json string" in {
      ThirdPartyOverridesReader.from("{invalid") must throwA[JsonProcessingException]
    }

    "read third party overrides from generated json" in new ctx {
      val originalOverrides = ThirdPartyOverrides(someRuntimeOverrides, someCompileTimeOverrides)
      val json = {
        val objectMapper = ThirdPartyOverridesReader.mapper
        objectMapper.writeValueAsString(originalOverrides)
      }

      val readOverrides = ThirdPartyOverridesReader.from(json)

      readOverrides mustEqual originalOverrides
    }

    "read third party overrides from manual json" in {
      val overrides = ThirdPartyOverridesReader.from(
        """{
          |  "runtimeOverrides" : {
          |  "com.example:an-artifact" :
          |   ["some-label"],
          |  "other.example:other-artifact" :
          |   ["other-label"]
          |  },
          |  "compileTimeOverrides" : {
          |  "com.example:an-artifact" :
          |   ["some-label"],
          |  "other.example:other-artifact" :
          |   ["other-label"]
          |  }
          |}""".stripMargin)

      overrides.runtimeDependenciesOverridesOf(OverrideCoordinates("com.example","an-artifact")) must contain("some-label")
      overrides.runtimeDependenciesOverridesOf(OverrideCoordinates("other.example","other-artifact")) must contain("other-label")

      overrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("com.example","an-artifact")) must contain("some-label")
      overrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("other.example","other-artifact")) must contain("other-label")
    }

    "fail when OverrideCoordinates key is in bad format" in {
      ThirdPartyOverridesReader.from(
        """{
          |  "runtimeOverrides" : {
          |  "com" :
          |   ["some-label"],
          |}""".stripMargin) must throwA[JsonProcessingException]("OverrideCoordinates.*groupId:artifactId")
    }

    "have sensible defaults when reading an empty json object to support specifying either compile/runtime on their own" in {
      val partialOverrides = ThirdPartyOverridesReader.from("{}")

      (partialOverrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("foo","bar")) must beEmpty) and
      (partialOverrides.runtimeDependenciesOverridesOf(OverrideCoordinates("foo","bar")) must beEmpty)
    }

  }

} 
Example 3
Source File: InternalTargetOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

class InternalTargetOverridesReaderIT extends SpecificationWithJUnit {
  "read" should {
    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("invl:")

      InternalTargetOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }
    "default to no overrides when trying to read an non existent overrides file" in new Context {
      InternalTargetOverridesReader.from(repoRoot).targetOverrides must beEmpty
    }

    "read empty overrides" in new Context {
      val label = "//some/path/to/target:target"

      writeOverrides(
        s"""|{
            |  "targetOverrides" : [ {
            |      "label" : "$label"
            |  } ]
            |}""".stripMargin
      )

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label)))
      )
    }

    "read docker image dep from manual json" in new Context {
      val label = "//some/path/to/target:target"
      val dockerImage = "docker-repo/docker-image:t.a.g"

      writeOverrides(
        s"""{
           |  "targetOverrides" : [ {
           |      "label" : "$label",
           |      "dockerImagesDeps" : [ "$dockerImage" ]
           |  } ]
           |}""".stripMargin)

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label, dockerImagesDeps = Option(List(dockerImage))))))
    }

    "read block network from manual json" in new Context {
      val label = "//some/path/to/target:target"
      val blockNetwork = false

      writeOverrides(
        s"""{
           |  "targetOverrides" : [ {
           |      "label" : "$label",
           |      "blockNetwork" : $blockNetwork
           |  } ]
           |}""".stripMargin)

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label, blockNetwork = Some(blockNetwork)))))
    }
  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    override val overridesPath: Path = setupOverridesPath(repoRoot, "internal_targets.overrides")
  }

} 
Example 4
Source File: GeneratedCodeLinksOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import com.wix.bazel.migrator
import com.wixpress.build.maven.{Coordinates, MavenMakers}
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class GeneratedCodeLinksOverridesReaderIT extends SpecificationWithJUnit {
  "read" should {
    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("invl:")

      GeneratedCodeOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "read overrides from manual json" in new Context {
      val generatedFile = "com/wixpress/Foo.scala"
      val sourceFile = "com/wixpress/foo.proto"
      writeOverrides(
        s"""{
           |  "links" : [ {
           |      "groupId" : "${module.groupId}",
           |      "artifactId" : "${module.artifactId}",
           |      "generatedFile" : "$generatedFile",
           |      "sourceFile" : "$sourceFile"
           |  } ]
           |}""".stripMargin)

      GeneratedCodeOverridesReader.from(repoRoot) must beEqualTo(GeneratedCodeLinksOverrides(Seq(
        GeneratedCodeLink(module.groupId, module.artifactId, generatedFile, sourceFile))))
    }

    "read overrides from generated json" in new Context {
      val overrides = multipleOverrides
      writeOverrides(objectMapper.writeValueAsString(overrides))

      GeneratedCodeOverridesReader.from(repoRoot) must beEqualTo(overrides)
    }

    "default to no overrides when trying to read an non existent overrides file" in new Context {
      GeneratedCodeOverridesReader.from(repoRoot).links must beEmpty
    }

  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    val module: Coordinates = MavenMakers.someCoordinates("some-module")
    override val overridesPath: Path = setupOverridesPath(repoRoot, "code_paths.overrides")

    def multipleOverrides: GeneratedCodeLinksOverrides = {
      val overrides = (1 to 20).map { index =>
        GeneratedCodeLink(
          groupId = module.groupId,
          artifactId = module.artifactId,
          generatedFile = s"com/wixpress/Foo$index.scala",
          sourceFile = s"com/wixpress/foo$index.proto"
        )
      }
      migrator.overrides.GeneratedCodeLinksOverrides(overrides)
    }
  }

} 
Example 5
Source File: SourceModulesOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import com.fasterxml.jackson.core.JsonProcessingException
import com.wix.build.maven.analysis.SourceModulesOverrides
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class SourceModulesOverridesReaderIT extends SpecificationWithJUnit {
  "SourceModulesOverridesReader" should {

    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("{invalid")

      SourceModulesOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "read overrides from generated json" in new Context {
      val originalOverrides = SourceModulesOverrides(mutedModules)
      writeOverrides(objectMapper.writeValueAsString(originalOverrides))

      SourceModulesOverridesReader.from(repoRoot) mustEqual originalOverrides
    }

    "read overrides from manual json" in new Context {
      writeOverrides("""{
          |  "modulesToMute" : [
          |   "some/path/to/module/one",
          |   "other/path"
          |  ]
          |}""".stripMargin)

      val overrides = SourceModulesOverridesReader.from(repoRoot)

      overrides.modulesToMute must contain("some/path/to/module/one", "other/path")
    }

    "default to no overrides when trying to read an non existent overrides file" in new Context {
      val partialOverrides = SourceModulesOverridesReader.from(repoRoot)

      partialOverrides.modulesToMute must beEmpty
    }

  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    override val overridesPath = setupOverridesPath(repoRoot, "source_modules.overrides")

    def mutedModules: Set[String] =
      { 1 to 10 }
        .map {
          index =>
            s"module$index"
        }.toSet

  }

} 
Example 6
Source File: MavenArchiveTargetsOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wixpress.build.bazel.OverrideCoordinates
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope


class MavenArchiveTargetsOverridesReaderIT extends SpecificationWithJUnit {
  "MavenArchiveTargetsOverridesReader" should {

    "return empty set in case override file does not exists" in {
      lazy val fileSystem = MemoryFileSystemBuilder.newLinux().build()
      val repoRoot: Path = fileSystem.getPath("repoRoot")
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set.empty)
    }

    "throw exception in case of invalid json" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      writeOverrides("blabla")

      MavenArchiveTargetsOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "return empty set in case of empty array in the json" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      val json = s"""|{
                     |  "unpackedOverridesToArchive" : []
                     |}""".stripMargin
      writeOverrides(json)
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set.empty)
    }

    "return set of maven archive coordinates to override" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      val json = s"""{
                     |  "unpackedOverridesToArchive": [
                     |    {
                     |      "groupId": "some-group",
                     |      "artifactId": "some-artifact-id"
                     |    },
                     |    {
                     |      "groupId": "another-group",
                     |      "artifactId": "another-artifact-id"
                     |    }
                     |  ]
                     |}""".stripMargin

      writeOverrides(json)
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set(
        OverrideCoordinates("some-group", "some-artifact-id"),
        OverrideCoordinates("another-group", "another-artifact-id")))
    }
  }
  trait ctx extends Scope with OverridesReaderITSupport
} 
Example 7
Source File: CustomJson.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.http

import java.io.IOException

import akka.http.scaladsl.model.{MediaRange, MediaType}
import akka.http.scaladsl.model.MediaTypes.`application/json`
import com.fasterxml.jackson.core.io.SegmentedStringWriter
import com.fasterxml.jackson.core.util.BufferRecyclers
import com.fasterxml.jackson.core.{JsonGenerator, JsonProcessingException}
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonMappingException, JsonSerializer, ObjectMapper, SerializerProvider}
import play.api.libs.json._

object NumberAsStringSerializer extends JsonSerializer[JsValue] {
  private val fieldNamesToTranslate = Set(
    "amount",
    "available",
    "balance",
    "buyMatcherFee",
    "currentReward",
    "desiredReward",
    "effective",
    "fee",
    "feeAmount",
    "generating",
    "in",
    "matcherFee",
    "minIncrement",
    "minSponsoredAssetFee",
    "out",
    "price",
    "quantity",
    "regular",
    "reward",
    "sellMatcherFee",
    "sponsorBalance",
    "totalAmount",
    "totalFee",
    "totalWavesAmount",
    "value"
  )

  override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = {
    value match {
      case JsNumber(v)  => json.writeNumber(v.bigDecimal)
      case JsString(v)  => json.writeString(v)
      case JsBoolean(v) => json.writeBoolean(v)

      case JsArray(elements) =>
        json.writeStartArray()
        elements.foreach { t =>
          serialize(t, json, provider)
        }
        json.writeEndArray()

      case JsObject(values) =>
        json.writeStartObject()
        values.foreach {
          case (name, JsNumber(v)) if fieldNamesToTranslate(name) =>
            json.writeStringField(name, v.bigDecimal.toPlainString)
          case (name, jsv) =>
            json.writeFieldName(name)
            serialize(jsv, json, provider)
        }
        json.writeEndObject()

      case JsNull => json.writeNull()
    }
  }
}

object CustomJson {
  val jsonWithNumbersAsStrings: MediaType.WithFixedCharset = `application/json`.withParams(Map("large-significand-format" -> "string"))

  def acceptsNumbersAsStrings(mr: MediaRange): Boolean = mr match {
    case MediaRange.One(`jsonWithNumbersAsStrings`, _) => true
    case _                                             => false
  }

  private lazy val mapper = (new ObjectMapper)
    .registerModule(new SimpleModule("WavesJson").addSerializer(classOf[JsValue], NumberAsStringSerializer))
    .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)

  def writeValueAsString(value: JsValue): String = {
    val sw = new SegmentedStringWriter(BufferRecyclers.getBufferRecycler)
    try mapper.writeValue(sw, value)
    catch {
      case e: JsonProcessingException =>
        throw e
      case e: IOException =>
        // shouldn't really happen, but is declared as possibility so:
        throw JsonMappingException.fromUnexpectedIOE(e)
    }
    sw.getAndClear
  }
}