io.circe.ParsingFailure Scala Examples
The following examples show how to use io.circe.ParsingFailure.
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: Versions.scala From daml with Apache License 2.0 | 6 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 object Versions { private val daSdkVersionKey = "da.sdk.version" private val errorMsg = s"Error: cannot determine DA SDK version, either specify it with '-D${daSdkVersionKey}=<VERSION>' or use 'daml.yaml' with configured 'sdk-version' field." val daSdkVersion: String = sys.props .get(daSdkVersionKey) .getOrElse( sdkVersionFromFile(new java.io.File("daml.yaml")).fold( error => { println(errorMsg); throw error }, identity ) ) println(s"$daSdkVersionKey = ${daSdkVersion: String}") private def sdkVersionFromFile(file: java.io.File): Either[io.circe.Error, String] = { import io.circe.yaml.parser import io.circe.ParsingFailure import scala.util.Try for { str <- Try(sbt.IO.read(file)).toEither.left.map(e => ParsingFailure(s"Cannot read file: $file", e)) yaml <- parser.parse(str) version <- yaml.hcursor.downField("sdk-version").as[String] } yield version } }
Example 2
Source File: Versions.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 object Versions { private val daSdkVersionKey = "da.sdk.version" private val errorMsg = s"Error: cannot determine DA SDK version, either specify it with '-D${daSdkVersionKey}=<VERSION>' or use 'daml.yaml' with configured 'sdk-version' field." val daSdkVersion: String = sys.props .get(daSdkVersionKey) .getOrElse( sdkVersionFromFile(new java.io.File("daml.yaml")).fold( error => { println(errorMsg); throw error }, identity ) ) println(s"$daSdkVersionKey = ${daSdkVersion: String}") private def sdkVersionFromFile(file: java.io.File): Either[io.circe.Error, String] = { import io.circe.yaml.parser import io.circe.ParsingFailure import scala.util.Try for { str <- Try(sbt.IO.read(file)).toEither.left.map(e => ParsingFailure(s"Cannot read file: $file", e)) yaml <- parser.parse(str) version <- yaml.hcursor.downField("sdk-version").as[String] } yield version } }
Example 3
Source File: Versions.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 object Versions { private val daSdkVersionKey = "da.sdk.version" private val errorMsg = s"Error: cannot determine DA SDK version, either specify it with '-D${daSdkVersionKey}=<VERSION>' or use 'daml.yaml' with configured 'sdk-version' field." val daSdkVersion: String = sys.props .get(daSdkVersionKey) .getOrElse( sdkVersionFromFile(new java.io.File("daml.yaml")).fold( error => { println(errorMsg); throw error }, identity ) ) println(s"$daSdkVersionKey = ${daSdkVersion: String}") private def sdkVersionFromFile(file: java.io.File): Either[io.circe.Error, String] = { import io.circe.yaml.parser import io.circe.ParsingFailure import scala.util.Try for { str <- Try(sbt.IO.read(file)).toEither.left.map(e => ParsingFailure(s"Cannot read file: $file", e)) yaml <- parser.parse(str) version <- yaml.hcursor.downField("sdk-version").as[String] } yield version } }
Example 4
Source File: Versions.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 object Versions { private val daSdkVersionKey = "da.sdk.version" private val errorMsg = s"Error: cannot determine DA SDK version, either specify it with '-D${daSdkVersionKey}=<VERSION>' or use 'daml.yaml' with configured 'sdk-version' field." val daSdkVersion: String = sys.props .get(daSdkVersionKey) .getOrElse( sdkVersionFromFile(new java.io.File("daml.yaml")).fold( error => { println(errorMsg); throw error }, identity ) ) println(s"$daSdkVersionKey = ${daSdkVersion: String}") private def sdkVersionFromFile(file: java.io.File): Either[io.circe.Error, String] = { import io.circe.yaml.parser import io.circe.ParsingFailure import scala.util.Try for { str <- Try(sbt.IO.read(file)).toEither.left.map(e => ParsingFailure(s"Cannot read file: $file", e)) yaml <- parser.parse(str) version <- yaml.hcursor.downField("sdk-version").as[String] } yield version } }
Example 5
Source File: Versions.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 object Versions { private val daSdkVersionKey = "da.sdk.version" private val errorMsg = s"Error: cannot determine DA SDK version, either specify it with '-D${daSdkVersionKey}=<VERSION>' or use 'daml.yaml' with configured 'sdk-version' field." val daSdkVersion: String = sys.props .get(daSdkVersionKey) .getOrElse( sdkVersionFromFile(new java.io.File("daml.yaml")).fold( error => { println(errorMsg); throw error }, identity ) ) println(s"$daSdkVersionKey = ${daSdkVersion: String}") private def sdkVersionFromFile(file: java.io.File): Either[io.circe.Error, String] = { import io.circe.yaml.parser import io.circe.ParsingFailure import scala.util.Try for { str <- Try(sbt.IO.read(file)).toEither.left.map(e => ParsingFailure(s"Cannot read file: $file", e)) yaml <- parser.parse(str) version <- yaml.hcursor.downField("sdk-version").as[String] } yield version } }
Example 6
Source File: SymmetricSerializationLaws.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import cats.Eq import cats.instances.either._ import cats.laws._ import cats.laws.discipline._ import io.circe.{ Decoder, Encoder, Json, ParsingFailure } import org.scalacheck.{ Arbitrary, Prop, Shrink } import org.typelevel.discipline.Laws trait SymmetricSerializationLaws { def printerRoundTrip[A: Eq: Encoder: Decoder]( parse: String => Either[ParsingFailure, Json], print: Json => String, a: A ): IsEq[Either[io.circe.Error, A]] = parse(print(Encoder[A].apply(a))).right.flatMap(_.as[A]) <-> Right(a) } object SymmetricSerializationLaws { def apply(): SymmetricSerializationLaws = new SymmetricSerializationLaws {} } trait SymmetricSerializationTests extends Laws { def laws: SymmetricSerializationLaws def symmetricPrinter[A: Eq: Arbitrary: Shrink: Encoder: Decoder]( print: Json => String, parse: String => Either[ParsingFailure, Json] ): RuleSet = new DefaultRuleSet( name = "printer", parent = None, "roundTrip" -> Prop.forAll { (a: A) => laws.printerRoundTrip(parse, print, a) } ) } object SymmetricSerializationTests { def apply[A: Eq: Arbitrary: Decoder: Encoder]( print: Json => String, parse: String => Either[ParsingFailure, Json] ): SymmetricSerializationTests = new SymmetricSerializationTests { val laws: SymmetricSerializationLaws = SymmetricSerializationLaws() symmetricPrinter[A](print, parse) } }
Example 7
Source File: HttpHelper.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.utils import io.circe.parser.parse import io.circe.{Json, ParsingFailure} import scalaj.http.{Http, HttpRequest, HttpResponse} class HttpHelper(apiUrl: Option[String], extraHeaders: Map[String, String]) { private lazy val connectionTimeoutMs = 2000 private lazy val readTimeoutMs = 5000 private val remoteUrl = apiUrl.getOrElse("https://api.codacy.com") + "/2.0" def get(endpoint: String): Either[ParsingFailure, Json] = { val headers: Map[String, String] = Map("Content-Type" -> "application/json") ++ extraHeaders val response: HttpResponse[String] = Http(s"$remoteUrl$endpoint").headers(headers).timeout(connectionTimeoutMs, readTimeoutMs).asString parse(response.body) } def post(endpoint: String, dataOpt: Option[Json] = None): Either[ParsingFailure, Json] = { val headers: Map[String, String] = dataOpt.fold(Map.empty[String, String]) { _ => Map("Content-Type" -> "application/json") } ++ extraHeaders val request: HttpRequest = dataOpt.map { data => Http(s"$remoteUrl$endpoint").postData(data.toString) }.getOrElse(Http(s"$remoteUrl$endpoint")) .method("POST") .headers(headers) .timeout(connectionTimeoutMs, readTimeoutMs) parse(request.asString.body) } }
Example 8
Source File: CirceYaml.scala From bazel-deps with MIT License | 5 votes |
package com.github.johnynek.bazel_deps import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import io.circe.jackson.CirceJsonModule import io.circe.{Decoder, Json, ParsingFailure, Parser} import scala.util.control.NonFatal object Yaml extends Parser { private[this] val mapper = new ObjectMapper(new YAMLFactory()).registerModule(CirceJsonModule) private[this] val factory = mapper.getFactory override def parse(input: String): Either[ParsingFailure, Json] = try { Right(mapper.readValue(factory.createParser(input), classOf[Json])) } catch { case NonFatal(error) => Left(ParsingFailure(error.getMessage, error)) } }
Example 9
Source File: CirceConfigLaws.scala From circe-config with Apache License 2.0 | 5 votes |
package io.circe.config import cats.instances.either._ import cats.laws._ import cats.laws.discipline._ import io.circe.{Decoder, Json, Parser, ParsingFailure} import io.circe.testing.ParserTests import org.scalatest.flatspec.AnyFlatSpec import org.scalatestplus.scalacheck.Checkers import org.scalacheck.{Arbitrary, Prop} import org.typelevel.discipline.Laws import com.typesafe.config.{parser => _, _} class CirceConfigLaws extends AnyFlatSpec { implicit val arbitraryConfigJson: Arbitrary[Json] = Arbitrary { def normalize(json: Json): Json = json.mapObject(_.filterKeys(_.nonEmpty).mapValues(normalize)).mapArray(_.map(normalize)).mapNumber { number => // Lower the precision to the types used internally by // Lightbend Config to ensure that numbers are representable. val double: java.lang.Double = number.toDouble val long: java.lang.Long = double.toLong val json = if (double.isInfinite) // While +/+Infinity can be represented, it cannot be round-tripped. Json.fromInt(42) else if (long == double) // Emulate Lightbend Config's internal cast: // https://github.com/lightbend/config/blob/v1.3.4/config/src/main/java/com/typesafe/config/impl/ConfigNumber.java#L96-L104 Json.fromLong(long) else Json.fromDouble(double).get json.asNumber.get } for (jsonObject <- io.circe.testing.instances.arbitraryJsonObject.arbitrary) yield normalize(Json.fromJsonObject(jsonObject)) } def checkLaws(name: String, ruleSet: Laws#RuleSet): Unit = ruleSet.all.properties.zipWithIndex.foreach { case ((id, prop), 0) => name should s"obey $id" in Checkers.check(prop) case ((id, prop), _) => it should s"obey $id" in Checkers.check(prop) } checkLaws("Parser", ParserTests(parser).fromString) checkLaws( "Parser", ParserTests(parser).fromFunction[Config]("fromConfig")( ConfigFactory.parseString, _.parse, _.decode[Json], _.decodeAccumulating[Json] ) ) checkLaws("Printer", PrinterTests(parser).fromJson) checkLaws("Codec", CodecTests[Config](syntax.configDecoder, parser.parse).fromFunction("fromConfig")) } case class PrinterTests(parser: Parser) extends Laws { def fromJson(implicit A: Arbitrary[Json]): RuleSet = new DefaultRuleSet( name = "printer", parent = None, "roundTrip" -> Prop.forAll { (json: Json) => parser.parse(printer.print(json)) <-> Right(json) } ) } case class CodecTests[A](decoder: Decoder[A], parse: A => Either[ParsingFailure, Json]) extends Laws { def fromFunction(name: String)(implicit arbitraryJson: Arbitrary[Json]): RuleSet = new DefaultRuleSet( name = s"codec[$name]", parent = None, "decodingRoundTrip" -> Prop.forAll { (json: Json) => decoder.decodeJson(json).flatMap(parse) <-> Right(json) } ) }
Example 10
Source File: DefaultRepositoriesSpec.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos.repository import com.mesosphere.cosmos.repository.DefaultRepositories._ import com.mesosphere.cosmos.rpc.v1.model.PackageRepository import io.lemonlabs.uri.dsl._ import com.twitter.util.Return import io.circe.ParsingFailure import org.scalatest.FreeSpec class DefaultRepositoriesSpec extends FreeSpec { val repo1 = PackageRepository("repo1", "http://someplace/repo1") val repo2 = PackageRepository("repo2", "http://someplace/repo2") val repo3 = PackageRepository("repo3", "http://someplace/repo3") "DefaultRepositories for" - { "empty-list.json should" - { val emptyList = new DefaultRepositories("/com/mesosphere/cosmos/repository/empty-list.json") "property load" in { val expected = List() assertResult(expected)(emptyList.getOrThrow) } } "repos.json should" - { val repos = new DefaultRepositories("/com/mesosphere/cosmos/repository/repos.json") "property load" in { val expected = List(repo1, repo2, repo3) assertResult(expected)(repos.getOrThrow) } } "malformed.json should" - { val malformed = new DefaultRepositories("/com/mesosphere/cosmos/repository/malformed.json") "collect an error" in { val Return(xor) = malformed.get() assert(xor.isLeft) } "throw an error for a getOrThrow()" in { try { val _ = malformed.getOrThrow } catch { case ParsingFailure(_, _) => // expected } } "return a default for a getOrElse()" in { val actual = malformed.getOrElse(List(repo1)) val expected = List(repo1) assertResult(expected)(actual) } } "non-existent resource should" - { "throw IllegalStateException" in { try { val _ = new DefaultRepositories("/does/not/exist").getOrThrow } catch { case _: IllegalStateException => // expected } } } "default-repositories.json should load" in { val defaults = DefaultRepositories().getOrThrow assertResult(List(PackageRepository("default", "http://default")))(defaults) } } }
Example 11
Source File: Decoders.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos.circe import cats.syntax.either._ import com.mesosphere.cosmos.error.JsonDecodingError import com.mesosphere.cosmos.error.JsonParsingError import com.mesosphere.cosmos.finch.MediaTypedDecoder import com.mesosphere.error.Result import com.mesosphere.error.ResultOps import com.mesosphere.http.MediaType import io.lemonlabs.uri.Uri import io.circe.Decoder import io.circe.DecodingFailure import io.circe.Error import io.circe.Json import io.circe.ParsingFailure import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util.Base64 import scala.reflect.ClassTag import scala.reflect.classTag object Decoders { implicit val decodeUri: Decoder[Uri] = Decoder.decodeString.map(Uri.parse) implicit val decodeString: Decoder[String] = { Decoder.decodeString.withErrorMessage("String value expected") } implicit val decodeByteBuffer: Decoder[ByteBuffer] = Decoder.instance { c => c.as[String].bimap( { _ => DecodingFailure("Base64 string value expected", c.history) }, { s => ByteBuffer.wrap(Base64.getDecoder.decode(s)) } ) } def decode[T: Decoder: ClassTag](value: String): Result[T] = { convertToCosmosError(io.circe.jawn.decode[T](value), value) } def mediaTypedDecode[T: ClassTag]( value: String, mediaType: MediaType )( implicit decoder: MediaTypedDecoder[T] ): Result[T] = { for { json <- parse(value) result <- decoder( json.hcursor, mediaType ) } yield result } def parse(value: String): Result[Json] = { convertToCosmosError(io.circe.jawn.parse(value), value) } def decode64[T: Decoder: ClassTag](value: String): T = { decode[T](base64DecodeString(value)).getOrThrow } def parse64(value: String): Json = { parse(base64DecodeString(value)).getOrThrow } def convertToCosmosError[T: ClassTag]( result: Either[Error, T], inputValue: String ): Result[T] = result match { case Right(value) => Right(value) case Left(ParsingFailure(message, underlying)) => Left( JsonParsingError( underlying.getClass.getName, message, inputValue ) ) case Left(DecodingFailure(message, _)) => Left( JsonDecodingError( classTag[T].runtimeClass.getName, message, inputValue ) ) } private[this] def base64DecodeString(value: String): String = { new String(Base64.getDecoder.decode(value), StandardCharsets.UTF_8) } }
Example 12
Source File: MappingSetting.scala From elastic-indexer4s with MIT License | 5 votes |
package com.yannick_cw.elastic_indexer4s.elasticsearch.elasic_config import com.sksamuel.elastic4s.analyzers.AnalyzerDefinition import com.sksamuel.elastic4s.mappings.MappingDefinition import io.circe.{Json, ParsingFailure} import io.circe.parser.parse sealed trait MappingSetting { def fold[A](typed: TypedMappingSetting => A, unsafe: StringMappingSetting => A): A } case class TypedMappingSetting( analyzer: List[AnalyzerDefinition] = List.empty, mappings: List[MappingDefinition] = List.empty, shards: Option[Int] = None, replicas: Option[Int] = None ) extends MappingSetting { def fold[A](typed: (TypedMappingSetting) => A, unsafe: (StringMappingSetting) => A): A = typed(this) } sealed abstract case class StringMappingSetting(source: Json) extends MappingSetting { def fold[A](typed: (TypedMappingSetting) => A, unsafe: (StringMappingSetting) => A): A = unsafe(this) } object StringMappingSetting { def unsafeString(source: String): Either[ParsingFailure, MappingSetting] = parse(source).map(json => new StringMappingSetting(json) {}) }
Example 13
Source File: JacksonParser.scala From circe-jackson with Apache License 2.0 | 5 votes |
package io.circe.jackson import cats.data.ValidatedNel import io.circe.{ Decoder, Error, Json, Parser, ParsingFailure } import java.io.File import scala.util.control.NonFatal trait JacksonParser extends Parser { this: WithJacksonMapper => final def parse(input: String): Either[ParsingFailure, Json] = try { Right(mapper.readValue(jsonStringParser(input), classOf[Json])) } catch { case NonFatal(error) => Left(ParsingFailure(error.getMessage, error)) } final def parseFile(file: File): Either[ParsingFailure, Json] = try { Right(mapper.readValue(jsonFileParser(file), classOf[Json])) } catch { case NonFatal(error) => Left(ParsingFailure(error.getMessage, error)) } final def parseByteArray(bytes: Array[Byte]): Either[ParsingFailure, Json] = try { Right(mapper.readValue(jsonBytesParser(bytes), classOf[Json])) } catch { case NonFatal(error) => Left(ParsingFailure(error.getMessage, error)) } final def decodeByteArray[A: Decoder](bytes: Array[Byte]): Either[Error, A] = finishDecode[A](parseByteArray(bytes)) final def decodeByteArrayAccumulating[A: Decoder](bytes: Array[Byte]): ValidatedNel[Error, A] = finishDecodeAccumulating[A](parseByteArray(bytes)) final def decodeFile[A: Decoder](file: File): Either[Error, A] = finishDecode[A](parseFile(file)) final def decodeFileAccumulating[A: Decoder](file: File): ValidatedNel[Error, A] = finishDecodeAccumulating[A](parseFile(file)) }