scala.concurrent.ExecutionException Scala Examples

The following examples show how to use scala.concurrent.ExecutionException. 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: PhaseCache.scala    From Converter   with GNU General Public License v3.0 5 votes vote down vote up
package org.scalablytyped.converter.internal.phases

import java.nio.channels.{ClosedByInterruptException, FileLockInterruptionException}
import java.util

import org.scalablytyped.converter.internal.phases.PhaseCache.Ref

import scala.concurrent.{ExecutionException, Future, Promise}
import scala.util.control.NonFatal

class PhaseCache[Id, U](initialCapacity: Int = 1000) {
  private val m: util.Map[Ref[(Id, IsCircular)], Ref[Future[PhaseRes[Id, U]]]] =
    new util.HashMap(initialCapacity)

  def getOrElse(key: (Id, IsCircular))(compute: Promise[PhaseRes[Id, U]] => Unit): Future[PhaseRes[Id, U]] = {
    val keyRef = new Ref(key)
    var op: Option[Promise[PhaseRes[Id, U]]] = None

    val ret = synchronized {
      val existingFuture: Option[Future[PhaseRes[Id, U]]] =
        m.get(keyRef) match {
          case null => None
          case uRef =>
            uRef.get match {
              case null => None
              case u    => Some(u)
            }
        }

      existingFuture match {
        case None =>
          val p      = Promise[PhaseRes[Id, U]]()
          val future = p.future
          m.put(keyRef, new Ref(future))
          op = Some(p)
          future
        case Some(found) => found
      }
    }

    op.foreach { p =>
      try compute(p)
      catch {
        case x: FileLockInterruptionException            => throw x
        case x: InterruptedException                     => throw x
        case x: ClosedByInterruptException               => throw x
        case x: ExecutionException if x.getCause != null => p.failure(x.getCause)
        case NonFatal(th) => p.failure(th)
      }
    }

    ret
  }
}

object PhaseCache {
  private final class Ref[T](t: T) extends java.lang.ref.SoftReference[T](t) {
    override def equals(obj: Any): Boolean =
      obj match {
        case that: Ref[_] => that.get == get
        case _ => false
      }

    override def hashCode: Int = get.##
  }
} 
Example 2
Source File: PhaseRes.scala    From Converter   with GNU General Public License v3.0 5 votes vote down vote up
package org.scalablytyped.converter.internal.phases

import java.nio.channels.{ClosedByInterruptException, FileLockInterruptionException}

import com.olvind.logging.Logger
import com.olvind.logging.Logger.LoggedException

import scala.collection.immutable.{SortedMap, TreeMap}
import scala.concurrent.ExecutionException
import scala.util.control.NonFatal

sealed trait PhaseRes[Id, T] extends Product with Serializable {
  import PhaseRes._

  def foreach(f: T => Unit): PhaseRes[Id, Unit] = map(f)

  def map[U](f: T => U): PhaseRes[Id, U] =
    this match {
      case Ok(value)       => Ok(f(value))
      case Ignore()        => Ignore()
      case Failure(errors) => Failure(errors)
    }

  def flatMap[U](f: T => PhaseRes[Id, U]): PhaseRes[Id, U] =
    this match {
      case Ok(value)       => f(value)
      case Ignore()        => Ignore()
      case Failure(errors) => Failure(errors)
    }
}

object PhaseRes {
  final case class Ok[Id, T](value: T) extends PhaseRes[Id, T]
  final case class Ignore[Id, T]() extends PhaseRes[Id, T]
  final case class Failure[Id, T](errors: Map[Id, Either[Throwable, String]]) extends PhaseRes[Id, T]

  def fromEither[Id, L, R](id: Id, e: Either[String, R]): PhaseRes[Id, R] =
    e match {
      case Right(value) => Ok(value)
      case Left(error)  => Failure(Map(id -> Right(error)))
    }

  def fromOption[Id, T](id: Id, e: Option[T], onEmpty: => Either[Throwable, String]): PhaseRes[Id, T] =
    e match {
      case Some(value) => Ok(value)
      case None        => Failure(Map(id -> onEmpty))
    }

