scala.util.Right Scala Examples

The following examples show how to use scala.util.Right. 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: ProduceError.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.common.state.diffs

import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.{Left, Right}

class ProduceError(errorMessage: String) extends Matcher[Either[_, _]] {
  override def apply(ei: Either[_, _]): MatchResult = {
    ei match {
      case r @ Right(_) => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))
      case l @ Left(_) =>
        MatchResult(matches = l.toString contains errorMessage,
                    "expecting Left(...{0}...) but got {1}",
                    "got expected error",
                    IndexedSeq(errorMessage, l))
    }
  }
}

object ProduceError {
  def produce(err: String): Matcher[Either[_, _]] = new ProduceError(err)
} 
Example 2
Source File: EncodersDecodersSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.thirdparty.adminrouter.circe

import com.mesosphere.cosmos.thirdparty.adminrouter.model.DcosVersion
import com.mesosphere.universe.v3.model.DcosReleaseVersion
import com.mesosphere.universe.v3.model.DcosReleaseVersion._
import io.circe.Json
import io.circe.syntax._
import org.scalatest.FreeSpec
import scala.util.Right

class EncodersDecodersSpec extends FreeSpec {

  "DcosVersion" - {
    "decode" in {
      val json = Json.obj(
        "version" -> "1.7.1".asJson,
        "dcos-image-commit" -> "0defde84e7a71ebeb5dfeca0936c75671963df48".asJson,
        "bootstrap-id" -> "f12bff891be7108962c7c98e530e1f2cd8d4e56b".asJson
      )

      val (major, minor, patch) = (1, 7, 1)
      val expected = DcosVersion(
        DcosReleaseVersion(Version(major), List(Version(minor), Version(patch))),
        "0defde84e7a71ebeb5dfeca0936c75671963df48",
        "f12bff891be7108962c7c98e530e1f2cd8d4e56b"
      )

      val Right(actual) = json.as[DcosVersion]
      assertResult(expected)(actual)
    }
  }

} 
Example 3
Source File: JsonSchemaSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.jsonschema

import com.github.fge.jsonschema.main.JsonSchemaFactory
import io.circe.Json
import io.circe.JsonObject
import io.circe.jawn.parse
import io.circe.syntax._
import org.scalatest.FreeSpec
import org.scalatest.Tag
import scala.io.Source
import scala.util.Right

class JsonSchemaSpec extends FreeSpec {

  private[this] implicit val jsf = JsonSchemaFactory.byDefault()

  "JsonSchema should" - {
    "be able to validate a document against a schema" - {
      // the draft v4 json schema itself should be able to validate itself
      val jsonSchemaDraftV4String = classpathJsonString("/draftv4/schema")

      "as io.circe.JsonObject" in {
        val Right(parsedJson: Json) = parse(jsonSchemaDraftV4String)
        val xor = JsonSchema.jsonMatchesSchema(parsedJson, parsedJson)
        assert(xor.isRight)
      }

      "as io.circe.Json" in {
        val Right(parsedJson: Json) = parse(jsonSchemaDraftV4String)
        val jObject: JsonObject = parsedJson.asObject.get
        val xor = JsonSchema.jsonObjectMatchesSchema(jObject, jObject)
        assert(xor.isRight)
      }
    }

    "be able to extract default property values from a schema" - {
      val expected = JsonObject.fromMap(Map(
        "prop1" -> 57.asJson,
        "prop2" -> Json.obj(
          "sub1" -> "ta-da".asJson
        )
      ))

      "when schema does not use definition refs" in {
        val s = classpathJsonString("/com/mesosphere/cosmos/jsonschema/no-definition-ref-used.json")
        val Right(schema) = parse(s)
        val defaults = JsonSchema.extractDefaultsFromSchema(schema.asObject.get)
        assertResult(expected)(defaults)
      }

      "when schema does use definition refs" taggedAs Tag("https://mesosphere.atlassian.net/browse/DCOS-10455") ignore {
        val s = classpathJsonString("/com/mesosphere/cosmos/jsonschema/definition-ref-used.json")
        val Right(schema) = parse(s)
        val defaults = JsonSchema.extractDefaultsFromSchema(schema.asObject.get)
        assertResult(expected)(defaults)
      }

    }
  }

  private[this] def classpathJsonString(resourceName: String): String = {
    Option(this.getClass.getResourceAsStream(resourceName)) match {
      case Some(is) => Source.fromInputStream(is).mkString
      case _ => throw new IllegalStateException(s"Unable to load classpath resource: $resourceName")
    }
  }

} 
Example 4
Source File: DcosReleaseVersionEncoderDecoderSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.universe.v3.circe

import com.mesosphere.universe.v3.model.DcosReleaseVersion
import com.mesosphere.universe.v3.model.DcosReleaseVersion._
import io.circe.Json
import io.circe.jawn.decode
import io.circe.syntax._
import org.scalatest.FreeSpec
import scala.util.Right

class DcosReleaseVersionEncoderDecoderSpec extends FreeSpec {

  "DcosReleaseVersion" - {
    val str = "2.10.153-beta"
    val (major, minor, patch) = (2, 10, 153)
    val subVersions = List(Version(minor), Version(patch))
    val obj = DcosReleaseVersion(Version(major), subVersions, Some(Suffix("beta")))
    "decode"  in {
      val stringToDecode = s""""$str""""
      val Right(decoded) = decode[DcosReleaseVersion](stringToDecode)
      assertResult(obj)(decoded)
    }
    "encode" in {
      assertResult(Json.fromString(str))(obj.asJson)
    }
  }

} 
Example 5
Source File: CapabilitiesHandlerSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.handler

import com.mesosphere.cosmos.http.CosmosRequests
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.cosmos.rpc.v1.model.CapabilitiesResponse
import com.mesosphere.cosmos.rpc.v1.model.Capability
import com.mesosphere.cosmos.test.CosmosIntegrationTestClient._
import com.twitter.finagle.http.Fields
import com.twitter.finagle.http.Status
import io.circe.jawn._
import org.scalatest.FreeSpec
import scala.util.Right

final class CapabilitiesHandlerSpec extends FreeSpec {

  "The capabilities handler should return a document" in {
    val response = CosmosClient.submit(CosmosRequests.capabilities)

    assertResult(Status.Ok)(response.status)
    assertResult(MediaTypes.CapabilitiesResponse.show)(response.headerMap(Fields.ContentType))
    val Right(body) = decode[CapabilitiesResponse](response.contentString)
    val expected = CapabilitiesResponse(List(
      Capability("PACKAGE_MANAGEMENT"),
      Capability("SUPPORT_CLUSTER_REPORT"),
      Capability("METRONOME"),
      Capability("LOGGING"),
      Capability("LOGGING_V2")
    ))
    assertResult(expected)(body)
  }
} 
Example 6
Source File: LTask.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect

import cats.Eq
import cats.effect.internals.Conversions
import cats.effect.laws.util.TestContext
import org.scalacheck.{Arbitrary, Cogen}
import cats.syntax.flatMap._
import cats.syntax.functor._

