io.circe.HCursor Scala Examples
The following examples show how to use io.circe.HCursor.
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: Analyzer.scala From scarango with MIT License | 8 votes |
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, DecodingFailure, Encoder, HCursor, Json} sealed abstract class Analyzer(val name: String) object Analyzer { case object Identity extends Analyzer("identity") case object TextGerman extends Analyzer("text_de") case object TextEnglish extends Analyzer("text_en") case object TextSpanish extends Analyzer("text_es") case object TextFinnish extends Analyzer("text_fi") case object TextFrench extends Analyzer("text_fr") case object TextItalian extends Analyzer("text_it") case object TextDutch extends Analyzer("text_nl") case object TextNorwegian extends Analyzer("text_no") case object TextPortuguese extends Analyzer("text_pt") case object TextRussian extends Analyzer("text_ru") case object TextSwedish extends Analyzer("text_sv") case object TextChinese extends Analyzer("text_zh") private val map = List(Identity, TextGerman, TextEnglish, TextSpanish, TextFinnish, TextFrench, TextItalian, TextDutch, TextNorwegian, TextPortuguese, TextRussian, TextSwedish, TextChinese).map(a => a.name -> a).toMap def apply(name: String): Analyzer = map.getOrElse(name, throw new RuntimeException(s"Unable to find analyzer by name: $name")) implicit val decoder: Decoder[Analyzer] = new Decoder[Analyzer] { override def apply(c: HCursor): Result[Analyzer] = c.value.asString match { case Some(s) => Right(Analyzer(s)) case None => Left(DecodingFailure(s"Expected String to decode Analyzer, but got: ${c.value}", Nil)) } } implicit val encoder: Encoder[Analyzer] = new Encoder[Analyzer] { override def apply(a: Analyzer): Json = Json.fromString(a.name) } }
Example 2
package com.mesosphere.universe.v3.model import com.mesosphere.cosmos.circe.Decoders._ import com.twitter.util.Return import com.twitter.util.Throw import com.twitter.util.Try import io.circe.syntax.EncoderOps import io.circe.Decoder import io.circe.DecodingFailure import io.circe.Encoder import io.circe.HCursor import java.util.regex.Pattern final class Tag private(val value: String) extends AnyVal { override def toString: String = value } object Tag { val packageDetailsTagRegex: String = "^[^\\s]+$" val packageDetailsTagPattern: Pattern = Pattern.compile(packageDetailsTagRegex) def apply(s: String): Tag = validate(s).get def validate(s: String): Try[Tag] = { if (packageDetailsTagPattern.matcher(s).matches()) { Return(new Tag(s)) } else { Throw(new IllegalArgumentException( s"Value '$s' does not conform to expected format $packageDetailsTagRegex" )) } } implicit val encodePackageDefinitionTag: Encoder[Tag] = { Encoder.instance(_.value.asJson) } implicit val decodePackageDefinitionTag: Decoder[Tag] = Decoder.instance[Tag] { (c: HCursor) => c.as[String].map(validate(_)).flatMap { case Return(r) => Right(r) case Throw(ex) => val msg = ex.getMessage.replaceAllLiterally("assertion failed: ", "") Left(DecodingFailure(msg, c.history)) } } }
Example 3
Source File: EnumerationDecoder.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.decoding import io.circe.{ Decoder, DecodingFailure, HCursor } import io.circe.generic.extras.Configuration import scala.annotation.implicitNotFound import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness } import shapeless.labelled.{ FieldType, field } @implicitNotFound( """Could not find EnumerationDecoder for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class EnumerationDecoder[A] extends Decoder[A] object EnumerationDecoder { implicit val decodeEnumerationCNil: EnumerationDecoder[CNil] = new EnumerationDecoder[CNil] { def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history)) } implicit def decodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit witK: Witness.Aux[K], gen: LabelledGeneric.Aux[V, HNil], decodeR: EnumerationDecoder[R], config: Configuration = Configuration.default ): EnumerationDecoder[FieldType[K, V] :+: R] = new EnumerationDecoder[FieldType[K, V] :+: R] { def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] = c.as[String] match { case Right(s) if s == config.transformConstructorNames(witK.value.name) => Right(Inl(field[K](gen.from(HNil)))) case Right(_) => decodeR.apply(c) match { case Right(v) => Right(Inr(v)) case Left(err) => Left(err) } case Left(err) => Left(DecodingFailure("Enumeration", c.history)) } } implicit def decodeEnumeration[A, Repr <: Coproduct](implicit gen: LabelledGeneric.Aux[A, Repr], decodeR: EnumerationDecoder[Repr] ): EnumerationDecoder[A] = new EnumerationDecoder[A] { def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match { case Right(v) => Right(gen.from(v)) case Left(err) => Left(err) } } }
Example 4
Source File: CirceStreamSupport.scala From akka-stream-json with Apache License 2.0 | 5 votes |
package de.knutwalker.akka.stream package support import akka.NotUsed import akka.stream.scaladsl.Flow import akka.util.ByteString import io.circe.CursorOp.DownField import io.circe.jawn.CirceSupportParser._ import io.circe.{ CursorOp, Decoder, DecodingFailure, Encoder, HCursor, Json, Printer } import jawn.AsyncParser object CirceStreamSupport extends CirceStreamSupport trait CirceStreamSupport { def decode[A: Decoder]: Flow[ByteString, A, NotUsed] = JsonStreamParser.flow[Json].map(decodeJson[A]) def decode[A: Decoder](mode: AsyncParser.Mode): Flow[ByteString, A, NotUsed] = JsonStreamParser.flow[Json](mode).map(decodeJson[A]) def encode[A](implicit A: Encoder[A], P: Printer = Printer.noSpaces): Flow[A, String, NotUsed] = Flow[A].map(a => P.pretty(A(a))) case class JsonParsingException(df: DecodingFailure, cursor: HCursor) extends Exception(errorMessage(df.history, cursor, df.message), df) private[knutwalker] def decodeJson[A](json: Json)(implicit decoder: Decoder[A]): A = { val cursor = json.hcursor decoder(cursor) match { case Right(e) => e case Left(f) => throw JsonParsingException(f, cursor) } } private[this] def errorMessage(hist: List[CursorOp], cursor: HCursor, typeHint: String) = { val ac = cursor.replay(hist) if (ac.failed && lastWasDownField(hist)) { s"The field [${CursorOp.opsToPath(hist)}] is missing." } else { s"Could not decode [${ac.focus.getOrElse(Json.Null)}] at [${CursorOp.opsToPath(hist)}] as [$typeHint]." } } private[this] def lastWasDownField(hist: List[CursorOp]) = hist.headOption match { case Some(DownField(_)) => true case _ => false } }
Example 5
Source File: DcosVersion.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos.thirdparty.adminrouter.model import com.mesosphere.universe import io.circe.Decoder import io.circe.HCursor case class DcosVersion( version: universe.v3.model.DcosReleaseVersion, dcosImageCommit: String, bootstrapId: String ) object DcosVersion { implicit val decodeDcosVersion: Decoder[DcosVersion] = Decoder.instance { (cursor: HCursor) => for { v <- cursor.downField("version").as[universe.v3.model.DcosReleaseVersion] dIC <- cursor.downField("dcos-image-commit").as[String] bId <- cursor.downField("bootstrap-id").as[String] } yield DcosVersion(v, dIC, bId) } }
Example 6
Source File: MediaTypedDecoder.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos.finch import cats.data.NonEmptyList import com.mesosphere.cosmos.circe.Decoders.convertToCosmosError import com.mesosphere.cosmos.error.UnsupportedContentType import com.mesosphere.error.Result import com.mesosphere.http.MediaType import io.circe.Decoder import io.circe.HCursor import scala.reflect.ClassTag trait MediaTypedDecoder[A] { val mediaTypes: NonEmptyList[MediaType] val decoder: Decoder[A] def apply(cursor: HCursor, mediaType: MediaType): Result[A] } final class SimpleMediaTypedDecoder[A]( val mediaTypes: NonEmptyList[MediaType], val decoder: Decoder[A] )( implicit classTag: ClassTag[A] ) extends MediaTypedDecoder[A] { def apply(cursor: HCursor, mediaType: MediaType): Result[A] = { if (mediaTypes.exists(current => MediaType.compatible(current, mediaType))) { convertToCosmosError(decoder(cursor), cursor.value.noSpaces) } else { Left( UnsupportedContentType( mediaTypes.toList, Some(mediaType.show) ) ) } } } object MediaTypedDecoder { def apply[A]( mediaTypes: NonEmptyList[MediaType] )( implicit decoder: Decoder[A], classTag: ClassTag[A] ): MediaTypedDecoder[A] = { new SimpleMediaTypedDecoder(mediaTypes, decoder) } def apply[A]( mediaType: MediaType )( implicit decoder: Decoder[A], classTag: ClassTag[A] ): MediaTypedDecoder[A] = { MediaTypedDecoder(NonEmptyList.of(mediaType)) } }
Example 7
Source File: Images.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.universe.v2.model import io.circe.Decoder import io.circe.Encoder import io.circe.HCursor import io.circe.Json import io.circe.syntax._ case class Images( iconSmall: Option[String], iconMedium: Option[String], iconLarge: Option[String], screenshots: Option[List[String]] ) object Images { implicit val encodeImages: Encoder[Images] = Encoder.instance { (images: Images) => Json.obj( "icon-small" -> images.iconSmall.asJson, "icon-medium" -> images.iconMedium.asJson, "icon-large" -> images.iconLarge.asJson, "screenshots" -> images.screenshots.asJson ) } implicit val decodeV2Images: Decoder[Images] = Decoder.instance { (cursor: HCursor) => for { iS <- cursor.downField("icon-small").as[Option[String]] iM <- cursor.downField("icon-medium").as[Option[String]] iL <- cursor.downField("icon-large").as[Option[String]] ss <- cursor.downField("screenshots").as[Option[List[String]]] } yield Images(iS, iM, iL, ss) } }
Example 8
Source File: ReleaseVersion.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.universe.v3.model import com.twitter.util.Return import com.twitter.util.Throw import com.twitter.util.Try import io.circe.Decoder import io.circe.DecodingFailure import io.circe.Encoder import io.circe.HCursor import io.circe.syntax.EncoderOps final class ReleaseVersion private(val value: Long) extends AnyVal object ReleaseVersion { def apply(value: Long): ReleaseVersion = validate(value).get def validate(value: Long): Try[ReleaseVersion] = { if (value >= 0) { Return(new ReleaseVersion(value)) } else { val message = s"Expected integer value >= 0 for release version, but found [$value]" Throw(new IllegalArgumentException(message)) } } implicit val packageDefinitionReleaseVersionOrdering: Ordering[ReleaseVersion] = { Ordering.by(_.value) } implicit val encodePackageDefinitionReleaseVersion: Encoder[ReleaseVersion] = { Encoder.instance(_.value.asJson) } implicit val decodePackageDefinitionReleaseVersion: Decoder[ReleaseVersion] = Decoder.instance[ReleaseVersion] { (c: HCursor) => c.as[Long].map(validate).flatMap { case Return(v) => Right(v) case Throw(e) => Left(DecodingFailure(e.getMessage, c.history)) } } }
Example 9
Source File: Images.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.universe.v3.model import com.mesosphere.cosmos.circe.Decoders._ import io.circe.Decoder import io.circe.Encoder import io.circe.HCursor import io.circe.Json import io.circe.syntax.EncoderOps case class Images( iconSmall: Option[String], iconMedium: Option[String], iconLarge: Option[String], screenshots: Option[List[String]] ) object Images { implicit val decodeImages: Decoder[Images] = Decoder.instance { (cursor: HCursor) => for { iS <- cursor.downField("icon-small").as[Option[String]] iM <- cursor.downField("icon-medium").as[Option[String]] iL <- cursor.downField("icon-large").as[Option[String]] ss <- cursor.downField("screenshots").as[Option[List[String]]] } yield Images(iS, iM, iL, ss) } implicit val encodeImages: Encoder[Images] = Encoder.instance { (images: Images) => Json.obj( "icon-small" -> images.iconSmall.asJson, "icon-medium" -> images.iconMedium.asJson, "icon-large" -> images.iconLarge.asJson, "screenshots" -> images.screenshots.asJson ) } }
Example 10
Source File: IncompleteConfiguredDecoders.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.decoding import io.circe.{ Decoder, HCursor } import io.circe.generic.extras.Configuration import io.circe.generic.extras.util.RecordToMap import io.circe.generic.util.PatchWithOptions import scala.collection.immutable.Map import shapeless.{ Default, HList, LabelledGeneric } import shapeless.ops.function.FnFromProduct import shapeless.ops.record.RemoveAll private[circe] trait IncompleteConfiguredDecoders { implicit final def decodeIncompleteCaseClass[F, P <: HList, A, D <: HList, T <: HList, R <: HList](implicit ffp: FnFromProduct.Aux[P => A, F], gen: LabelledGeneric.Aux[A, T], removeAll: RemoveAll.Aux[T, P, (P, R)], decode: ReprDecoder[R], defaults: Default.AsRecord.Aux[A, D], defaultMapper: RecordToMap[D], config: Configuration ): ConfiguredDecoder[F] = new ConfiguredDecoder[F](config) { private[this] val defaultMap: Map[String, Any] = if (config.useDefaults) defaultMapper(defaults()) else Map.empty final def apply(c: HCursor): Decoder.Result[F] = decode.configuredDecode(c)( config.transformMemberNames, constructorNameTransformer, defaultMap, None ) match { case Right(r) => Right(ffp(p => gen.from(removeAll.reinsert((p, r))))) case l @ Left(_) => l.asInstanceOf[Decoder.Result[F]] } override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[F] = decode .configuredDecodeAccumulating(c)( config.transformMemberNames, constructorNameTransformer, defaultMap, None ) .map(r => ffp(p => gen.from(removeAll.reinsert((p, r))))) } implicit final def decodeCaseClassPatch[A, D <: HList, R <: HList, O <: HList](implicit gen: LabelledGeneric.Aux[A, R], patch: PatchWithOptions.Aux[R, O], decode: ReprDecoder[O], defaults: Default.AsRecord.Aux[A, D], defaultMapper: RecordToMap[D], config: Configuration ): ConfiguredDecoder[A => A] = new ConfiguredDecoder[A => A](config) { private[this] val defaultMap: Map[String, Any] = if (config.useDefaults) defaultMapper(defaults()) else Map.empty final def apply(c: HCursor): Decoder.Result[A => A] = decode.configuredDecode(c)( config.transformMemberNames, constructorNameTransformer, defaultMap, None ) match { case Right(o) => Right(a => gen.from(patch(gen.to(a), o))) case l @ Left(_) => l.asInstanceOf[Decoder.Result[A => A]] } override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A => A] = decode .configuredDecodeAccumulating(c)( config.transformMemberNames, constructorNameTransformer, defaultMap, None ) .map(o => a => gen.from(patch(gen.to(a), o))) } }
Example 11
Source File: Environment.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.lang.v1.traits import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.v1.traits.domain.Recipient.Address import com.wavesplatform.lang.v1.traits.domain._ import shapeless._ object Environment { import io.circe.{Decoder, HCursor} case class BalanceDetails(available: Long, regular: Long, generating: Long, effective: Long) implicit val BalanceDetailsDecoder: Decoder[BalanceDetails] = (c: HCursor) => for { available <- c.downField("available").as[Long] regular <- c.downField("regular").as[Long] generating <- c.downField("generating").as[Long] effective <- c.downField("effective").as[Long] } yield BalanceDetails(available, regular, generating, effective) type InputEntity = Tx :+: Ord :+: PseudoTx :+: CNil case class AssetId(id: Array[Byte]) type Tthis = Recipient.Address :+: AssetId :+: CNil } trait Environment[F[_]] { def chainId: Byte def inputEntity: Environment.InputEntity def tthis: Environment.Tthis def height: F[Long] def transactionById(id: Array[Byte]): F[Option[Tx]] def transferTransactionById(id: Array[Byte]): F[Option[Tx.Transfer]] def transactionHeightById(id: Array[Byte]): F[Option[Long]] def assetInfoById(id: Array[Byte]): F[Option[ScriptAssetInfo]] def lastBlockOpt(): F[Option[BlockInfo]] def blockInfoByHeight(height: Int): F[Option[BlockInfo]] def data(addressOrAlias: Recipient, key: String, dataType: DataType): F[Option[Any]] def resolveAlias(name: String): F[Either[String, Recipient.Address]] def accountBalanceOf(addressOrAlias: Recipient, assetId: Option[Array[Byte]]): F[Either[String, Long]] def accountWavesBalanceOf(addressOrAlias: Recipient): F[Either[String, Environment.BalanceDetails]] def multiPaymentAllowed: Boolean def txId: ByteStr def transferTransactionFromProto(b: Array[Byte]): F[Option[Tx.Transfer]] def addressFromString(address: String): Either[String, Address] def dAppAlias: Boolean = false }
Example 12
Source File: DataEntry.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.lang.v1.repl.node.http.response.model import com.wavesplatform.lang.v1.traits.DataType import io.circe.{Decoder, DecodingFailure, HCursor} private[node] case class DataEntry(key: String, value: Any, `type`: DataType) private[node] object DataEntry { implicit val decoder: Decoder[DataEntry] = (c: HCursor) => for { rawType <- c.downField("type").as[String] key <- c.downField("key").as[String] v = c.downField("value") (value, resolvedType) <- rawType match { case "binary" => v.as[ByteString] map(b => (b.byteStr, DataType.ByteArray)) case "boolean" => v.as[Boolean] map((_, DataType.Boolean)) case "integer" => v.as[Long] map((_, DataType.Long)) case "string" => v.as[String] map((_, DataType.String)) case t => Left(DecodingFailure(s"Illegal data entry type: $t", Nil)) } } yield DataEntry(key, value, resolvedType) }
Example 13
Source File: ByteString.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.lang.v1.repl.node.http.response.model import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, Base64} import io.circe.{Decoder, HCursor} private[node] case class ByteString(bytes: Array[Byte] = Array(0)) { lazy val byteStr: ByteStr = ByteStr(bytes) override def toString: String = byteStr.toString } private[node] object ByteString { implicit val decoder: Decoder[ByteString] = (c: HCursor) => Right { val str = c.value.asString.get if (str.startsWith("base58:")) ByteString(Base58.decode(str.substring(7))) else if (str.startsWith("base64:")) ByteString(Base64.decode(str.substring(7))) else ByteString(Base58.decode(str)) } }
Example 14
Source File: Transaction.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.lang.v1.repl.node.http.response.model import com.wavesplatform.lang.v1.traits.domain.Recipient import com.wavesplatform.lang.v1.traits.domain.Recipient.{Address, Alias} import io.circe.{Decoder, HCursor} private[node] case class TransferTransaction( id: ByteString, recipient: Recipient, amount: Long, assetId: Option[ByteString], feeAssetId: Option[ByteString], attachment: ByteString, fee: Long, timestamp: Long, height: Int, `type`: Byte, version: Byte, senderPublicKey: ByteString, proofs: List[ByteString], bodyBytes: ByteString, succeed: Boolean ) object Transaction { private val aliasPattern = "alias:\\w:(\\w+)".r implicit val decoder: Decoder[TransferTransaction] = (c: HCursor) => for { applicationStatus <- c.downField("applicationStatus").as[Option[String]] succeed = applicationStatus.fold(true)(_ == "succeeded") version <- c.downField("version").as[Int] height <- c.downField("height").as[Option[Int]] typeId <- c.downField("type").as[Int] bodyBytes <- c.downField("bodyBytes").as[ByteString] proofs <- version match { case 1 => c.downField("signature").as[ByteString].map(v => List.apply(v)) case _ => c.downField("proofs").as[List[ByteString]] } id <- c.downField("id").as[ByteString] recipient <- c.downField("recipient").as[String].flatMap { case aliasPattern(alias) => Right(Alias(alias)) case _ => c.downField("recipient").as[ByteString].map(b => Address(b.byteStr)) } af = c.downField("attachment") attachment <- af.as[ByteString] senderPublicKey <- c.downField("senderPublicKey").as[ByteString] amount <- c.downField("amount").as[Long] fee <- c.downField("fee").as[Long] timestamp <- c.downField("timestamp").as[Long] assetId <- c.downField("assetId").as[Option[ByteString]] feeAssetId <- c.downField("feeAssetId").as[Option[ByteString]] } yield TransferTransaction( id, recipient, amount, assetId, feeAssetId, attachment, fee, timestamp, height.getOrElse(-1), typeId.toByte, version.toByte, senderPublicKey, proofs, ByteString(), succeed ) }
Example 15
Source File: GraphQLResponseError.scala From caliban with Apache License 2.0 | 5 votes |
package caliban.client import caliban.client.GraphQLResponseError.Location import io.circe.{ Decoder, DecodingFailure, HCursor } case class GraphQLResponseError( message: String, locations: Option[List[Location]], path: Option[List[Either[String, Int]]] ) object GraphQLResponseError { case class Location(line: Int, column: Int) implicit val decoderEither: Decoder[Either[String, Int]] = (c: HCursor) => c.value.asNumber.flatMap(_.toInt).map(v => Right(Right(v))) orElse c.value.asString .map(v => Right(Left(v))) getOrElse Left(DecodingFailure("Value is not an Either[String, Int]", c.history)) implicit val locationDecoder: Decoder[Location] = (c: HCursor) => for { line <- c.downField("line").as[Int] column <- c.downField("column").as[Int] } yield Location(line, column) implicit val decoder: Decoder[GraphQLResponseError] = (c: HCursor) => for { message <- c.downField("message").as[String] locations <- c.downField("locations").as[Option[List[Location]]] path <- c.downField("path").as[Option[List[Either[String, Int]]]] } yield GraphQLResponseError(message, locations, path) }
Example 16
Source File: package.scala From patchless with Apache License 2.0 | 5 votes |
package patchless.circe import cats.syntax.either._ import io.circe.{Decoder, HCursor, Json, JsonObject} import io.circe.generic.decoding.DerivedDecoder import io.circe.generic.extras.decoding.ReprDecoder import io.circe.generic.encoding.DerivedObjectEncoder import io.circe.generic.extras.Configuration import io.circe.generic.extras.encoding.ReprObjectEncoder import io.circe.generic.extras.util.RecordToMap import patchless.{Patch, Patchable} import shapeless.{Default, HList, Lazy} package object extras { implicit def decodeOptionOption[T]( implicit decodeOpt: Decoder[Option[T]] ) : Decoder[Option[Option[T]]] = Decoder.withReattempt { c => if (c.succeeded) c.as[Option[T]].map(Some(_)) else Right(None) } implicit def decodePatch[T, U <: HList, D <: HList](implicit patchable: Patchable.Aux[T, U], decodeU: Lazy[ReprDecoder[U]], defaults: Default.AsRecord.Aux[T, D], defaultMapper: RecordToMap[D], config: Configuration ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] { def apply(c: HCursor): Decoder.Result[Patch[T]] = decodeU.value.configuredDecode(c)( config.transformMemberNames, config.transformConstructorNames, if(config.useDefaults) defaultMapper(defaults()) else Map.empty, config.discriminator ).map { updates => Patch.ofUpdates[T, U](updates) } } implicit def encodePatch[T, U <: HList](implicit patchable: Patchable.Aux[T, U], encodeU: Lazy[ReprObjectEncoder[U]], config: Configuration ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] { def encodeObject(a: Patch[T]): JsonObject = encodeU.value.configuredEncodeObject(a.patchUpdates)( config.transformMemberNames, config.transformConstructorNames, config.discriminator ) } }
Example 17
Source File: package.scala From patchless with Apache License 2.0 | 5 votes |
package patchless import cats.syntax.either._ import io.circe.Decoder.Result import io.circe.{Decoder, HCursor, Json, JsonObject} import io.circe.generic.decoding.{DerivedDecoder, ReprDecoder} import io.circe.generic.encoding.{DerivedObjectEncoder, ReprObjectEncoder} import shapeless.{HList, LabelledGeneric} package object circe { implicit def decodeOptionOption[T]( implicit decodeOpt: Decoder[Option[T]] ) : Decoder[Option[Option[T]]] = { Decoder.instance { cursor => if(cursor.focus == Json.Null) { Right(Some(None)) } else decodeOpt.apply(cursor).map(Some(_)) } } implicit def decodePatch[T, U <: HList](implicit patchable: Patchable.Aux[T, U], decodeU: ReprDecoder[U] ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] { def apply(c: HCursor): Result[Patch[T]] = decodeU(c).map { updates => Patch.ofUpdates[T, U](updates) } } implicit def encodePatch[T, U <: HList](implicit patchable: Patchable.Aux[T, U], encodeU: ReprObjectEncoder[U] ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] { def encodeObject(a: Patch[T]): JsonObject = encodeU.encodeObject(a.patchUpdates) } }
Example 18
Source File: RateLimit.scala From github with MIT License | 5 votes |
package io.chrisdavenport.github.data import cats.implicits._ import io.circe.Decoder import io.circe.HCursor object RateLimit { final case class Limits( max: Int, remaining: Int, reset: Int ) object Limits { implicit val decoder = new Decoder[Limits]{ def apply(c: HCursor): Decoder.Result[Limits] = ( c.downField("limit").as[Int], c.downField("remaining").as[Int], c.downField("reset").as[Int] ).mapN(Limits.apply) } } final case class RateLimit( core: Limits, search: Limits, graphQL: Limits, integrationManifest: Limits ) object RateLimit { implicit val decoder = new Decoder[RateLimit]{ def apply(c: HCursor): Decoder.Result[RateLimit] = { val base = c.downField("resources") ( base.downField("core").as[Limits], base.downField("search").as[Limits], base.downField("graphql").as[Limits], base.downField("integration_manifest").as[Limits] ).mapN(RateLimit.apply) } } } }
Example 19
Source File: TemplateId.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw.values import cats.Eq import io.circe.{Decoder, Encoder, HCursor, Json, KeyDecoder, KeyEncoder} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import cats.implicits._ import org.adridadou.openlaw.parser.template.variableTypes.EthereumAddress final case class TemplateId(id: String = "") extends Comparable[TemplateId] { override def toString: String = id override def compareTo(o: TemplateId): Int = id.compareTo(o.id) } object TemplateId { def apply(data: Array[Byte]): TemplateId = TemplateId(EthereumAddress.bytes2hex(data)) implicit val templateIdEnc: Encoder[TemplateId] = deriveEncoder implicit val templateIdDec: Decoder[TemplateId] = deriveDecoder implicit val eq: Eq[TemplateId] = Eq.by(_.id) } final case class TemplateIdentifier(title: TemplateTitle, version: Int) final case class TemplateTitle(originalTitle: String, title: String) { override def toString: String = title override def equals(obj: Any): Boolean = obj match { case other: TemplateTitle => this === other case _ => false } override def hashCode(): Int = this.title.hashCode } object TemplateTitle { def apply(): TemplateTitle = TemplateTitle("") def apply(title: String): TemplateTitle = TemplateTitle(originalTitle = title, title = title.toLowerCase()) implicit val eq: Eq[TemplateTitle] = (x: TemplateTitle, y: TemplateTitle) => x.title === y.title implicit val templateTitleEnc: Encoder[TemplateTitle] = (a: TemplateTitle) => Json.fromString(a.originalTitle) implicit val templateTitleDec: Decoder[TemplateTitle] = (c: HCursor) => (for { title <- c.downField("title").as[String] } yield TemplateTitle(title)) match { case Right(title) => Right(title) case Left(_) => c.as[String].map(TemplateTitle(_)) } implicit val templateTitleKeyEnc: KeyEncoder[TemplateTitle] = (key: TemplateTitle) => key.title implicit val templateTitleKeyDec: KeyDecoder[TemplateTitle] = (key: String) => Some(TemplateTitle(key)) }
Example 20
Source File: APIWalTail.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import io.circe.Decoder.Result import io.youi.client.HttpClient import io.youi.http.{HeaderKey, HttpMethod} import io.youi.net._ import io.circe.{Decoder, DecodingFailure, HCursor} import profig.JsonUtil import scala.concurrent.{ExecutionContext, Future} object APIWalTail { private implicit def operationTypeDecoder: Decoder[OperationType] = new Decoder[OperationType] { override def apply(c: HCursor): Result[OperationType] = c.value.asNumber match { case Some(n) => Right(OperationType(n.toInt.get)) case None => Left(DecodingFailure(s"OperationType not a number: ${c.value}", Nil)) } } def get(client: HttpClient, global: Option[Boolean] = None, from: Option[Long] = None, to: Option[Long] = None, lastScanned: Long = 0L, chunkSize: Option[Long] = None, syncerId: Option[Long] = None, serverId: Option[Long] = None, clientId: Option[String] = None)(implicit ec: ExecutionContext): Future[WALOperations] = { client .method(HttpMethod.Get) .path(path"/_api/wal/tail", append = true) .param[Option[Long]]("from", from, None) .param[Option[Long]]("to", to, None) .param[Long]("lastScanned", lastScanned, 0L) .param[Option[Boolean]]("global", global, None) .param[Option[Long]]("chunkSize", chunkSize, None) .param[Option[Long]]("syncerId", syncerId, None) .param[Option[Long]]("serverId", serverId, None) .param[Option[String]]("clientId", clientId, None) .send() .map { response => val lines = response.content.map(_.asString).getOrElse("").split('\n').toList val operations = lines.map(_.trim).collect { case line if line.nonEmpty => JsonUtil.fromJsonString[WALOperation](line) } val headers = response.headers WALOperations( client = client, global = global, chunkSize = chunkSize, syncerId = syncerId, serverId = serverId, clientId = clientId, checkMore = headers.first(HeaderKey("X-Arango-Replication-Checkmore")).exists(_.toBoolean), fromPresent = headers.first(HeaderKey("X-Arango-Replication-Frompresent")).exists(_.toBoolean), lastIncluded = headers.first(HeaderKey("X-Arango-Replication-Lastincluded")).map(_.toLong).getOrElse(-1L), lastScanned = headers.first(HeaderKey("X-Arango-Replication-Lastscanned")).map(_.toLong).getOrElse(-1L), lastTick = headers.first(HeaderKey("X-Arango-Replication-Lasttick")).map(_.toLong).getOrElse(-1L), operations = operations ) } } }
Example 21
Source File: TransactionStatus.scala From scarango with MIT License | 5 votes |
package com.outr.arango.transaction import io.circe.Decoder.Result import io.circe.{Decoder, DecodingFailure, HCursor} sealed trait TransactionStatus object TransactionStatus { case object Running extends TransactionStatus case object Committed extends TransactionStatus case object Aborted extends TransactionStatus implicit val decoder: Decoder[TransactionStatus] = new Decoder[TransactionStatus] { override def apply(c: HCursor): Result[TransactionStatus] = c.value.asString match { case Some(s) => Right(TransactionStatus(s)) case None => Left(DecodingFailure(s"Failed to decode from ${c.value}", Nil)) } } def apply(value: String): TransactionStatus = value match { case "running" => Running case "committed" => Committed case "aborted" => Aborted } }
Example 22
Source File: Transaction.scala From scarango with MIT License | 5 votes |
package com.outr.arango.transaction import com.outr.arango.Graph import io.circe.Decoder.Result import io.circe.{Decoder, DecodingFailure, HCursor} import scala.concurrent.{ExecutionContext, Future} case class Transaction(id: String, status: TransactionStatus) { private[arango] var graph: Option[Graph] = None def withGraph(option: Option[Graph]): Transaction = { graph = option this } def checkStatus()(implicit ec: ExecutionContext): Future[Transaction] = { val g = graph.getOrElse(throw new RuntimeException("Graph not included!")) g.arangoDatabase.transactionStatus(id).map(_.withGraph(graph)) } def commit()(implicit ec: ExecutionContext): Future[Unit] = { val g = graph.getOrElse(throw new RuntimeException("Graph not included!")) g.arangoDatabase.transactionCommit(id).map { t => t.status match { case TransactionStatus.Running => throw new RuntimeException("Commit failed, transaction still running!") case TransactionStatus.Committed => () case TransactionStatus.Aborted => throw new RuntimeException("Commit failed, transaction aborted!") } } } def abort()(implicit ec: ExecutionContext): Future[Unit] = { val g = graph.getOrElse(throw new RuntimeException("Graph not included!")) g.arangoDatabase.transactionAbort(id).map { t => t.status match { case TransactionStatus.Running => throw new RuntimeException("Abort failed, transaction still running!") case TransactionStatus.Committed => throw new RuntimeException("Abort failed, transaction committed!") case TransactionStatus.Aborted => () } } } }
Example 23
Source File: Serialization.scala From scarango with MIT License | 5 votes |
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, Encoder, HCursor, Json} import scala.language.experimental.macros case class Serialization[D](private val doc2Json: D => Json, private val json2Doc: Json => D) { final def toJson(document: D): Json = Id.update(doc2Json(document)) final def fromJson(json: Json): D = json2Doc(Id.update(json)) lazy val decoder: Decoder[D] = new Decoder[D] { override def apply(c: HCursor): Result[D] = Right(fromJson(c.value)) } } object Serialization { def auto[D]: Serialization[D] = macro Macros.serializationAuto[D] def create[D](encoder: Encoder[D], decoder: Decoder[D]): Serialization[D] = { val doc2Json = (d: D) => encoder(d) val json2Doc = (json: Json) => decoder.decodeJson(json) match { case Left(df) => throw df case Right(d) => d } Serialization[D](doc2Json, json2Doc) } }
Example 24
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, Encoder, HCursor, Json} import com.outr.arango.JsonImplicits._ lazy val _id: String = s"$collection/$value" override def compare(that: Id[D]): Int = this._id.compare(that._id) override def toString: String = _id } object Id { private val ExtractorRegex = """(.+)/(.+)""".r implicit def encoder[D]: Encoder[Id[D]] = new Encoder[Id[D]] { override def apply(id: Id[D]): Json = Json.fromString(id._id) } implicit def decoder[D]: Decoder[Id[D]] = new Decoder[Id[D]] { override def apply(c: HCursor): Result[Id[D]] = c.value.asString.get match { case ExtractorRegex(collection, value) => Right(Id[D](value, collection)) } } def parse[D](id: String): Id[D] = id match { case ExtractorRegex(collection, value) => Id[D](value, collection) } def extract[D](json: Json): Id[D] = { val updated = update(json) decoder[D].decodeJson((updated \ "_id").get) match { case Left(df) => throw df case Right(id) => id } } def update(json: Json): Json = { val _key = (json \ "_key").flatMap(_.asString) val _id = (json \ "_id").flatMap(_.asString) val _identity = _id.map(parse[Any]) if (_id.nonEmpty && _key.isEmpty) { json.deepMerge(Json.obj("_key" -> Json.fromString(_identity.get.value))) } else { json } } }
Example 25
Source File: package.scala From kanadi with MIT License | 5 votes |
package org.zalando import java.net.URI import cats.syntax.either._ import io.circe.Decoder.Result import io.circe.syntax._ import io.circe.{Decoder, DecodingFailure, Encoder, HCursor} import scala.util.control.NonFatal package object kanadi { private[kanadi] implicit val uriEncoder: Encoder[URI] = Encoder.instance[URI](_.toString.asJson) private[kanadi] implicit val uriDecoder: Decoder[URI] = new Decoder[URI] { override def apply(c: HCursor): Result[URI] = c.as[String].flatMap { value => try { Right(new URI(value)) } catch { case NonFatal(_) => Left(DecodingFailure("Invalid Uri", c.history)) } } } }
Example 26
Source File: package.scala From tsec with MIT License | 5 votes |
package tsec import cats.{Eq, MonadError} import cats.instances.string._ import cats.syntax.either._ import io.circe.{Decoder, Encoder, HCursor, Json} import tsec.cipher.common.padding.NoPadding import tsec.cipher.symmetric._ import tsec.cipher.symmetric.jca._ import tsec.common._ import tsec.mac.MAC import tsec.mac.jca.MacVerificationError package object cookies { type AEADCookie[A] = AEADCookie.Cookie[A] implicit object AEADCookie { type Cookie[A] <: String @inline def fromEncrypted[A](a: CipherText[A], aad: AAD): AEADCookie[A] = apply[A](a.toConcatenated.toB64String + "-" + aad.toB64String) @inline def subst[G[_], A](fa: G[String]): G[AEADCookie[A]] = fa.asInstanceOf[G[AEADCookie[A]]] @inline def unsubst[G[_], A](fa: G[AEADCookie[A]]): G[String] = fa.asInstanceOf[G[String]] @inline def apply[A](raw: String): AEADCookie[A] = raw.asInstanceOf[AEADCookie[A]] def getEncryptedContent[F[_], A: AES]( signed: AEADCookie[A] )(implicit encryptor: AADEncryptor[F, A, SecretKey]): Either[CipherTextError, CipherText[A]] = { val split = signed.split("-") if (split.length != 2) Left(CipherTextError("String encoded improperly")) else { split(0).b64Bytes match { case Some(e) => CTOPS.ciphertextFromArray[A, GCM, NoPadding](e) case None => Left(CipherTextError("String encoded improperly")) } } } implicit def circeDecoder[A]: Decoder[AEADCookie[A]] = new Decoder[AEADCookie[A]] { def apply(c: HCursor) = c.as[String].map(AEADCookie.apply[A]) } implicit def circeEncoder[A]: Encoder[AEADCookie[A]] = new Encoder[AEADCookie[A]] { def apply(a: AEADCookie[A]): Json = Json.fromString(a) } } type SignedCookie[A] = SignedCookie.Cookie[A] implicit object SignedCookie { type Cookie[A] <: String @inline def from[A](signed: MAC[A], joined: String): SignedCookie[A] = apply[A](joined + "-" + signed.toB64String) @inline def apply[A](raw: String): SignedCookie[A] = raw.asInstanceOf[SignedCookie[A]] @inline def subst[G[_], A](fa: G[String]): G[SignedCookie[A]] = fa.asInstanceOf[G[SignedCookie[A]]] @inline def unsubst[G[_], A](fa: G[SignedCookie[A]]): G[String] = fa.asInstanceOf[G[String]] def fromDecodedString[F[_]](original: String)(implicit F: MonadError[F, Throwable]): F[String] = original.split("-") match { case Array(orig, nonce) => orig.b64Bytes match { case Some(o) => F.pure(o.toUtf8String) case None => F.raiseError(MacVerificationError("String encoded improperly")) } case _ => F.raiseError(MacVerificationError("String encoded improperly")) } } implicit final def cookieEQ[A]: Eq[SignedCookie[A]] = SignedCookie.subst(Eq[String]) implicit final def ecookieEQ[A]: Eq[AEADCookie[A]] = Eq.by[AEADCookie[A], String](identity[String]) }
Example 27
Source File: UpdatePattern.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.repoconfig import cats.implicits._ import io.circe.generic.semiauto._ import io.circe.{Decoder, Encoder, HCursor} import org.scalasteward.core.data.{GroupId, Update} final case class UpdatePattern( groupId: GroupId, artifactId: Option[String], version: Option[UpdatePattern.Version] ) object UpdatePattern { final case class MatchResult( byArtifactId: List[UpdatePattern], filteredVersions: List[String] ) final case class Version(prefix: Option[String], suffix: Option[String]) { def matches(version: String): Boolean = suffix.forall(version.endsWith) && prefix.forall(version.startsWith) } def findMatch( patterns: List[UpdatePattern], update: Update.Single, include: Boolean ): MatchResult = { val byGroupId = patterns.filter(_.groupId === update.groupId) val byArtifactId = byGroupId.filter(_.artifactId.forall(_ === update.artifactId.name)) val filteredVersions = update.newerVersions.filter(newVersion => byArtifactId.exists(_.version.forall(_.matches(newVersion))) === include ) MatchResult(byArtifactId, filteredVersions) } implicit val updatePatternDecoder: Decoder[UpdatePattern] = deriveDecoder implicit val updatePatternEncoder: Encoder[UpdatePattern] = deriveEncoder implicit val updatePatternVersionDecoder: Decoder[Version] = Decoder[String] .map(s => Version(Some(s), None)) .or((hCursor: HCursor) => for { prefix <- hCursor.downField("prefix").as[Option[String]] suffix <- hCursor.downField("suffix").as[Option[String]] } yield Version(prefix, suffix) ) implicit val updatePatternVersionEncoder: Encoder[Version] = deriveEncoder }
Example 28
Source File: UnwrappedDecoder.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.decoding import io.circe.{ Decoder, HCursor } import scala.annotation.implicitNotFound import shapeless.{ ::, Generic, HNil, Lazy } @implicitNotFound( """Could not find UnwrappedDecoder for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class UnwrappedDecoder[A] extends Decoder[A] object UnwrappedDecoder { implicit def decodeUnwrapped[A, R](implicit gen: Lazy[Generic.Aux[A, R :: HNil]], decodeR: Decoder[R] ): UnwrappedDecoder[A] = new UnwrappedDecoder[A] { override def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match { case Right(unwrapped) => Right(gen.value.from(unwrapped :: HNil)) case l @ Left(_) => l.asInstanceOf[Decoder.Result[A]] } } }
Example 29
Source File: ContractAccess.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw.values import cats.Eq import io.circe.{Decoder, Encoder, HCursor, Json} sealed abstract class ContractAccess(val name: String) case object ContractSignable extends ContractAccess("signable") case object ContractNoAccess extends ContractAccess("noaccess") case object ContractReadonly extends ContractAccess("readonly") case object ContractEditable extends ContractAccess("editable") object ContractAccess { def apply(name: String): ContractAccess = name match { case ContractReadonly.name => ContractReadonly case ContractNoAccess.name => ContractNoAccess case ContractSignable.name => ContractSignable case ContractEditable.name => ContractEditable } def unapply(arg: ContractAccess): String = arg.name implicit val accessDecoder: Decoder[ContractAccess] = (c: HCursor) => { for { name <- c.as[String] } yield ContractAccess(name) } implicit val accessEncoder: Encoder[ContractAccess] = (a: ContractAccess) => Json.fromString(a.name) implicit val eqForContractAccess: Eq[ContractAccess] = Eq.fromUniversalEquals }
Example 30
Source File: SearchFilters.scala From franklin with Apache License 2.0 | 5 votes |
package com.azavea.franklin.database import cats.implicits._ import com.azavea.franklin.api.schemas.bboxToString import com.azavea.franklin.datamodel.{PaginationToken, Query} import com.azavea.stac4s.{Bbox, TemporalExtent} import eu.timepit.refined.types.numeric.NonNegInt import geotrellis.vector.Geometry import geotrellis.vector.{io => _, _} import io.circe.generic.semiauto._ import io.circe.refined._ import io.circe.{Decoder, HCursor} import java.net.URLEncoder import java.nio.charset.StandardCharsets final case class SearchFilters( bbox: Option[Bbox], datetime: Option[TemporalExtent], intersects: Option[Geometry], collections: List[String], items: List[String], limit: Option[NonNegInt], query: Map[String, List[Query]], next: Option[PaginationToken] ) { def asQueryParameters: String = { val bboxQP = bbox map { box => s"bbox=${bboxToString(box)}" } val datetimeQP = datetime map { tempExtent => s"datetime=${SearchFilters.encodeString(temporalExtentToString(tempExtent))}" } val collectionsQP = collections.toNel map { _ => s"""collections=${SearchFilters.encodeString(collections.mkString(","))}""" } val itemsQP = items.toNel map { _ => s"""ids=${SearchFilters.encodeString(items.mkString(","))}""" } List(bboxQP, datetimeQP, collectionsQP, itemsQP).flatten.mkString("&") } } object SearchFilters { def encodeString(s: String): String = URLEncoder.encode(s, StandardCharsets.UTF_8.toString) implicit val searchFilterDecoder = new Decoder[SearchFilters] { final def apply(c: HCursor): Decoder.Result[SearchFilters] = for { bbox <- c.downField("bbox").as[Option[Bbox]] datetime <- c.downField("datetime").as[Option[TemporalExtent]] intersects <- c.downField("intersects").as[Option[Geometry]] collectionsOption <- c.downField("collections").as[Option[List[String]]] itemsOption <- c.downField("items").as[Option[List[String]]] limit <- c.downField("limit").as[Option[NonNegInt]] query <- c.get[Option[Map[String, List[Query]]]]("query") paginationToken <- c.get[Option[PaginationToken]]("next") } yield { SearchFilters( bbox, datetime, intersects, collectionsOption.getOrElse(List.empty), itemsOption.getOrElse(List.empty), limit, query getOrElse Map.empty, paginationToken ) } } implicit val searchFilterEncoder = deriveEncoder[SearchFilters] }
Example 31
Source File: IamIdentitiesClient.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.client.RequestBuilding.Get import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.model.headers.OAuth2BearerToken import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller import akka.util.ByteString import cats.effect.{ContextShift, Effect, IO} import cats.implicits._ import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.storage.IamIdentitiesClient.Identity._ import ch.epfl.bluebrain.nexus.storage.IamIdentitiesClient._ import ch.epfl.bluebrain.nexus.storage.IamIdentitiesClientError.IdentitiesSerializationError import ch.epfl.bluebrain.nexus.storage.config.IamClientConfig import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport.{DecodingFailures => AccDecodingFailures} import io.circe.Decoder.Result import io.circe.{Decoder, DecodingFailure, HCursor} import scala.concurrent.ExecutionContext class IamIdentitiesClient[F[_]](config: IamClientConfig)(implicit F: Effect[F], as: ActorSystem) extends JsonLdCirceSupport { private val um: FromEntityUnmarshaller[Caller] = unmarshaller[Caller] implicit private val ec: ExecutionContext = as.dispatcher implicit private val contextShift: ContextShift[IO] = IO.contextShift(ec) def apply()(implicit credentials: Option[AccessToken]): F[Caller] = credentials match { case Some(token) => execute(Get(config.identitiesIri.asAkka).addCredentials(OAuth2BearerToken(token.value))) case None => F.pure(Caller.anonymous) } private def execute(req: HttpRequest): F[Caller] = { IO.fromFuture(IO(Http().singleRequest(req))).to[F].flatMap { resp => if (resp.status.isSuccess()) IO.fromFuture(IO(um(resp.entity))).to[F].recoverWith { case err: AccDecodingFailures => F.raiseError(IdentitiesSerializationError(err.getMessage)) case err: Error => F.raiseError(IdentitiesSerializationError(err.getMessage)) } else IO.fromFuture(IO(resp.entity.dataBytes.runFold(ByteString(""))(_ ++ _).map(_.utf8String))) .to[F] .flatMap { err => F.raiseError(IamIdentitiesClientError.unsafe(resp.status, err)) } } } } object IamIdentitiesClient { final case class Authenticated(realm: String) extends Identity private def decodeAnonymous(hc: HCursor): Result[Subject] = hc.get[String]("@type").flatMap { case "Anonymous" => Right(Anonymous) case _ => Left(DecodingFailure("Cannot decode Anonymous Identity", hc.history)) } private def decodeUser(hc: HCursor): Result[Subject] = (hc.get[String]("subject"), hc.get[String]("realm")).mapN { case (subject, realm) => User(subject, realm) } private def decodeGroup(hc: HCursor): Result[Identity] = (hc.get[String]("group"), hc.get[String]("realm")).mapN { case (group, realm) => Group(group, realm) } private def decodeAuthenticated(hc: HCursor): Result[Identity] = hc.get[String]("realm").map(Authenticated) private val attempts = List[HCursor => Result[Identity]](decodeAnonymous, decodeUser, decodeGroup, decodeAuthenticated) implicit val identityDecoder: Decoder[Identity] = Decoder.instance { hc => attempts.foldLeft(Left(DecodingFailure("Unexpected", hc.history)): Result[Identity]) { case (acc @ Right(_), _) => acc case (_, f) => f(hc) } } } }
Example 32
Source File: ConfiguredAsObjectCodec.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.codec import io.circe.{ Decoder, Encoder, HCursor, JsonObject } import io.circe.generic.codec.DerivedAsObjectCodec import io.circe.generic.extras.{ Configuration, JsonKey } import io.circe.generic.extras.decoding.ConfiguredDecoder import io.circe.generic.extras.encoding.ConfiguredAsObjectEncoder import io.circe.generic.extras.util.RecordToMap import scala.annotation.implicitNotFound import shapeless.{ Annotations, Coproduct, Default, HList, LabelledGeneric, Lazy } import shapeless.ops.hlist.ToTraversable import shapeless.ops.record.Keys @implicitNotFound( """Could not find ConfiguredAsObjectCodec for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class ConfiguredAsObjectCodec[A] extends DerivedAsObjectCodec[A] object ConfiguredAsObjectCodec { implicit def codecForCaseClass[A, R <: HList, D <: HList, F <: HList, K <: HList](implicit gen: LabelledGeneric.Aux[A, R], codec: Lazy[ReprAsObjectCodec[R]], defaults: Default.AsRecord.Aux[A, D], defaultMapper: RecordToMap[D], config: Configuration, fields: Keys.Aux[R, F], fieldsToList: ToTraversable.Aux[F, List, Symbol], keys: Annotations.Aux[JsonKey, A, K], keysToList: ToTraversable.Aux[K, List, Option[JsonKey]] ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] { private[this] val decodeA: Decoder[A] = ConfiguredDecoder.decodeCaseClass[A, R, D, F, K]( gen, codec, defaults, defaultMapper, config, fields, fieldsToList, keys, keysToList ) private[this] val encodeA: Encoder.AsObject[A] = ConfiguredAsObjectEncoder.encodeCaseClass[A, R, F, K](gen, codec, config, fields, fieldsToList, keys, keysToList) final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c) final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c) final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a) } implicit def codecForAdt[A, R <: Coproduct](implicit gen: LabelledGeneric.Aux[A, R], codec: Lazy[ReprAsObjectCodec[R]], config: Configuration ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] { private[this] val decodeA: Decoder[A] = ConfiguredDecoder.decodeAdt[A, R](gen, codec, config) private[this] val encodeA: Encoder.AsObject[A] = ConfiguredAsObjectEncoder.encodeAdt[A, R](gen, codec, config) final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c) final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c) final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a) } }
Example 33
Source File: UnwrappedCodec.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.codec import io.circe.{ Codec, Decoder, Encoder, HCursor, Json } import scala.annotation.implicitNotFound import shapeless.{ ::, Generic, HNil, Lazy } @implicitNotFound( """Could not find UnwrappedCodec for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class UnwrappedCodec[A] extends Codec[A] object UnwrappedCodec { implicit def codecForUnwrapped[A, R](implicit gen: Lazy[Generic.Aux[A, R :: HNil]], decodeR: Decoder[R], encodeR: Encoder[R] ): UnwrappedCodec[A] = new UnwrappedCodec[A] { override def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match { case Right(unwrapped) => Right(gen.value.from(unwrapped :: HNil)) case l @ Left(_) => l.asInstanceOf[Decoder.Result[A]] } override def apply(a: A): Json = encodeR(gen.value.to(a).head) } }
Example 34
Source File: EnumerationCodec.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.codec import io.circe.{ Codec, Decoder, DecodingFailure, HCursor, Json } import io.circe.generic.extras.Configuration import scala.annotation.implicitNotFound import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness } import shapeless.labelled.{ FieldType, field } @implicitNotFound( """Could not find EnumerationCodec for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class EnumerationCodec[A] extends Codec[A] object EnumerationCodec { implicit val codecForEnumerationCNil: EnumerationCodec[CNil] = new EnumerationCodec[CNil] { def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history)) def apply(a: CNil): Json = sys.error("Cannot encode CNil") } implicit def codecForEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit witK: Witness.Aux[K], gen: LabelledGeneric.Aux[V, HNil], codecForR: EnumerationCodec[R], config: Configuration = Configuration.default ): EnumerationCodec[FieldType[K, V] :+: R] = new EnumerationCodec[FieldType[K, V] :+: R] { def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] = c.as[String] match { case Right(s) if s == config.transformConstructorNames(witK.value.name) => Right(Inl(field[K](gen.from(HNil)))) case Right(_) => codecForR.apply(c) match { case Right(v) => Right(Inr(v)) case Left(err) => Left(err) } case Left(err) => Left(DecodingFailure("Enumeration", c.history)) } def apply(a: FieldType[K, V] :+: R): Json = a match { case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name)) case Inr(r) => codecForR(r) } } implicit def codecForEnumeration[A, R <: Coproduct](implicit gen: LabelledGeneric.Aux[A, R], codecForR: EnumerationCodec[R] ): EnumerationCodec[A] = new EnumerationCodec[A] { def apply(c: HCursor): Decoder.Result[A] = codecForR(c) match { case Right(v) => Right(gen.from(v)) case Left(err) => Left(err) } def apply(a: A): Json = codecForR(gen.to(a)) } }
Example 35
Source File: ReprAsObjectCodec.scala From circe-generic-extras with Apache License 2.0 | 5 votes |
package io.circe.generic.extras.codec import cats.data.Validated import io.circe.{ Decoder, DecodingFailure, HCursor, JsonObject } import io.circe.generic.extras.ConfigurableDeriver import io.circe.generic.extras.decoding.ReprDecoder import io.circe.generic.extras.encoding.ReprAsObjectEncoder import scala.annotation.implicitNotFound import scala.collection.immutable.Map import scala.language.experimental.macros import shapeless.HNil @implicitNotFound( """Could not find ReprAsObjectCodec for type ${A}. Some possible causes for this: - ${A} isn't a case class or sealed trat - some of ${A}'s members don't have codecs of their own - missing implicit Configuration""" ) abstract class ReprAsObjectCodec[A] extends ReprDecoder[A] with ReprAsObjectEncoder[A] object ReprAsObjectCodec { implicit def deriveReprAsObjectCodec[R]: ReprAsObjectCodec[R] = macro ConfigurableDeriver.deriveConfiguredCodec[R] val hnilReprCodec: ReprAsObjectCodec[HNil] = new ReprAsObjectCodec[HNil] { def configuredDecode(c: HCursor)( transformMemberNames: String => String, transformConstructorNames: String => String, defaults: Map[String, Any], discriminator: Option[String] ): Decoder.Result[HNil] = if (c.value.isObject) Right(HNil) else Left(DecodingFailure("HNil", c.history)) def configuredDecodeAccumulating(c: HCursor)( transformMemberNames: String => String, transformConstructorNames: String => String, defaults: Map[String, Any], discriminator: Option[String] ): Decoder.AccumulatingResult[HNil] = if (c.value.isObject) Validated.valid(HNil) else Validated.invalidNel(DecodingFailure("HNil", c.history)) def configuredEncodeObject(a: HNil)( transformMemberNames: String => String, transformDiscriminator: String => String, discriminator: Option[String] ): JsonObject = JsonObject.empty } }