  def sequenceSet[Id, T](rs: Set[PhaseRes[Id, T]]): PhaseRes[Id, Set[T]] =
    rs.foldLeft[PhaseRes[Id, Set[T]]](Ok(Set.empty)) {
      case (other, Ignore())                 => other
      case (Ok(ts), Ok(t))                   => Ok(ts + t)
      case (Ok(_), Failure(errors))          => Failure(errors)
      case (Failure(errors), Failure(error)) => Failure(errors ++ error)
      case (error @ Failure(_), Ok(_))       => error
      case (Ignore(), Ok(t))                 => Ok(Set(t))
      case (Ignore(), Failure(error))        => Failure(error)
    }

  def sequenceMap[Id: Ordering, T](rs: SortedMap[Id, PhaseRes[Id, T]]): PhaseRes[Id, SortedMap[Id, T]] =
    rs.foldLeft[PhaseRes[Id, SortedMap[Id, T]]](Ok(TreeMap.empty[Id, T])) {
      case (other, (_, Ignore()))                    => other
      case (Ok(map), (id, Ok(value)))                => Ok(map + ((id, value)))
      case (Ok(_), (_, Failure(errors)))             => Failure(errors)
      case (Failure(errors1), (_, Failure(errors2))) => Failure(errors1 ++ errors2)
      case (error @ Failure(_), _)                   => error
      case (Ignore(), (id, Ok(value)))               => Ok(TreeMap((id, value)))
      case (Ignore(), (_, Failure(errors)))          => Failure(errors)
    }

  def attempt[Id, T](id: Id, logger: Logger[Unit], t: => PhaseRes[Id, T]): PhaseRes[Id, T] =
    try t
    catch {
      case x: InterruptedException => throw x
      case x: ClosedByInterruptException => throw x
      case x: FileLockInterruptionException => throw x
      case x: ExecutionException if x.getCause != null =>
        val th = x.getCause
        logger.error(s"Caught exception: ${th.getMessage}", th)
        Failure[Id, T](Map(id -> Left(th)))
      case th: LoggedException =>
        Failure[Id, T](Map(id -> Left(th)))
      case NonFatal(th) =>
        logger.error(s"Caught exception: ${th.getMessage}", th)
        Failure[Id, T](Map(id -> Left(th)))
      case th: StackOverflowError =>
        logger.error("StackOverflowError", th)
        Failure[Id, T](Map(id -> Left(th)))
    }
} 
Example 3
Source File: javaz.scala    From interop-java   with Apache License 2.0 5 votes vote down vote up
package zio.interop

import _root_.java.nio.channels.CompletionHandler
import _root_.java.util.concurrent.{ CompletableFuture, CompletionException, CompletionStage, Future }

import zio.Fiber.Status
import zio._
import zio.blocking.{ blocking, Blocking }

import scala.concurrent.ExecutionException

object javaz {
  def withCompletionHandler[T](op: CompletionHandler[T, Any] => Unit): Task[T] =
    Task.effectSuspendTotalWith { p =>
      Task.effectAsync { k =>
        val handler = new CompletionHandler[T, Any] {
          def completed(result: T, u: Any): Unit = k(Task.succeed(result))

          def failed(t: Throwable, u: Any): Unit = t match {
            case e if !p.fatal(e) => k(Task.fail(e))
            case _                => k(Task.die(t))
          }
        }

        try {
          op(handler)
        } catch {
          case e if !p.fatal(e) => k(Task.fail(e))
        }
      }
    }

  private def catchFromGet(isFatal: Throwable => Boolean): PartialFunction[Throwable, Task[Nothing]] = {
    case e: CompletionException =>
      Task.fail(e.getCause)
    case e: ExecutionException =>
      Task.fail(e.getCause)
    case _: InterruptedException =>
      Task.interrupt
    case e if !isFatal(e) =>
      Task.fail(e)
  }

  private def unwrapDone[A](isFatal: Throwable => Boolean)(f: Future[A]): Task[A] =
    try {
      Task.succeed(f.get())
    } catch catchFromGet(isFatal)