import scala.concurrent.{ExecutionContext, ExecutionException, Future, Promise}
import scala.util.{Either, Left, Right}


  implicit def effectInstance(implicit ec: ExecutionContext): Effect[LTask] =
    new Effect[LTask] {
      def pure[A](x: A): LTask[A] =
        LTask(_ => Future.successful(x))
      def raiseError[A](e: Throwable): LTask[A] =
        LTask(_ => Future.failed(e))
      def suspend[A](thunk: => LTask[A]): LTask[A] =
        LTask { implicit ec =>
          Future.successful(()).flatMap(_ => thunk.run(ec))
        }

      def async[A](k: (Either[Throwable, A] => Unit) => Unit): LTask[A] =
        LTask { _ =>
          val p = Promise[A]()
          k(r => p.tryComplete(Conversions.toTry(r)))
          p.future
        }

      def asyncF[A](k: (Either[Throwable, A] => Unit) => LTask[Unit]): LTask[A] =
        LTask { implicit ec =>
          val p = Promise[A]()
          k(r => p.tryComplete(Conversions.toTry(r))).run(ec)
          p.future
        }

      def runAsync[A](fa: LTask[A])(cb: Either[Throwable, A] => IO[Unit]): SyncIO[Unit] =
        SyncIO(fa.run(ec).onComplete { r =>
          cb(Conversions.toEither(r)).unsafeRunAsyncAndForget()
        })

      def flatMap[A, B](fa: LTask[A])(f: A => LTask[B]): LTask[B] =
        LTask { implicit ec =>
          Future.successful(()).flatMap { _ =>
            fa.run(ec).flatMap { a =>
              f(a).run(ec)
            }
          }
        }

      def tailRecM[A, B](a: A)(f: A => LTask[Either[A, B]]): LTask[B] =
        flatMap(f(a)) {
          case Left(a)  => tailRecM(a)(f)
          case Right(b) => pure(b)
        }

      def handleErrorWith[A](fa: LTask[A])(f: Throwable => LTask[A]): LTask[A] =
        LTask { implicit ec =>
          Future.successful(()).flatMap { _ =>
            fa.run(ec).recoverWith {
              case err: ExecutionException if err.getCause ne null =>
                f(err.getCause).run(ec)
              case err =>
                f(err).run(ec)
            }
          }
        }

      def bracketCase[A, B](
        acquire: LTask[A]
      )(use: A => LTask[B])(release: (A, ExitCase[Throwable]) => LTask[Unit]): LTask[B] =
        for {
          a <- acquire
          etb <- attempt(use(a))
          _ <- release(a, etb match {
            case Left(e)  => ExitCase.error[Throwable](e)
            case Right(_) => ExitCase.complete
          })
          b <- rethrow(pure(etb))
        } yield b
    }
} 
Example 7
Source File: IOBinaryCompat.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect
package internals

import cats.effect

import scala.annotation.unchecked.uncheckedVariance
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Left, Right, Success}


  @deprecated("ExecutionContext parameter is being removed", "0.10")
  private[internals] def fromFuture[A](iof: IO[Future[A]])(implicit ec: ExecutionContext): IO[A] =
    // $COVERAGE-OFF$
    iof.flatMap { f =>
      IO.async { cb =>
        f.onComplete { r =>
          cb(r match {
            case Success(a) => Right(a)
            case Failure(e) => Left(e)
          })
        }
      }
    }
  // $COVERAGE-ON$
} 
Example 8
Source File: IOFromFuture.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect.internals

import cats.effect.IO
import cats.effect.internals.TrampolineEC.immediate
import scala.concurrent.Future
import scala.util.{Failure, Left, Right, Success}

private[effect] object IOFromFuture {

  
  def apply[A](f: Future[A]): IO[A] =
    f.value match {
      case Some(result) =>
        result match {
          case Success(a) => IO.pure(a)
          case Failure(e) => IO.raiseError(e)
        }
      case _ =>
        IO.async { cb =>
          f.onComplete { r =>
            cb(r match {
              case Success(a) => Right(a)
              case Failure(e) => Left(e)
            })
          }(immediate)
        }
    }
} 
Example 9
Source File: Testing.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.lang
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.lang.v1.compiler.Terms._

import scala.util.{Left, Right}

object Testing {

  def evaluated(i: Any): Either[String, EVALUATED] = i match {
    case s: String        => CONST_STRING(s)
    case s: Long          => Right(CONST_LONG(s))
    case s: Int           => Right(CONST_LONG(s))
    case s: ByteStr       => CONST_BYTESTR(s)
    case s: CaseObj       => Right(s)
    case s: Boolean       => Right(CONST_BOOLEAN(s))
    case a: Seq[_]        => ARR(a.map(x => evaluated(x).explicitGet()).toIndexedSeq, false)
    case _                => Left("Bad Assert: unexprected type")
  }
} 
Example 10
Source File: EncodersDecodersSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.thirdparty.marathon.circe

import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import io.circe.Json
import io.circe.jawn.decode
import io.circe.syntax._
import org.scalatest.FreeSpec
import scala.util.Right

class EncodersDecodersSpec extends FreeSpec {

  "AppId" - {
    val relative: String = "cassandra/dcos"
    val absolute: String = s"/$relative"
    "encode" in {
      assertResult(Json.fromString(absolute))(AppId(relative).asJson)
    }
    "decode" in {
      val id = AppId(absolute)
      val Right(decoded) = decode[AppId](relative.asJson.noSpaces)
      assertResult(id)(decoded)
    }
  }

} 
Example 11
Source File: MicroblockAppender.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.appender

import cats.data.EitherT
import com.wavesplatform.block.Block.BlockId
import com.wavesplatform.block.MicroBlock
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.metrics.{BlockStats, _}
import com.wavesplatform.network.MicroBlockSynchronizer.MicroblockData
import com.wavesplatform.network._
import com.wavesplatform.state.Blockchain
import com.wavesplatform.transaction.BlockchainUpdater
import com.wavesplatform.transaction.TxValidationError.InvalidSignature
import com.wavesplatform.utils.ScorexLogging
import com.wavesplatform.utx.UtxPool
import io.netty.channel.Channel
import io.netty.channel.group.ChannelGroup
import kamon.Kamon
import monix.eval.Task
import monix.execution.Scheduler

import scala.util.{Left, Right}

object MicroblockAppender extends ScorexLogging {
  def apply(blockchainUpdater: BlockchainUpdater with Blockchain, utxStorage: UtxPool, scheduler: Scheduler, verify: Boolean = true)(
      microBlock: MicroBlock
  ): Task[Either[ValidationError, BlockId]] = {

    Task(metrics.microblockProcessingTimeStats.measureSuccessful {
      blockchainUpdater
        .processMicroBlock(microBlock, verify)
        .map { totalBlockId =>
          utxStorage.removeAll(microBlock.transactionData)
          totalBlockId
        }
    }).executeOn(scheduler)
  }

  def apply(
      blockchainUpdater: BlockchainUpdater with Blockchain,
      utxStorage: UtxPool,
      allChannels: ChannelGroup,
      peerDatabase: PeerDatabase,
      scheduler: Scheduler
  )(ch: Channel, md: MicroblockData): Task[Unit] = {
    import md.microBlock
    val microblockTotalResBlockSig = microBlock.totalResBlockSig
    (for {
      _ <- EitherT(Task.now(microBlock.signaturesValid()))
      _ <- EitherT(apply(blockchainUpdater, utxStorage, scheduler)(microBlock))
    } yield ()).value.map {
      case Right(_) =>
        md.invOpt match {
          case Some(mi) => allChannels.broadcast(mi, except = md.microblockOwners())
          case None     => log.warn(s"${id(ch)} Not broadcasting MicroBlockInv")
        }
        BlockStats.applied(microBlock)
      case Left(is: InvalidSignature) =>
        peerDatabase.blacklistAndClose(ch, s"Could not append microblock $microblockTotalResBlockSig: $is")
      case Left(ve) =>
        BlockStats.declined(microBlock)
        log.debug(s"${id(ch)} Could not append microblock $microblockTotalResBlockSig: $ve")
    }
  }

  private[this] object metrics {
    val microblockProcessingTimeStats = Kamon.timer("microblock-appender.processing-time").withoutTags()
  }
} 
Example 12
Source File: LeaseTransactionsDiff.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats._
import cats.implicits._
import com.wavesplatform.account.Address
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.state._
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.TxValidationError.GenericError
import com.wavesplatform.transaction.lease._

import scala.util.{Left, Right}

object LeaseTransactionsDiff {

  def lease(blockchain: Blockchain)(tx: LeaseTransaction): Either[ValidationError, Diff] = {
    val sender = Address.fromPublicKey(tx.sender)
    blockchain.resolveAlias(tx.recipient).flatMap { recipient =>
      if (recipient == sender)
        Left(GenericError("Cannot lease to self"))
      else {
        val lease   = blockchain.leaseBalance(tx.sender.toAddress)
        val balance = blockchain.balance(tx.sender.toAddress, Waves)
        if (balance - lease.out < tx.amount) {
          Left(GenericError(s"Cannot lease more than own: Balance:${balance}, already leased: ${lease.out}"))
        } else {
          val portfolioDiff: Map[Address, Portfolio] = Map(
            sender    -> Portfolio(-tx.fee, LeaseBalance(0, tx.amount), Map.empty),
            recipient -> Portfolio(0, LeaseBalance(tx.amount, 0), Map.empty)
          )
          Right(
            Diff(
              tx = tx,
              portfolios = portfolioDiff,
              leaseState = Map(tx.id() -> true),
              scriptsRun = DiffsCommon.countScriptRuns(blockchain, tx)
            ))
        }
      }
    }
  }

  def leaseCancel(blockchain: Blockchain, time: Long)(tx: LeaseCancelTransaction): Either[ValidationError, Diff] = {
    val fs = blockchain.settings.functionalitySettings

    val leaseEi = blockchain.leaseDetails(tx.leaseId) match {
      case None    => Left(GenericError(s"Related LeaseTransaction not found"))
      case Some(l) => Right(l)
    }
    for {
      lease     <- leaseEi
      recipient <- blockchain.resolveAlias(lease.recipient)
      isLeaseActive = lease.isActive
      _ <- if (!isLeaseActive && time > fs.allowMultipleLeaseCancelTransactionUntilTimestamp)
        Left(GenericError(s"Cannot cancel already cancelled lease"))
      else Right(())
      canceller = Address.fromPublicKey(tx.sender)
      portfolioDiff <- if (tx.sender == lease.sender) {
        Right(
          Monoid.combine(Map(canceller -> Portfolio(-tx.fee, LeaseBalance(0, -lease.amount), Map.empty)),
                         Map(recipient -> Portfolio(0, LeaseBalance(-lease.amount, 0), Map.empty))))
      } else if (time < fs.allowMultipleLeaseCancelTransactionUntilTimestamp) { // cancel of another acc
        Right(
          Monoid.combine(Map(canceller -> Portfolio(-tx.fee, LeaseBalance(0, -lease.amount), Map.empty)),
                         Map(recipient -> Portfolio(0, LeaseBalance(-lease.amount, 0), Map.empty))))
      } else
        Left(
          GenericError(
            s"LeaseTransaction was leased by other sender " +
              s"and time=$time > allowMultipleLeaseCancelTransactionUntilTimestamp=${fs.allowMultipleLeaseCancelTransactionUntilTimestamp}"))

    } yield
      Diff(
        tx = tx,
        portfolios = portfolioDiff,
        leaseState = Map(tx.leaseId -> false),
        scriptsRun = DiffsCommon.countScriptRuns(blockchain, tx)
      )
  }
} 
Example 13
Source File: BalanceDiffValidation.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import com.wavesplatform.account.Address
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.state.{Blockchain, Diff, Portfolio}
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.TxValidationError.AccountBalanceError
import com.wavesplatform.utils.ScorexLogging

import scala.util.{Left, Right}

object BalanceDiffValidation extends ScorexLogging {

  def apply(b: Blockchain)(d: Diff): Either[AccountBalanceError, Diff] = {
    val changedAccounts = d.portfolios.keySet

    def check(acc: Address): Option[(Address, String)] = {
      val portfolioDiff = d.portfolios(acc)

      val balance       = portfolioDiff.balance
      lazy val oldWaves = b.balance(acc, Waves)
      lazy val oldLease = b.leaseBalance(acc)
      lazy val lease    = cats.Monoid.combine(oldLease, portfolioDiff.lease)
      (if (balance < 0) {
         val newB = oldWaves + balance

         if (newB < 0) {
           Some(acc -> s"negative waves balance: $acc, old: $oldWaves, new: $newB")
         } else if (newB < lease.out && b.height > b.settings.functionalitySettings.allowLeasedBalanceTransferUntilHeight) {
           Some(acc -> (if (newB + lease.in - lease.out < 0) {
                          s"negative effective balance: $acc, old: ${(oldWaves, oldLease)}, new: ${(newB, lease)}"
                        } else if (portfolioDiff.lease.out == 0) {
                          s"$acc trying to spend leased money"
                        } else {
                          s"leased being more than own: $acc, old: ${(oldWaves, oldLease)}, new: ${(newB, lease)}"
                        }))
         } else {
           None
         }
       } else {
         None
       }) orElse (portfolioDiff.assets find {
        case (a, c) =>
          // Tokens it can produce overflow are exist.
          val oldB = b.balance(acc, a)
          val newB = oldB + c
          newB < 0
      } map { _ =>
        acc -> s"negative asset balance: $acc, new portfolio: ${negativeAssetsInfo(b, acc, portfolioDiff)}"
      })
    }

    val positiveBalanceErrors: Map[Address, String] = changedAccounts.flatMap(check).toMap

    if (positiveBalanceErrors.isEmpty) {
      Right(d)
    } else {
      Left(AccountBalanceError(positiveBalanceErrors))
    }
  }

  private def negativeAssetsInfo(b: Blockchain, acc: Address, diff: Portfolio): Map[ByteStr, Long] =
    diff.assets
      .map { case (aid, balanceChange) => aid.id -> (b.balance(acc, aid) + balanceChange) }
      .filter(_._2 < 0)
} 
Example 14
Source File: PaymentTransactionDiff.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats.implicits._
import com.wavesplatform.account.Address
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.state.{Blockchain, Diff, LeaseBalance, Portfolio}
import com.wavesplatform.transaction.PaymentTransaction
import com.wavesplatform.transaction.TxValidationError.GenericError