  def fromCompletionStage[A](csUio: UIO[CompletionStage[A]]): Task[A] =
    csUio.flatMap { cs =>
      Task.effectSuspendTotalWith { p =>
        val cf = cs.toCompletableFuture
        if (cf.isDone) {
          unwrapDone(p.fatal)(cf)
        } else {
          Task.effectAsync { cb =>
            val _ = cs.handle[Unit] { (v: A, t: Throwable) =>
              val io = Option(t).fold[Task[A]](Task.succeed(v)) { t =>
                catchFromGet(p.fatal).lift(t).getOrElse(Task.die(t))
              }
              cb(io)
            }
          }
        }
      }
    }

  
  object CompletableFuture_ {
    def failedFuture[A](e: Throwable): CompletableFuture[A] = {
      val f = new CompletableFuture[A]
      f.completeExceptionally(e)
      f
    }
  }

  implicit class TaskCompletableFutureOps[A](private val io: Task[A]) extends AnyVal {
    def toCompletableFuture: UIO[CompletableFuture[A]] =
      io.fold(CompletableFuture_.failedFuture, CompletableFuture.completedFuture[A])
  }

  implicit class IOCompletableFutureOps[E, A](private val io: IO[E, A]) extends AnyVal {
    def toCompletableFutureWith(f: E => Throwable): UIO[CompletableFuture[A]] =
      io.mapError(f).toCompletableFuture
  }
} 
Example 4
Source File: javaz.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.interop

import scala.concurrent.ExecutionException

import _root_.java.nio.channels.CompletionHandler
import _root_.java.util.concurrent.{ CompletableFuture, CompletionException, CompletionStage, Future }

import zio._
import zio.blocking.{ blocking, Blocking }

private[zio] object javaz {
  def effectAsyncWithCompletionHandler[T](op: CompletionHandler[T, Any] => Any): Task[T] =
    Task.effectSuspendTotalWith[T] { (p, _) =>
      Task.effectAsync { k =>
        val handler = new CompletionHandler[T, Any] {
          def completed(result: T, u: Any): Unit = k(Task.succeedNow(result))

          def failed(t: Throwable, u: Any): Unit = t match {
            case e if !p.fatal(e) => k(Task.fail(e))
            case _                => k(Task.die(t))
          }
        }

        try {
          op(handler)
        } catch {
          case e if !p.fatal(e) => k(Task.fail(e))
        }
      }
    }

  private def catchFromGet(isFatal: Throwable => Boolean): PartialFunction[Throwable, Task[Nothing]] = {
    case e: CompletionException =>
      Task.fail(e.getCause)
    case e: ExecutionException =>
      Task.fail(e.getCause)
    case _: InterruptedException =>
      Task.interrupt
    case e if !isFatal(e) =>
      Task.fail(e)
  }

  def unwrapDone[A](isFatal: Throwable => Boolean)(f: Future[A]): Task[A] =
    try {
      Task.succeedNow(f.get())
    } catch catchFromGet(isFatal)

  def fromCompletionStage[A](thunk: => CompletionStage[A]): Task[A] =
    Task.effect(thunk).flatMap { cs =>
      Task.effectSuspendTotalWith { (p, _) =>
        val cf = cs.toCompletableFuture
        if (cf.isDone) {
          unwrapDone(p.fatal)(cf)
        } else {
          Task.effectAsync { cb =>
            cs.handle[Unit] { (v: A, t: Throwable) =>
              val io = Option(t).fold[Task[A]](Task.succeed(v)) { t =>
                catchFromGet(p.fatal).lift(t).getOrElse(Task.die(t))
              }
              cb(io)
            }
          }
        }
      }
    }

  
  object CompletableFuture_ {
    def failedFuture[A](e: Throwable): CompletableFuture[A] = {
      val f = new CompletableFuture[A]
      f.completeExceptionally(e)
      f
    }
  }
} 
Example 5
Source File: GrpcExceptionHandler.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.javadsl

import java.util.concurrent.CompletionException

import akka.actor.ActorSystem
import akka.actor.ClassicActorSystemProvider
import akka.annotation.ApiMayChange
import akka.annotation.InternalApi
import akka.grpc.{ GrpcServiceException, Trailers }
import akka.grpc.GrpcProtocol.GrpcProtocolWriter
import akka.grpc.internal.{ GrpcResponseHelpers, MissingParameterException }
import akka.http.javadsl.model.HttpResponse
import akka.japi.{ Function => jFunction }
import io.grpc.Status