import scala.util.{Left, Right}

object PaymentTransactionDiff {

  def apply(blockchain: Blockchain)(tx: PaymentTransaction): Either[ValidationError, Diff] = {
    val blockVersion3AfterHeight = blockchain.settings.functionalitySettings.blockVersion3AfterHeight
    if (blockchain.height > blockVersion3AfterHeight) {
      Left(GenericError(s"Payment transaction is deprecated after h=$blockVersion3AfterHeight"))
    } else {
      Right(
        Diff(
          tx = tx,
          portfolios = Map(tx.recipient -> Portfolio(balance = tx.amount, LeaseBalance.empty, assets = Map.empty)) combine Map(
            Address.fromPublicKey(tx.sender) -> Portfolio(
              balance = -tx.amount - tx.fee,
              LeaseBalance.empty,
              assets = Map.empty
            ))
        ))
    }
  }
} 
Example 15
Source File: TransferTransactionDiff.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import cats.implicits._
import com.wavesplatform.account.Address
import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.state._
import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves}
import com.wavesplatform.transaction.TxValidationError
import com.wavesplatform.transaction.TxValidationError.GenericError
import com.wavesplatform.transaction.transfer._

import scala.util.{Right, Try}

object TransferTransactionDiff {
  def apply(blockchain: Blockchain, blockTime: Long)(tx: TransferTransaction): Either[ValidationError, Diff] = {
    val sender = Address.fromPublicKey(tx.sender)

    val isSmartAsset = tx.feeAssetId match {
      case Waves => false
      case asset @ IssuedAsset(_) =>
        blockchain
          .assetDescription(asset)
          .flatMap(_.script)
          .isDefined
    }

    for {
      recipient <- blockchain.resolveAlias(tx.recipient)
      _         <- Either.cond(!isSmartAsset, (), GenericError("Smart assets can't participate in TransferTransactions as a fee"))

      _ <- validateOverflow(blockchain, blockchain.height, tx)
      portfolios = (tx.assetId match {
        case Waves =>
          Map(sender -> Portfolio(-tx.amount, LeaseBalance.empty, Map.empty)).combine(
            Map(recipient -> Portfolio(tx.amount, LeaseBalance.empty, Map.empty))
          )
        case asset @ IssuedAsset(_) =>
          Map(sender -> Portfolio(0, LeaseBalance.empty, Map(asset -> -tx.amount))).combine(
            Map(recipient -> Portfolio(0, LeaseBalance.empty, Map(asset -> tx.amount)))
          )
      }).combine(
        tx.feeAssetId match {
          case Waves => Map(sender -> Portfolio(-tx.fee, LeaseBalance.empty, Map.empty))
          case asset @ IssuedAsset(_) =>
            val senderPf = Map(sender -> Portfolio(0, LeaseBalance.empty, Map(asset -> -tx.fee)))
            if (blockchain.height >= Sponsorship.sponsoredFeesSwitchHeight(blockchain)) {
              val sponsorPf = blockchain
                .assetDescription(asset)
                .collect {
                  case desc if desc.sponsorship > 0 =>
                    val feeInWaves = Sponsorship.toWaves(tx.fee, desc.sponsorship)
                    Map(desc.issuer.toAddress -> Portfolio(-feeInWaves, LeaseBalance.empty, Map(asset -> tx.fee)))
                }
                .getOrElse(Map.empty)
              senderPf.combine(sponsorPf)
            } else senderPf
        }
      )
      assetIssued    = tx.assetId.fold(true)(blockchain.assetDescription(_).isDefined)
      feeAssetIssued = tx.feeAssetId.fold(true)(blockchain.assetDescription(_).isDefined)
      _ <- Either.cond(
        blockTime <= blockchain.settings.functionalitySettings.allowUnissuedAssetsUntil || (assetIssued && feeAssetIssued),
        (),
        GenericError(
          s"Unissued assets are not allowed after allowUnissuedAssetsUntil=${blockchain.settings.functionalitySettings.allowUnissuedAssetsUntil}"
        )
      )
    } yield Diff(
      tx,
      portfolios,
      scriptsRun = DiffsCommon.countScriptRuns(blockchain, tx)
    )
  }

  private def validateOverflow(blockchain: Blockchain, height: Int, tx: TransferTransaction) = {
    if (blockchain.isFeatureActivated(BlockchainFeatures.Ride4DApps, height)) {
      Right(()) // lets transaction validates itself
    } else {
      Try(Math.addExact(tx.fee, tx.amount))
        .fold(
          _ => TxValidationError.OverflowError.asLeft[Unit],
          _ => ().asRight[ValidationError]
        )
    }
  }
} 
Example 16
Source File: CreateAliasTransactionDiff.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.state.diffs

import com.wavesplatform.features.BlockchainFeatures
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.state.{Blockchain, Diff, LeaseBalance, Portfolio}
import com.wavesplatform.transaction.CreateAliasTransaction
import com.wavesplatform.transaction.TxValidationError.GenericError

import scala.util.Right

object CreateAliasTransactionDiff {
  def apply(blockchain: Blockchain)(tx: CreateAliasTransaction): Either[ValidationError, Diff] =
    if (blockchain.isFeatureActivated(BlockchainFeatures.DataTransaction, blockchain.height) && !blockchain.canCreateAlias(tx.alias))
      Left(GenericError("Alias already claimed"))
    else
      Right(
        Diff(
          tx = tx,
          portfolios = Map(tx.sender.toAddress -> Portfolio(-tx.fee, LeaseBalance.empty, Map.empty)),
          aliases = Map(tx.alias               -> tx.sender.toAddress),
          scriptsRun = DiffsCommon.countScriptRuns(blockchain, tx)
        )
      )
} 
Example 17
Source File: ReadInstances.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc
package protocol

import cats.{Contravariant, Monad}

import scala.util.{Left, Right}

private[protocol] object ReadInstances {
  implicit def readContravariant[X]: Contravariant[* ==> X] =
    new Contravariant[* ==> X] {
      override def contramap[A, B](fa: A ==> X)(f: B => A): B ==> X = fa.contramap(f)
    }

  implicit def readMonad[X]: Monad[X ==> *] =
    new Monad[X ==> *] {
      override def pure[A](x: A): X ==> A                               = Read.const(x)
      override def flatMap[A, B](fa: X ==> A)(f: A => X ==> B): X ==> B = fa.flatMap(f)
      override def tailRecM[A, B](a: A)(f: A => X ==> Either[A, B]): X ==> B =
        flatMap(f(a)) {
          case Left(a)  => tailRecM(a)(f)
          case Right(b) => pure(b)
        }
    }
} 
Example 18
Source File: typeable.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.shapeless

import _root_.shapeless.Typeable
import eu.timepit.refined.api.{RefType, Validate}
import scala.util.Right

package object typeable {

  
  implicit def refTypeTypeable[F[_, _], T, P](
      implicit rt: RefType[F],
      V: Validate[T, P],
      T: Typeable[T],
      P: Typeable[P]
  ): Typeable[F[T, P]] =
    new Typeable[F[T, P]] {
      override def cast(t: Any): Option[F[T, P]] =
        T.cast(t)
          .flatMap(casted =>
            rt.refine[P](casted) match {
              case Right(v) => Some(v)
              case _        => None
            }
          )
      override def describe: String = s"Refined[${T.describe}, ${P.describe}]"
    }
} 
Example 19
Source File: DefaultRepositories.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.repository

import com.google.common.io.CharStreams
import com.mesosphere.cosmos.rpc
import com.twitter.util.Try
import io.circe.jawn.decode
import java.io.InputStreamReader
import scala.util.Either
import scala.util.Left
import scala.util.Right

private[repository] class DefaultRepositories private[repository](resourceName: String) {
  private val repos: Try[Either[io.circe.Error, List[rpc.v1.model.PackageRepository]]] = Try {
    Option(this.getClass.getResourceAsStream(resourceName)) match {
      case Some(is) =>
        val json = CharStreams.toString(new InputStreamReader(is))
        decode[List[rpc.v1.model.PackageRepository]](json)
      case _ =>
        throw new IllegalStateException(s"Unable to load classpath resource: $resourceName")
    }
  }
}

object DefaultRepositories {
  private[this] val loaded = new DefaultRepositories("/default-repositories.json")

  def apply(): DefaultRepositories = loaded

  implicit class DefaultRepositoriesOps(val dr: DefaultRepositories) extends AnyVal {
    def get(): Try[Either[io.circe.Error, List[rpc.v1.model.PackageRepository]]] = {
      dr.repos
    }

    def getOrThrow: List[rpc.v1.model.PackageRepository] = {
      get().map {
        case Right(list) => list
        case Left(err) => throw err
      }.get
    }

    def getOrElse(
      orElse: List[rpc.v1.model.PackageRepository]
    ): List[rpc.v1.model.PackageRepository] = {
      get().map(_.getOrElse(orElse)).getOrElse(orElse)
    }
  }

} 
Example 20
Source File: Committable.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.data

import aecor.Has
import cats.implicits._
import cats.{ Applicative, Eval, Functor, Monad, Traverse }

import scala.util.{ Left, Right }

final case class Committable[F[_], +A](commit: F[Unit], value: A) {
  def map[B](f: A => B): Committable[F, B] = copy(value = f(value))
  def traverse[G[_], B](f: A => G[B])(implicit G: Functor[G]): G[Committable[F, B]] =
    G.map(f(value))(b => copy(value = b))
  def process[B](f: A => F[B])(implicit F: Monad[F]): F[B] = f(value) <* commit
}

object Committable {
  implicit def aecorHasInstance[F[_], A, B](implicit B: Has[B, A]): Has[Committable[F, B], A] =
    B.contramap(_.value)

  implicit def catsMonadAndTraversInstance[F[_]: Applicative]
    : Monad[Committable[F, *]] with Traverse[Committable[F, *]] =
    new Monad[Committable[F, *]] with Traverse[Committable[F, *]] {
      override def traverse[G[_], A, B](
        fa: Committable[F, A]
      )(f: (A) => G[B])(implicit evidence$1: Applicative[G]): G[Committable[F, B]] =
        fa.traverse(f)

      override def flatMap[A, B](
        fa: Committable[F, A]
      )(f: (A) => Committable[F, B]): Committable[F, B] =
        f(fa.value)

      override def tailRecM[A, B](
        a: A
      )(f: (A) => Committable[F, Either[A, B]]): Committable[F, B] = {
        val c = f(a)
        c.value match {
          case Left(aa) => tailRecM(aa)(f)
          case Right(b) => c.copy(value = b)
        }
      }

      override def foldLeft[A, B](fa: Committable[F, A], b: B)(f: (B, A) => B): B =
        f(b, fa.value)

      override def foldRight[A, B](fa: Committable[F, A], lb: Eval[B])(
        f: (A, Eval[B]) => Eval[B]
      ): Eval[B] = f(fa.value, lb)

      override def pure[A](x: A): Committable[F, A] = Committable.pure(x)
    }
  def pure[F[_]: Applicative, A](a: A): Committable[F, A] = Committable(().pure[F], a)
  def unit[F[_]: Applicative]: Committable[F, Unit] = pure(())
  def collector[F[_], A, B](
    pf: PartialFunction[A, B]
  ): PartialFunction[Committable[F, A], Committable[F, B]] = {
    case c if pf.isDefinedAt(c.value) => c.map(pf)
  }
} 
Example 21
Source File: EitherValuesSpec.scala    From cats-scalatest   with Apache License 2.0 5 votes vote down vote up
package cats.scalatest

import org.scalatest.exceptions.TestFailedException
import scala.util.{Either, Left, Right}

class EitherValuesSpec extends TestBase {
  import EitherValues._

  "value on Either" should {
    "return the value inside a Right if that Either is Right" in {
      val r: String Either String = Right(thisRecord)
      r.value should ===(thisRecord)
    }

    "should throw TestFailedException if that Either is a left " in {
      val r: String Either String = Left(thisTobacconist)
      val caught =
        intercept[TestFailedException] {
          r.value should ===(thisRecord)
        }
      if (isJVM)
        caught.failedCodeLineNumber.value should equal(thisLineNumber - 3)
      caught.failedCodeFileName.value should be("EitherValuesSpec.scala")
    }
  }

  "leftValue on Either" should {
    "return the value if it's left" in {
      val r = Left(thisRecord)
      r.leftValue should ===(thisRecord)
    }

    "throw TestFailedException if the Either is right" in {
      val r = Right(thisRecord)
      val caught = intercept[TestFailedException] {
        r.leftValue
      }
      if (isJVM)
        caught.failedCodeLineNumber.value should equal(thisLineNumber - 3)
      caught.failedCodeFileName.value should be("EitherValuesSpec.scala")
    }
  }
} 
Example 22
Source File: EitherMatchersSpec.scala    From cats-scalatest   with Apache License 2.0 5 votes vote down vote up
package cats.scalatest

import scala.util.{Left, Right}

class EitherMatchersSpec extends TestBase with EitherMatchers {
  val goodHovercraft = Right(hovercraft)
  val badTobacconist = Left(thisTobacconist)
  val badRecord = Left(thisRecord)

  "EitherMatchers" should {
    "Match 'blind' invalid (i.e. not with specific element)" in {
      badTobacconist should be(left)
    }
    "Match 'valued' left disjunction syntax" in {
      badTobacconist should beLeft(thisTobacconist)
    }
    "Match 'valued' right disjunction syntax" in {
      goodHovercraft should beRight(hovercraft)
    }
    "Match 'blind' right disjunction syntax (i.e. with no specific element)" in {
      goodHovercraft should be(right)
    }
    "Match negation of left when it's right" in {
      goodHovercraft should not be left
    }
    "Match negation of right when it's left" in {
      badRecord should not be right
    }
  }
} 
Example 23
Source File: ParsebackSpec.scala    From parseback   with Apache License 2.0 5 votes vote down vote up
package parseback

import cats.Eval

import org.specs2.matcher.Matcher
import org.specs2.mutable._
import org.specs2.specification.SpecificationFeatures

import scala.util.{Left, Right}

trait ParsebackSpec extends Spec with SpecificationFeatures {