import scala.concurrent.ExecutionException

@ApiMayChange
object GrpcExceptionHandler {
  private val INTERNAL = Trailers(Status.INTERNAL)
  private val INVALID_ARGUMENT = Trailers(Status.INVALID_ARGUMENT)
  private val UNIMPLEMENTED = Trailers(Status.UNIMPLEMENTED)

  def defaultMapper: jFunction[ActorSystem, jFunction[Throwable, Trailers]] =
    new jFunction[ActorSystem, jFunction[Throwable, Trailers]] {
      override def apply(system: ActorSystem): jFunction[Throwable, Trailers] =
        default(system)
    }

  
  @InternalApi
  private def default(system: ActorSystem): jFunction[Throwable, Trailers] =
    new jFunction[Throwable, Trailers] {
      override def apply(param: Throwable): Trailers =
        param match {
          case e: ExecutionException =>
            if (e.getCause == null) INTERNAL
            else default(system)(e.getCause)
          case e: CompletionException =>
            if (e.getCause == null) INTERNAL
            else default(system)(e.getCause)
          case grpcException: GrpcServiceException => Trailers(grpcException.status, grpcException.metadata)
          case _: MissingParameterException        => INVALID_ARGUMENT
          case _: NotImplementedError              => UNIMPLEMENTED
          case _: UnsupportedOperationException    => UNIMPLEMENTED
          case other =>
            system.log.error(other, "Unhandled error: [" + other.getMessage + "]")
            INTERNAL
        }
    }

  def standard(t: Throwable, writer: GrpcProtocolWriter, system: ClassicActorSystemProvider): HttpResponse =
    standard(t, default, writer, system)

  def standard(
      t: Throwable,
      mapper: jFunction[ActorSystem, jFunction[Throwable, Trailers]],
      writer: GrpcProtocolWriter,
      system: ClassicActorSystemProvider): HttpResponse =
    GrpcResponseHelpers.status(mapper(system.classicSystem)(t))(writer)
} 
Example 6
Source File: GrpcExceptionHandler.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.scaladsl

import akka.actor.ActorSystem
import akka.actor.ClassicActorSystemProvider
import akka.annotation.{ ApiMayChange, InternalStableApi }
import akka.grpc.{ GrpcServiceException, Trailers }
import akka.grpc.GrpcProtocol.GrpcProtocolWriter
import akka.grpc.internal.{ GrpcResponseHelpers, MissingParameterException }
import akka.http.scaladsl.model.HttpResponse
import io.grpc.Status

import scala.concurrent.{ ExecutionException, Future }

@ApiMayChange
object GrpcExceptionHandler {
  private val INTERNAL = Trailers(Status.INTERNAL)
  private val INVALID_ARGUMENT = Trailers(Status.INVALID_ARGUMENT)
  private val UNIMPLEMENTED = Trailers(Status.UNIMPLEMENTED)

  def defaultMapper(system: ActorSystem): PartialFunction[Throwable, Trailers] = {
    case e: ExecutionException =>
      if (e.getCause == null) INTERNAL
      else defaultMapper(system)(e.getCause)
    case grpcException: GrpcServiceException => Trailers(grpcException.status, grpcException.metadata)
    case _: NotImplementedError              => UNIMPLEMENTED
    case _: UnsupportedOperationException    => UNIMPLEMENTED
    case _: MissingParameterException        => INVALID_ARGUMENT
    case other =>
      system.log.error(other, s"Unhandled error: [${other.getMessage}].")
      INTERNAL
  }

  @InternalStableApi
  def default(
      implicit system: ClassicActorSystemProvider,
      writer: GrpcProtocolWriter): PartialFunction[Throwable, Future[HttpResponse]] =
    from(defaultMapper(system.classicSystem))

  @InternalStableApi
  def from(mapper: PartialFunction[Throwable, Trailers])(
      implicit system: ClassicActorSystemProvider,
      writer: GrpcProtocolWriter): PartialFunction[Throwable, Future[HttpResponse]] =
    mapper.orElse(defaultMapper(system.classicSystem)).andThen(s => Future.successful(GrpcResponseHelpers.status(s)))

} 
Example 7
Source File: GrpcExceptionHandlerSpec.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.scaladsl