  final def recognize[A](input: String, ambiguous: Boolean = true)(implicit W: Whitespace): Matcher[Parser[A]] = { p: Parser[A] =>
    val maybeResults = p(LineStream[Eval](input)).value

    maybeResults match {
      case Right(results) =>
        (ambiguous || results.toList.length == 1,    // TODO implement lengthCompare
          s"recognized '$input'",
          s"recognized '$input', but with multiple results: $results")

      case Left(err) =>
        (false, "", s"failed to recognize '$input' with error $err")
    }
  }

  final def recognizeUnambiguously[A](input: String) = recognize[A](input, false)

  final def parseOk[A](input: String)(results: A*)(implicit W: Whitespace): Matcher[Parser[A]] = { p: Parser[A] =>
    val maybeResults = p(LineStream[Eval](input)).value

    maybeResults match {
      case Right(actual) =>
        val actualList = actual.toList
        val permuted = actualList flatMap { a => results map { b => (a, b) } }

        val compared = permuted filter {
          case (a, b) => a == b
        }

        (results.length == actualList.length && compared.length == results.length,
          s"accepted '$input' with results $actual",
          s"accepted '$input' but produced results $actualList, expected $results")

      case Left(err) =>
        (false, "", s"failed to parse '$input' with error $err")
    }
  }

  final def failToParse(input: String)(errors: ParseError*)(implicit W: Whitespace): Matcher[Parser[_]] = { p: Parser[_] =>
    val maybeResults = p(LineStream[Eval](input)).value

    maybeResults match {
      case Right(results) =>
        (false, "", s"failed to reject '$input' with results $results")

      case Left(actual) =>
        val permuted = actual flatMap { a => errors map { b => (a, b) } }

        val compared = permuted filter {
          case (a, b) => a == b
        }

        (errors.length == actual.length && compared.length == errors.length,
          s"rejected '$input' with errors $actual",
          s"rejected '$input' with errors $actual, expected $errors")
    }
  }
} 
Example 24
Source File: Results.scala    From parseback   with Apache License 2.0 5 votes vote down vote up
package parseback

import util.Catenable
import util.Catenable.Syntax

import scala.util.{Either, Left, Right}

// semantics must mirror Nullable
sealed trait Results[+A] {
  import Results._

  final def map[B](f: A => B): Results[B] = this pmap { _ map f }

  final def pmap[B](f: Catenable[A] => Catenable[B]): Results[B] = this match {
    case Success(values) => Success(f(values))
    case Failure(errors) => Failure(errors)
    case Hypothetical(errors) => Hypothetical(errors)
  }

  // error merging is not commutative
  final def &&[B](that: Results[B]): Results[(A, B)] = (this, that) match {
    case (Success(v1), Success(v2)) => Success(v1 flatMap { a => v2 map { b => (a, b) } })
    case (Success(_), Failure(e)) => Failure(e)
    case (Failure(e), Success(_)) => Failure(e)
    case (Failure(e), Failure(_)) => Failure(e)
    case (Failure(e), Hypothetical(_)) => Failure(e)
    case (Hypothetical(h), Failure(_)) => Failure(h)
    case (Success(_), Hypothetical(h)) => Hypothetical(h)
    case (Hypothetical(h), Success(_)) => Hypothetical(h)
    case (Hypothetical(h1), Hypothetical(h2)) => Hypothetical(ParseError.prioritize(h1 ::: h2))
  }

  final def ||[B >: A](that: Results[B]): Results[B] = (this, that) match {
    case (Success(v1), Success(v2)) => Success(v1 ++ v2)
    case (Success(v), Failure(_)) => Success(v)
    case (Failure(_), Success(v)) => Success(v)
    case (Failure(e1), Failure(e2)) => Failure(ParseError.prioritize(e1 ::: e2))
    case (Failure(e), Hypothetical(h)) => Hypothetical(ParseError.prioritize(e ::: h))
    case (Hypothetical(h), Failure(e)) => Hypothetical(ParseError.prioritize(e ::: h))
    case (Success(v), Hypothetical(_)) => Success(v)
    case (Hypothetical(_), Success(v)) => Success(v)
    case (Hypothetical(h1), Hypothetical(h2)) => Hypothetical(ParseError.prioritize(h1 ::: h2))
  }

  final def toEither: Either[List[ParseError], Catenable[A]] = this match {
    case Success(results) => Right(results)
    case Failure(errors) => Left(errors)
    case Hypothetical(errors) => Left(errors)
  }
}

object Results {
  sealed trait Cacheable[+A] extends Results[A]

  final case class Success[+A](values: Catenable[A]) extends Cacheable[A]
  final case class Failure(errors: List[ParseError]) extends Cacheable[Nothing]
  final case class Hypothetical(errors: List[ParseError]) extends Results[Nothing]
} 
Example 25
Source File: DeliverySchemeSpec.scala    From sangria   with Apache License 2.0 5 votes vote down vote up
package sangria.parser

import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class DeliverySchemeSpec extends AnyWordSpec with Matchers {
  "DeliveryScheme" should {
    "by default support `Try`" in {
      import scala.util.{Success, Failure}

      QueryParser.parse("{ field }") shouldBe a [Success[_]]
      QueryParser.parse("}") shouldBe a [Failure[_]]
    }

    "support `Either`" in {
      import sangria.parser.DeliveryScheme.Either
      import scala.util.{Left, Right}

      QueryParser.parse("{ field }") shouldBe a [Right[_, _]]
      QueryParser.parse("}") shouldBe a [Left[_, _]]
    }

    "support exception throwing" in {
      import sangria.parser.DeliveryScheme.Throw
      import sangria.ast.Document

      QueryParser.parse("{ field }") shouldBe a [Document]
      a [SyntaxError] should be thrownBy QueryParser.parse("}")
    }
  }
} 
Example 26
Source File: JsonInnerEngine.scala    From Soteria   with MIT License 5 votes vote down vote up
package com.leobenkel.soteria.Utils.Json

import com.github.ghik.silencer.silent
import com.leobenkel.soteria.Utils.Json.FilterNulls._
import com.leobenkel.soteria.Utils.Json.JsonDecode.Encoder

import scala.util.parsing.json._
import scala.util.{Either, Left, Right, Try}


@silent("deprecated")
private[Json] object JsonInnerEngine {
  def parse[A](
    input:  String,
    parser: JsonDecode.Parser[A]
  ): Either[String, A] = {
    Try(
      JSON
        .parseFull(input)
        .map(_.asInstanceOf[Map[String, Any]])
    ).toEither.left
      .map(_.toString)
      .right.flatMap {
        case None => Left("Did not parse")
        case Some(v) =>
          parser(v) match {
            case Right(vv) => Right(vv)
            case Left(ex)  => Left(s"The parser failed: $ex")
          }
      }
  }

  private def unsafeConvert[A <: Encoder](input: A): Map[String, Any] = {
    input.toJsonStructure.right.get
  }

  private def convert(input: Map[_, _]): Map[String, Any] = {
    input.filterNullsOut
      .mapValues {
        case v: JsonDecode.Encoder => JSONObject(convert(unsafeConvert(v)))
        case v: Map[_, _]          => JSONObject(convert(v))
        case v: List[_]            => JSONArray(v)
        case v => v
      }
  }

  def encode[A <: Encoder](input: A): Either[String, String] = {
    input.toJsonStructure.right
      .flatMap(
        inputMap =>
          Try(
            JSONObject
              .apply(convert(inputMap))
              .toString(JSONFormat.defaultFormatter)
          ).toEither.left
            .map(_.toString)
      )
  }
} 
Example 27
Source File: try.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import cats.{ Applicative, CoflatMap, Eq, Eval, MonadError, Monoid, Semigroup, Traverse }
import com.twitter.util.{ Return, Throw, Try }
import java.lang.Throwable
import scala.{ Boolean, inline }
import scala.annotation.tailrec
import scala.util.{ Either, Left, Right }

trait TryInstances extends TryInstances1 {
  implicit final def twitterTryEq[A](implicit A: Eq[A], T: Eq[Throwable]): Eq[Try[A]] =
    new Eq[Try[A]] {
      def eqv(x: Try[A], y: Try[A]): Boolean = (x, y) match {
        case (Throw(xError), Throw(yError))   => T.eqv(xError, yError)
        case (Return(xValue), Return(yValue)) => A.eqv(xValue, yValue)
        case _                                => false
      }
    }

  implicit final def twitterTrySemigroup[A](implicit A: Semigroup[A]): Semigroup[Try[A]] =
    new TrySemigroup[A]

  implicit final val twitterTryInstance: MonadError[Try, Throwable] with CoflatMap[Try] with Traverse[Try] =
    new MonadError[Try, Throwable] with CoflatMap[Try] with Traverse[Try] {
      final def pure[A](x: A): Try[A] = Return(x)
      final def flatMap[A, B](fa: Try[A])(f: A => Try[B]): Try[B] = fa.flatMap(f)
      override final def map[A, B](fa: Try[A])(f: A => B): Try[B] = fa.map(f)

      final def handleErrorWith[A](fa: Try[A])(f: Throwable => Try[A]): Try[A] = fa.rescue {
        case e => f(e)
      }
      final def raiseError[A](e: Throwable): Try[A] = Throw(e)

      final def coflatMap[A, B](ta: Try[A])(f: Try[A] => B): Try[B] = Try(f(ta))

      final def foldLeft[A, B](fa: Try[A], b: B)(f: (B, A) => B): B = fa match {
        case Return(a) => f(b, a)
        case Throw(_)  => b
      }

      final def foldRight[A, B](fa: Try[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] = fa match {
        case Return(a) => f(a, lb)
        case Throw(_)  => lb
      }

      final def traverse[G[_], A, B](fa: Try[A])(f: A => G[B])(implicit G: Applicative[G]): G[Try[B]] = fa match {
        case Return(a)   => G.map(f(a))(Return(_))
        case t: Throw[_] => G.pure(TryInstances.castThrow[B](t))
      }

      @tailrec final def tailRecM[A, B](a: A)(f: A => Try[Either[A, B]]): Try[B] = f(a) match {
        case t: Throw[_]      => TryInstances.castThrow[B](t)
        case Return(Left(a1)) => tailRecM(a1)(f)
        case Return(Right(b)) => Return(b)
      }
    }
}

private[util] final object TryInstances {
  @inline final def castThrow[A](t: Throw[_]): Try[A] = t.asInstanceOf[Try[A]]
}

private[util] trait TryInstances1 {
  implicit final def twitterTryMonoid[A](implicit A: Monoid[A]): Monoid[Try[A]] =
    new TrySemigroup[A] with Monoid[Try[A]] {
      final def empty: Try[A] = Return(A.empty)
    }
}

private[util] class TrySemigroup[A](implicit A: Semigroup[A]) extends Semigroup[Try[A]] {
  final def combine(fx: Try[A], fy: Try[A]): Try[A] = fx.flatMap(x => fy.map(y => A.combine(x, y)))
} 
Example 28
Source File: var.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util

import cats.{ CoflatMap, Comonad, Eq, Monad, Monoid, Semigroup }
import com.twitter.util.Var
import scala.Boolean
import scala.util.{ Either, Left, Right }

trait VarInstances extends VarInstances1 {
  implicit final val twitterVarInstance: Monad[Var] with CoflatMap[Var] =
    new VarCoflatMap with Monad[Var] {
      final def pure[A](x: A): Var[A] = Var.value(x)
      final def flatMap[A, B](fa: Var[A])(f: A => Var[B]): Var[B] = fa.flatMap(f)
      override final def map[A, B](fa: Var[A])(f: A => B): Var[B] = fa.map(f)
    }

  implicit final def twitterVarSemigroup[A](implicit A: Semigroup[A]): Semigroup[Var[A]] =
    new VarSemigroup[A]

  final def varEq[A](implicit A: Eq[A]): Eq[Var[A]] =
    new Eq[Var[A]] {
      final def eqv(fx: Var[A], fy: Var[A]): Boolean = Var.sample(
        fx.join(fy).map {
          case (x, y) => A.eqv(x, y)
        }
      )
    }
}

trait VarInstances1 {
  final def varComonad: Comonad[Var] = new VarCoflatMap with Comonad[Var] {
    final def extract[A](x: Var[A]): A = Var.sample(x)
    final def map[A, B](fa: Var[A])(f: A => B): Var[B] = fa.map(f)
  }

  implicit final def twitterVarMonoid[A](implicit A: Monoid[A]): Monoid[Var[A]] =
    new VarSemigroup[A] with Monoid[Var[A]] {
      final def empty: Var[A] = Var.value(A.empty)
    }
}

private[util] abstract class VarCoflatMap extends CoflatMap[Var] {
  final def coflatMap[A, B](fa: Var[A])(f: Var[A] => B): Var[B] = Var(f(fa))

  
  final def tailRecM[A, B](a: A)(f: A => Var[Either[A, B]]): Var[B] = f(a).flatMap {
    case Left(a1) => tailRecM(a1)(f)
    case Right(b) => Var.value(b)
  }
}

private[util] class VarSemigroup[A](implicit A: Semigroup[A]) extends Semigroup[Var[A]] {
  final def combine(fx: Var[A], fy: Var[A]): Var[A] = fx.join(fy).map {
    case (x, y) => A.combine(x, y)
  }
} 
Example 29
Source File: RerunnableInstances.scala    From catbird   with Apache License 2.0 5 votes vote down vote up
package io.catbird.util.effect

import cats.effect.{ Effect, ExitCase, IO, SyncIO }
import com.twitter.util.{ Future, Monitor, Promise, Return, Throw }
import io.catbird.util.{ Rerunnable, RerunnableMonadError }
import java.lang.Throwable
import scala.Unit
import scala.util.{ Either, Left, Right }

trait RerunnableInstances {
  implicit final val rerunnableEffectInstance: Effect[Rerunnable] =
    new RerunnableMonadError with Effect[Rerunnable] {
      final def suspend[A](thunk: => Rerunnable[A]): Rerunnable[A] = Rerunnable.suspend[A](thunk)

      override final def delay[A](thunk: => A): Rerunnable[A] = Rerunnable[A](thunk)

      final def async[A](k: (Either[Throwable, A] => Unit) => Unit): Rerunnable[A] =
        new Rerunnable[A] {
          final def run: Future[A] = {
            val promise = new Promise[A]

            k { e =>
              if (promise.isDefined) ()
              else
                e match {
                  case Right(a)  => promise.setValue(a)
                  case Left(err) => promise.setException(err)
                }
            }

            promise
          }
        }

      final def asyncF[A](k: (Either[Throwable, A] => Unit) => Rerunnable[Unit]): Rerunnable[A] =
        new Rerunnable[A] {
          final def run: Future[A] = {
            val promise = new Promise[A]

            val rerunnable = k { e =>
              if (promise.isDefined) ()
              else
                e match {
                  case Right(a)  => promise.setValue(a)
                  case Left(err) => promise.setException(err)
                }
            }

            rerunnable.run.flatMap(_ => promise)
          }
        }

      final def runAsync[A](fa: Rerunnable[A])(cb: Either[Throwable, A] => IO[Unit]): SyncIO[Unit] =
        rerunnableToIO[A](fa).runAsync(cb)

      final def bracketCase[A, B](acquire: Rerunnable[A])(use: A => Rerunnable[B])(
        release: (A, ExitCase[Throwable]) => Rerunnable[Unit]
      ): Rerunnable[B] = new Rerunnable[B] {
        final def run: Future[B] =
          acquire.run.flatMap { a =>
            val future = use(a).run
            future.transform {
              case Return(b)  => release(a, ExitCase.complete).run.handle(Monitor.catcher).flatMap(_ => future)
              case Throw(err) => release(a, ExitCase.error(err)).run.handle(Monitor.catcher).flatMap(_ => future)
            }
          }
      }
    }
} 
Example 30
Source File: BaseResource.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.resources

import org.joda.time.DateTime
import play.api.Logger
import play.api.mvc.{ActionBuilder, _}
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.play.bootstrap.controller.BackendController
import uk.gov.hmrc.vatapi.auth.{Agent, AuthContext}
import uk.gov.hmrc.vatapi.services.AuthorisationService

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Right

abstract class BaseResource(cc: ControllerComponents) extends BackendController(cc) {
  val authService: AuthorisationService