import akka.actor.ActorSystem
import akka.grpc.GrpcServiceException
import akka.grpc.internal.{ GrpcProtocolNative, GrpcResponseHelpers, Identity }
import akka.grpc.scaladsl.GrpcExceptionHandler.defaultMapper
import akka.http.scaladsl.model.HttpEntity._
import akka.http.scaladsl.model.HttpResponse
import akka.stream.ActorMaterializer
import io.grpc.Status
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.wordspec.AnyWordSpec

import scala.concurrent.{ ExecutionException, Future }

class GrpcExceptionHandlerSpec extends AnyWordSpec with Matchers with ScalaFutures with BeforeAndAfterAll {
  implicit val system = ActorSystem("Test")
  implicit val materializer = ActorMaterializer()
  implicit override val patienceConfig =
    PatienceConfig(timeout = scaled(Span(2, Seconds)), interval = scaled(Span(5, Millis)))
  implicit val writer = GrpcProtocolNative.newWriter(Identity)

  val expected: Function[Throwable, Status] = {
    case e: ExecutionException =>
      if (e.getCause == null) Status.INTERNAL
      else expected(e.getCause)
    case grpcException: GrpcServiceException => grpcException.status
    case _: NotImplementedError              => Status.UNIMPLEMENTED
    case _: UnsupportedOperationException    => Status.UNIMPLEMENTED
    case _                                   => Status.INTERNAL
  }

  val otherTypes: Seq[Throwable] = Seq(
    new GrpcServiceException(status = Status.DEADLINE_EXCEEDED),
    new NotImplementedError,
    new UnsupportedOperationException,
    new NullPointerException,
    new RuntimeException)

  val executionExceptions: Seq[Throwable] =
    otherTypes.map(new ExecutionException(_)) :+ new ExecutionException("doh", null)

  "defaultMapper" should {
    (otherTypes ++ executionExceptions).foreach { e =>
      val exp = expected(e)
      s"Map $e to $exp" in {
        defaultMapper(system)(e).status shouldBe exp
      }
    }
  }

  "default(defaultMapper)" should {
    (otherTypes ++ executionExceptions).foreach { e =>
      s"Correctly map $e" in {
        val exp = GrpcResponseHelpers.status(defaultMapper(system)(e))
        val expChunks = getChunks(exp)
        val act = GrpcExceptionHandler.from(defaultMapper(system))(system, writer)(e).futureValue
        val actChunks = getChunks(act)
        // Following is because aren't equal
        act.status shouldBe exp.status
        actChunks.toString shouldEqual expChunks.toString
      }
    }
  }

  def getChunks(resp: HttpResponse): Seq[ChunkStreamPart] =
    (resp.entity match {
      case Chunked(_, chunks) =>
        chunks.runFold(Seq.empty[ChunkStreamPart]) { case (seq, chunk) => seq :+ chunk }
      case _ => Future.successful(Seq.empty[ChunkStreamPart])
    }).futureValue

  override def afterAll(): Unit = {
    super.afterAll()
    system.terminate()
  }
} 
Example 8
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 9
Source File: TimeLimitedRoute.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.api.http

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.{Directive1, ExceptionHandler, Route}
import com.google.common.util.concurrent.{ExecutionError, UncheckedExecutionException}
import com.wavesplatform.utils.Schedulers
import monix.execution.Scheduler

import scala.concurrent.ExecutionException

trait TimeLimitedRoute { self: ApiRoute =>
  def limitedScheduler: Scheduler

  def executeLimited[T](f: => T): Directive1[T] = {
    val handler = ExceptionHandler {
      case _: InterruptedException | _: ExecutionException | _: ExecutionError | _: UncheckedExecutionException =>
        complete(ApiError.CustomValidationError("The request took too long to complete"))
    }
    handleExceptions(handler) & onSuccess(Schedulers.executeCatchingInterruptedException(limitedScheduler)(f))
  }

  def completeLimited(f: => ToResponseMarshallable): Route =
    executeLimited(f)(complete(_))
}