  val logger: Logger = Logger(this.getClass)

  def AuthAction(vrn: Vrn, nrsRequired: Boolean = false)(implicit ec: ExecutionContext): ActionRefiner[Request, AuthRequest] = new ActionRefiner[Request, AuthRequest] {
    logger.debug(s"[BaseResource][AuthAction] Check MTD VAT authorisation for the VRN : $vrn")

    override def executionContext: ExecutionContext = ec

    override protected def refine[A](request: Request[A]): Future[Either[Result, AuthRequest[A]]] = {
      implicit val ev: Request[A] = request
      nrsRequired match {
        case false =>
          authService.authCheck(vrn) map {
            case Right(authContext) => Right(new AuthRequest(authContext, request))
            case Left(authError) => Left(authError)
          }
        case true =>
          authService.authCheckWithNrsRequirement(vrn) map {
            case Right(authContext) => Right(new AuthRequest(authContext, request))
            case Left(authError) => Left(authError)
          }
      }
    }
  }

  def APIAction(vrn: Vrn, nrsRequired: Boolean = false)(implicit ec: ExecutionContext): ActionBuilder[AuthRequest, AnyContent] = Action andThen AuthAction(vrn, nrsRequired)

  def getRequestDateTimestamp(implicit request: AuthRequest[_]): String = {
    val requestTimestampHeader = "X-Request-Timestamp"
    val requestTimestamp = request.headers.get(requestTimestampHeader) match {
      case Some(timestamp) if timestamp.trim.length > 0 => timestamp.trim
      case _ =>
        logger.warn(s"$requestTimestampHeader header is not passed or is empty in the request.")
        DateTime.now().toString()
    }
    requestTimestamp
  }

  def getArn(implicit request: AuthRequest[_]): Option[String] = {
    request.authContext match {
      case Agent(_, _, _, enrolments) => enrolments.getEnrolment("HMRC-AS-AGENT").flatMap(_.getIdentifier("AgentReferenceNumber")).map(_.value)
      case c: AuthContext => c.agentReference
    }
  }

  def getClientId(implicit request: AuthRequest[_]): String = request.headers.get("X-Client-Id").getOrElse("N/A")

}

class AuthRequest[A](val authContext: AuthContext, request: Request[A]) extends WrappedRequest[A](request) 
Example 31
Source File: refs.scala    From benchmarks   with Apache License 2.0 5 votes vote down vote up
import sbt._

import scala.util.{Either, Left, Right}

trait Fs2Refs {
  def repo: Either[URI, File]

  lazy val fs2Core = repo.fold(ProjectRef(_, "coreJVM"), ProjectRef(_, "coreJVM"))
  lazy val fs2IO = repo.fold(ProjectRef(_, "io"), ProjectRef(_, "io"))
}

object github extends Fs2Refs {
  val repo = Left(uri("git://github.com/functional-streams-for-scala/fs2.git#01ec76b"))
}

object local extends Fs2Refs {
  val repo = Right(file("..") / "fs2")
} 
Example 32
Source File: FailWith.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.matchers

import com.wavesplatform.dex.it.api.responses.dex.MatcherError
import com.wavesplatform.dex.it.api.responses.dex.MatcherError.Params
import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.{Left, Right}

class FailWith(expectedErrorCode: Int, expectedMessagePart: Option[String] = None, expectedParams: Params = Params())
    extends Matcher[Either[MatcherError, Any]] {

  override def apply(input: Either[MatcherError, Any]): MatchResult = result(
    matches = input match {
      case Right(_) => false
      case Left(e) =>
        e.error == expectedErrorCode && expectedMessagePart.forall(e.message.contains) && (
          expectedParams.isEmpty || e.params.exists(Params.contains(_, expectedParams))
        )
    },
    input
  )

  private def result(matches: Boolean, r: Either[MatcherError, Any]): MatchResult =
    MatchResult(
      matches = matches,
      s"expecting Left(MatcherError(errorCode={0}, expectedMessagePart={1} params={2})) but got {3}",
      "got expected error",
      IndexedSeq(expectedErrorCode, expectedMessagePart, expectedParams, r)
    )
} 
Example 33
Source File: ProduceError.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.test.matchers

import org.scalatest.matchers.{MatchResult, Matcher}

import scala.util.matching.Regex
import scala.util.{Left, Right}

object ProduceError {

  def produce(errorPattern: Regex): Matcher[Either[_, _]] = {
    case r @ Right(_) => MatchResult(matches = false, "expecting {0} to be Left and match: {1}", "got expected error", IndexedSeq(r, errorPattern))
    case Left(l) =>
      MatchResult(
        matches = errorPattern.findFirstIn(l.toString).isDefined,
        rawFailureMessage = "expecting {0} to match: {1}",
        rawNegatedFailureMessage = "got expected error",
        args = IndexedSeq(l, errorPattern)
      )
  }

  def produce(errorMessage: String): Matcher[Either[_, _]] = {
    case r @ Right(_) => MatchResult(matches = false, "expecting Left(...{0}...) but got {1}", "got expected error", IndexedSeq(errorMessage, r))
    case l @ Left(_) =>
      MatchResult(
        matches = l.toString contains errorMessage,
        rawFailureMessage = "expecting Left(...{0}...) but got {1}",
        rawNegatedFailureMessage = "got expected error",
        args = IndexedSeq(errorMessage, l)
      )
  }
}