com.github.ghik.silencer.silent Scala Examples

The following examples show how to use com.github.ghik.silencer.silent. 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: GrpcProtocolNative.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.internal

import akka.grpc.GrpcProtocol._
import akka.http.scaladsl.model.HttpEntity.{ Chunk, ChunkStreamPart, LastChunk }
import akka.util.ByteString
import com.github.ghik.silencer.silent


object GrpcProtocolNative extends AbstractGrpcProtocol("grpc") {

  override protected def writer(codec: Codec) =
    AbstractGrpcProtocol.writer(this, codec, encodeFrame(codec, _))

  override protected def reader(codec: Codec): GrpcProtocolReader =
    AbstractGrpcProtocol.reader(codec, decodeFrame)

  @inline
  private def decodeFrame(@silent("never used") frameType: Int, data: ByteString) = DataFrame(data)

  @inline
  private def encodeFrame(codec: Codec, frame: Frame): ChunkStreamPart = {
    val compressedFlag = AbstractGrpcProtocol.fieldType(codec)
    frame match {
      case DataFrame(data)       => Chunk(AbstractGrpcProtocol.encodeFrameData(compressedFlag, codec.compress(data)))
      case TrailerFrame(headers) => LastChunk(trailer = headers)
    }
  }

} 
Example 2
Source File: Project.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package models

import com.github.ghik.silencer.silent
import io.swagger.annotations.ApiModelProperty


case class Variable(name: String, value: String)

@silent("Interpolated")
@silent("missing interpolator")
case class Project(
                    @ApiModelProperty(value = "id of the project", example = "theGardener", required = true) id: String,
                    @ApiModelProperty(value = "name of the project", example = "theGardener", required = true) name: String,
                    @ApiModelProperty(value = "location of the project", example = "https://github.com/KelkooGroup/theGardener", required = true) repositoryUrl: String,
                    @ApiModelProperty(value = "source URL template", example = "https://github.com/KelkooGroup/theGardener/blob/${branch}/${path}", required = false) sourceUrlTemplate: Option[String],
                    @ApiModelProperty(value = "stableBranch of the project", example = "master", required = true) stableBranch: String,
                    @ApiModelProperty(value = "branches that will be displayed", example = "qa|master|feature.*|bugfix.*") displayedBranches: Option[String] = None,
                    @ApiModelProperty(value = "path that lead to the feature files", example = "test/features") featuresRootPath: Option[String],
                    @ApiModelProperty(value = "path that lead to the documentation files", example = "documentation") documentationRootPath: Option[String] = None,
                    @ApiModelProperty(value = "variables defined for this project", example = "[{\"name\":\"${swagger.url}\",\"value\":\"http://dc1-pmbo-corp-srv-pp.corp.dc1.kelkoo.net:9001/docs\"}]") variables: Option[Seq[Variable]] = None,
                    @ApiModelProperty(value = "Hierarchy matching the project") hierarchy: Option[Seq[HierarchyNode]] = None,
                    @ApiModelProperty(value = "branches of the project") branches: Option[Seq[Branch]] = None)

case class ProjectBranch(project:Project,branch:Branch) 
Example 3
Source File: DefaultMetricsOps.scala    From datadog4s   with MIT License 5 votes vote down vote up
package com.avast.datadog4s.extension.http4s.impl

import java.time.Duration

import cats.effect.Sync
import cats.effect.concurrent.Ref
import cats.syntax.flatMap._
import com.avast.datadog4s.api.MetricFactory
import com.avast.datadog4s.api.tag.Tagger
import com.avast.datadog4s.extension.http4s.DatadogMetricsOps.ClassifierTags
import com.avast.datadog4s.extension.http4s._
import com.github.ghik.silencer.silent
import org.http4s.metrics.{ MetricsOps, TerminationType }
import org.http4s.{ Method, Status }

private[http4s] class DefaultMetricsOps[F[_]](
  metricFactory: MetricFactory[F],
  classifierTags: ClassifierTags,
  activeConnectionsRef: Ref[F, ActiveConnections]
)(implicit
  F: Sync[F]
) extends MetricsOps[F] {
  private[this] val methodTagger          = Tagger.make[Method]("method")
  @deprecated("please use terminationTypeTagger - this will be removed in next release 0.8.0", "0.6.3")
  private[this] val typeTagger            = Tagger.make[TerminationType]("type")
  private[this] val terminationTypeTagger = Tagger.make[TerminationType]("termination_type")
  private[this] val statusCodeTagger      = Tagger.make[Status]("status_code")
  private[this] val statusBucketTagger    = Tagger.make[String]("status_bucket")
  private[this] val activeRequests        = metricFactory.gauge.long("active_requests")

  override def increaseActiveRequests(classifier: Option[String]): F[Unit] =
    modifyActiveRequests(classifier, 0, 1)

  override def decreaseActiveRequests(classifier: Option[String]): F[Unit] =
    // if we try to decrement non existing classifier, make sure it's zero
    modifyActiveRequests(classifier, 1, -1)

  private def modifyActiveRequests(classifier: Option[String], default: Int, delta: Int): F[Unit] =
    activeConnectionsRef.modify { activeConnections =>
      val current               = activeConnections.getOrElse(classifier, default)
      val next                  = current + delta
      val nextActiveConnections = activeConnections.updated(classifier, next)
      val action                = activeRequests.set(
        next.toLong,
        classifier.toList.flatMap(classifierTags): _*
      )
      (nextActiveConnections, action)
    }.flatten

  private[this] val headersTime = metricFactory.timer("headers_time")

  override def recordHeadersTime(method: Method, elapsed: Long, classifier: Option[String]): F[Unit] =
    headersTime
      .record(
        Duration.ofNanos(elapsed),
        methodTagger.tag(method) :: classifier.toList.flatMap(classifierTags): _*
      )

  private[this] val requestCount   = metricFactory.count("requests_count")
  private[this] val requestLatency = metricFactory.timer("requests_latency")
  override def recordTotalTime(method: Method, status: Status, elapsed: Long, classifier: Option[String]): F[Unit] = {
    val tags = methodTagger.tag(method) ::
      statusBucketTagger.tag(s"${status.code / 100}xx") ::
      statusCodeTagger.tag(status) :: classifier.toList.flatMap(classifierTags)
    requestCount.inc(tags: _*) >> requestLatency.record(Duration.ofNanos(elapsed), tags: _*)
  }

  private[this] val abnormalCount   = metricFactory.count("abnormal_count")
  private[this] val abnormalLatency = metricFactory.timer("abnormal_latency")
  override def recordAbnormalTermination(
    elapsed: Long,
    terminationType: TerminationType,
    classifier: Option[String]
  ): F[Unit] = {
    val terminationTpe = terminationTypeTagger.tag(terminationType)
    @silent("deprecated")
    val tpe            = typeTagger.tag(terminationType)
    val tags           = tpe :: terminationTpe :: classifier.toList.flatMap(classifierTags)
    abnormalCount.inc(tags: _*) >> abnormalLatency.record(Duration.ofNanos(elapsed), tags: _*)
  }
} 
Example 4
Source File: TRandom.scala    From zio-keeper   with Apache License 2.0 5 votes vote down vote up
package zio.keeper.hyparview

import com.github.ghik.silencer.silent
import zio.random.Random
import zio.stm.{ STM, TRef, ZSTM }
import zio.{ URIO, ZLayer, random }
import scala.{ Stream => ScStream }

object TRandom {

  
    def selectN[A](values: List[A], n: Int): STM[Nothing, List[A]]
  }

  def selectOne[A](values: List[A]): ZSTM[TRandom, Nothing, Option[A]] =
    ZSTM.accessM(_.get.selectOne(values))

  def selectN[A](values: List[A], n: Int): ZSTM[TRandom, Nothing, List[A]] =
    ZSTM.accessM(_.get.selectN(values, n))

  def live: ZLayer[Random, Nothing, TRandom] = {
    @silent("deprecated")
    val makePickRandom: URIO[Random, Int => STM[Nothing, Int]] =
      for {
        seed    <- random.nextInt
        sRandom = new scala.util.Random(seed)
        ref     <- TRef.make(ScStream.continually((i: Int) => sRandom.nextInt(i))).commit
      } yield (i: Int) => ref.modify(s => (s.head(i), s.tail))

    ZLayer.fromEffect {
      makePickRandom.map { pickRandom =>
        new Service {
          def selectOne[A](values: List[A]): STM[Nothing, Option[A]] =
            if (values.isEmpty) STM.succeed(None)
            else {
              for {
                index    <- pickRandom(values.size)
                selected = values(index)
              } yield Some(selected)
            }

          def selectN[A](values: List[A], n: Int): STM[Nothing, List[A]] = {
            def go(remaining: Vector[A], toPick: Int, acc: List[A]): STM[Nothing, List[A]] =
              (remaining, toPick) match {
                case (Vector(), _) | (_, 0) => STM.succeed(acc)
                case _ =>
                  pickRandom(remaining.size).flatMap { index =>
                    val x  = remaining(index)
                    val xs = remaining.patch(index, Nil, 1)
                    go(xs, toPick - 1, x :: acc)
                  }
              }
            go(values.toVector, Math.max(0, n), Nil)
          }
        }
      }
    }
  }
} 
Example 5
Source File: Same.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.optics

import com.github.ghik.silencer.silent


trait PSame[-S, +T, +A, -B] extends PEquivalent[S, T, A, B] {
  self =>

  def rsubst[R[-_, +_]](r: R[A, B]): R[S, T]

  def upcast(b: B): T                     = rsubst[λ[(`-x`, `+y`) => y]](b)
  def extract(a: S): A                    = inverse.rsubst[λ[(`-x`, `+y`) => y]](a)
  override def inverse: PSame[B, A, T, S] = PSame.invert(this)
}

object Same extends MonoOpticCompanion(PSame) {
  def id[A]: Same[A, A] = PSame.id[A, A]
}

object PSame extends OpticCompanion[PSame] with OpticProduct[PSame] {
  type Context             = OpticContext
  override type Mono[A, B] = Same[A, B]

  @silent("never used") private type Inv[-s, +t, +a, -b] = PSame[b, a, t, s]

  private def refl[A, B]: PSame[A, B, A, B] = new PSame[A, B, A, B] {
    def rsubst[K[_, _]](k: K[A, B]): K[A, B] = k
  }

  private val anyId               = refl[Any, Any]
  def id[A, B]: PSame[A, B, A, B] = anyId.asInstanceOf[PSame[A, B, A, B]]

  def compose[S, T, A, B, U, V](f: PSame[A, B, U, V], g: PSame[S, T, A, B]): PSame[S, T, U, V] =
    g.rsubst[PSame[-*, +*, U, V]](f)

  override def product[S1, S2, T1, T2, A1, A2, B1, B2](
      f: PSame[S1, T1, A1, B1],
      g: PSame[S2, T2, A2, B2]
  ): PSame[(S1, S2), (T1, T2), (A1, A2), (B1, B2)] = anyId.asInstanceOf[PSame[(S1, S2), (T1, T2), (A1, A2), (B1, B2)]]

  override def toGeneric[S, T, A, B](o: PSame[S, T, A, B]): Optic[OpticContext, S, T, A, B] =
    new Optic[OpticContext, S, T, A, B] {
      def apply(c: OpticContext)(p: c.P[A, c.F[B]]): c.P[S, c.F[T]] =
        o.rsubst[λ[(`-x`, `+y`) => c.P[x, c.F[y]]]](p)
    }

  override def fromGeneric[S, T, A, B](o: Optic[OpticContext, S, T, A, B]): PSame[S, T, A, B] =
    new PSame[S, T, A, B] {
      def rsubst[R[-_, +_]](r: R[A, B]): R[S, T] =
        o(new OpticContext {
          type F[+x]     = x
          type P[-x, +y] = R[x, y]
        })(r)
    }

  private def invert[S, T, A, B](self: PSame[S, T, A, B]): PSame[B, A, T, S] =
    self.rsubst[Inv[-*, +*, A, B]](PSame.id)

  implicit final class SameOps[A, B](private val s: PSame[A, A, B, B]) extends AnyVal {
    def subst[F[+_]](fa: F[A]): F[B] = s.inverse.rsubst[λ[(`-s`, `+t`) => F[t]]](fa)
  }
} 
Example 6
Source File: DoobieInstancesSuite.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.doobie

import cats.Applicative
import cats.data.ReaderT
import cats.effect.{IO, SyncIO}
import com.github.ghik.silencer.silent
import doobie.ConnectionIO
import monix.eval.{Coeval, Task}
import monix.execution.Scheduler
import tofu.doobie.instances.implicits._
import tofu.env.Env
import tofu.lift.Lift
import tofu.zioInstances.implicits._
import zio.interop.catz._

object DoobieInstancesSuite {

  def summonImplicitsViaLiftToIO[F[_]: Applicative, R](implicit L: Lift[F, IO]): Unit = {
    Lift[F, ConnectionIO]
    Lift[F, ConnectionRIO[R, *]]
    Lift[ReaderT[F, R, *], ConnectionRIO[R, *]]
    ()
  }

  def summonCatsEffectImplicits[R](): Unit = {
    Lift[SyncIO, ConnectionIO]
    Lift[SyncIO, ConnectionRIO[R, *]]
    Lift[ReaderT[SyncIO, R, *], ConnectionRIO[R, *]]

    Lift[IO, ConnectionIO]
    Lift[IO, ConnectionRIO[R, *]]
    Lift[ReaderT[IO, R, *], ConnectionRIO[R, *]]

    ()
  }

  def summonMonixImplicitsViaScheduler[R](implicit sc: Scheduler): Unit = {
    Lift[Coeval, ConnectionIO]
    Lift[Coeval, ConnectionRIO[R, *]]
    Lift[ReaderT[Coeval, R, *], ConnectionRIO[R, *]]

    Lift[Task, ConnectionIO]
    Lift[Task, ConnectionRIO[R, *]]
    Lift[ReaderT[Task, R, *], ConnectionRIO[R, *]]

    Lift[Env[R, *], ConnectionRIO[R, *]]

    ()
  }

  def summonMonixImplicitsUnambiguously[R](implicit @silent sc: Scheduler, L: Lift[Task, IO]): Unit = {
    Lift[Task, ConnectionIO]
    Lift[Task, ConnectionRIO[R, *]]
    Lift[ReaderT[Task, R, *], ConnectionRIO[R, *]]
    ()
  }

  def summonZioImplicits[R](): zio.Task[Unit] =
    zio.Task.concurrentEffect.map { implicit CE =>
      Lift[zio.Task, ConnectionIO]
      Lift[zio.Task, ConnectionRIO[R, *]]
      Lift[zio.RIO[R, *], ConnectionRIO[R, *]]
      ()
    }

  def summonLiftConnectionIO[R](): Unit = {
    LiftConnectionIO[ConnectionIO]
    LiftConnectionIO[ConnectionRIO[R, *]]
    ()
  }

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

import scala.collection.JavaConverters._
import scala.collection.immutable
import akka.grpc.gen.{ BuildInfo, CodeGenerator, Logger }
import com.google.protobuf.Descriptors._
import com.google.protobuf.compiler.PluginProtos.{ CodeGeneratorRequest, CodeGeneratorResponse }
import scalapb.compiler.GeneratorParams
import protocbridge.Artifact

import com.github.ghik.silencer.silent

abstract class ScalaCodeGenerator extends CodeGenerator {
  // Override this to add generated files per service
  def perServiceContent: Set[(Logger, Service) => immutable.Seq[CodeGeneratorResponse.File]] = Set.empty

  // Override these to add service-independent generated files
  def staticContent(@silent("never used") logger: Logger): Set[CodeGeneratorResponse.File] = Set.empty
  def staticContent(
      @silent("never used") logger: Logger,
      @silent("never used") allServices: Seq[Service]): Set[CodeGeneratorResponse.File] = Set.empty

  override def suggestedDependencies =
    (scalaBinaryVersion: CodeGenerator.ScalaBinaryVersion) =>
      Seq(
        Artifact(
          BuildInfo.organization,
          BuildInfo.runtimeArtifactName + "_" + scalaBinaryVersion.prefix,
          BuildInfo.version))

  // generate services code here, the data types we want to leave to scalapb
  override def run(request: CodeGeneratorRequest, logger: Logger): CodeGeneratorResponse = {
    val b = CodeGeneratorResponse.newBuilder
    val fileDescByName: Map[String, FileDescriptor] =
      request.getProtoFileList.asScala.foldLeft[Map[String, FileDescriptor]](Map.empty) {
        case (acc, fp) =>
          val deps = fp.getDependencyList.asScala.map(acc).toArray
          acc + (fp.getName -> FileDescriptor.buildFrom(fp, deps))
      }

    // Currently per-invocation options, intended to become per-service options eventually
    // https://github.com/akka/akka-grpc/issues/451
    val params = request.getParameter.toLowerCase
    // flags listed in akkaGrpcCodeGeneratorSettings's description
    val serverPowerApi = params.contains("server_power_apis") && !params.contains("server_power_apis=false")
    val usePlayActions = params.contains("use_play_actions") && !params.contains("use_play_actions=false")

    val services =
      (for {
        file <- request.getFileToGenerateList.asScala
        fileDesc = fileDescByName(file)
        serviceDesc <- fileDesc.getServices.asScala
      } yield Service(
        parseParameters(request.getParameter),
        fileDesc,
        serviceDesc,
        serverPowerApi,
        usePlayActions)).toSeq

    for {
      service <- services
      generator <- perServiceContent
      generated <- generator(logger, service)
    } {
      b.addFile(generated)
    }

    staticContent(logger).map(b.addFile)
    staticContent(logger, services).map(b.addFile)

    b.build()
  }

  // flags listed in akkaGrpcCodeGeneratorSettings's description
  private def parseParameters(params: String): GeneratorParams =
    params.split(",").map(_.trim).filter(_.nonEmpty).foldLeft[GeneratorParams](GeneratorParams()) {
      case (p, "java_conversions")            => p.copy(javaConversions = true)
      case (p, "flat_package")                => p.copy(flatPackage = true)
      case (p, "single_line_to_string")       => p.copy(singleLineToProtoString = true) // for backward-compatibility
      case (p, "single_line_to_proto_string") => p.copy(singleLineToProtoString = true)
      case (p, "ascii_format_to_string")      => p.copy(asciiFormatToString = true)
      case (p, "no_lenses")                   => p.copy(lenses = false)
      case (p, "retain_source_code_info")     => p.copy(retainSourceCodeInfo = true)
      case (x, _)                             => x
    }
} 
Example 8
Source File: ScalaMarshallersCodeGenerator.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.gen.scaladsl

import scala.collection.immutable
import akka.grpc.gen.{ BuildInfo, CodeGenerator, Logger }
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse
import protocbridge.Artifact
import templates.ScalaCommon.txt._

import com.github.ghik.silencer.silent


trait ScalaMarshallersCodeGenerator extends ScalaCodeGenerator {
  def name = "akka-grpc-scaladsl-server-marshallers"

  override def perServiceContent = Set(generateMarshalling)

  override def suggestedDependencies =
    (scalaBinaryVersion: CodeGenerator.ScalaBinaryVersion) =>
      Artifact("com.typesafe.akka", s"akka-http_${scalaBinaryVersion.prefix}", BuildInfo.akkaHttpVersion) +: super
        .suggestedDependencies(scalaBinaryVersion)

  def generateMarshalling(
      @silent("never used") logger: Logger,
      service: Service): immutable.Seq[CodeGeneratorResponse.File] = {
    val b = CodeGeneratorResponse.File.newBuilder()
    b.setContent(Marshallers(service).body)
    b.setName(s"${service.packageDir}/${service.name}Marshallers.scala")
    immutable.Seq(b.build)
  }
}

object ScalaMarshallersCodeGenerator extends ScalaMarshallersCodeGenerator 
Example 9
Source File: JavaCodeGenerator.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.gen.javadsl

import akka.grpc.gen.{ BuildInfo, CodeGenerator, Logger }
import com.google.protobuf.Descriptors._
import com.google.protobuf.compiler.PluginProtos.{ CodeGeneratorRequest, CodeGeneratorResponse }
import protocbridge.Artifact
import templates.JavaCommon.txt.ApiInterface

import scala.collection.JavaConverters._
import scala.collection.immutable

import com.github.ghik.silencer.silent

abstract class JavaCodeGenerator extends CodeGenerator {

  
  def staticContent(@silent("never used") logger: Logger): Set[CodeGeneratorResponse.File] =
    Set.empty
  def staticContent(
      @silent("never used") logger: Logger,
      @silent("never used") allServices: Seq[Service]): Set[CodeGeneratorResponse.File] =
    Set.empty

  override def run(request: CodeGeneratorRequest, logger: Logger): CodeGeneratorResponse = {
    val b = CodeGeneratorResponse.newBuilder

    // generate services code here, the data types we want to leave to scalapb

    val fileDescByName: Map[String, FileDescriptor] =
      request.getProtoFileList.asScala.foldLeft[Map[String, FileDescriptor]](Map.empty) {
        case (acc, fp) =>
          val deps = fp.getDependencyList.asScala.map(acc).toArray
          acc + (fp.getName -> FileDescriptor.buildFrom(fp, deps))
      }

    // Currently per-invocation options, intended to become per-service options eventually
    // https://github.com/akka/akka-grpc/issues/451
    val params = request.getParameter.toLowerCase
    val serverPowerApi = params.contains("server_power_apis") && !params.contains("server_power_apis=false")
    val usePlayActions = params.contains("use_play_actions") && !params.contains("use_play_actions=false")

    val services = (for {
      file <- request.getFileToGenerateList.asScala
      fileDesc = fileDescByName(file)
      serviceDesc <- fileDesc.getServices.asScala
    } yield Service(fileDesc, serviceDesc, serverPowerApi, usePlayActions)).toVector

    for {
      service <- services
      generator <- perServiceContent
      generated <- generator(logger, service)
    } {
      b.addFile(generated)
    }

    staticContent(logger).map(b.addFile)
    staticContent(logger, services).map(b.addFile)

    b.build()
  }

  def generateServiceInterface(service: Service): CodeGeneratorResponse.File = {
    val b = CodeGeneratorResponse.File.newBuilder()
    b.setContent(ApiInterface(service).body)
    b.setName(s"${service.packageDir}/${service.name}.java")
    b.build
  }

  override val suggestedDependencies = (scalaBinaryVersion: CodeGenerator.ScalaBinaryVersion) =>
    Seq(
      Artifact(
        BuildInfo.organization,
        BuildInfo.runtimeArtifactName + "_" + scalaBinaryVersion.prefix,
        BuildInfo.version))
} 
Example 10
Source File: PageController.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.io.File

import com.github.ghik.silencer.silent
import controllers.AssetAccessError.{AssetNotAllowed, AssetNotFound}
import controllers.dto._
import io.swagger.annotations._
import javax.inject.Inject
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc._
import repositories._
import services._

import scala.concurrent.ExecutionContext

@silent("Interpolated")
@silent("missing interpolator")
@Api(value = "PageController", produces = "application/json")
class PageController @Inject()(pageService: PageService)(implicit ec: ExecutionContext) extends InjectedController {

  @ApiOperation(value = "Get pages from path", response = classOf[PageDTO], responseContainer = "list")
  @ApiResponses(Array(new ApiResponse(code = 404, message = "Page not found")))
  def getPageFromPath(path: String): Action[AnyContent] = Action.async {
    pageService.computePageFromPath(path).map {
      case Some(pageDto) => Ok(Json.toJson(Seq(pageDto)))
      case None => NotFound(s"No Page $path")
    }
  }

}

sealed abstract class AssetAccessError(message: String) extends Throwable(message)


object AssetAccessError {

  case class AssetNotAllowed(message: String) extends AssetAccessError(message)

  case class AssetNotFound(message: String) extends AssetAccessError(message)

}

class PageAssetController @Inject()(config: Configuration, projectRepository: ProjectRepository)(implicit ec: ExecutionContext) extends InjectedController {

  val projectsRootDirectory = config.get[String]("projects.root.directory")

  def getImageFromPath(path: String): Action[AnyContent] = Action {
    val params = path.split(">")

    (for {
      projectId <- params.lift(0)
      branchName <- params.lift(1)
      relativePath <- params.lift(2)

      documentationRootPath <- projectRepository.findById(projectId).flatMap(_.documentationRootPath)
      assetFileAccess = accessToAsset(s"$projectsRootDirectory/$projectId/$branchName/$documentationRootPath", relativePath)
    } yield (relativePath, assetFileAccess)) match {

      case None => NotFound("Project not found or bad configuration")
      case Some((_, Left(AssetNotAllowed(message)))) => Forbidden(message)
      case Some((_, Left(AssetNotFound(message)))) => NotFound(message)
      case Some((_, Right(assetFile))) => Ok.sendFile(assetFile)
    }
  }

  def accessToAsset(documentationRootPath: String, assetRelativePath: String): Either[AssetAccessError, File] = {
    val assetFile = new File(s"$documentationRootPath/$assetRelativePath")
    val documentationCanonicalPath = new File(documentationRootPath).getCanonicalPath
    val assetCanonicalPath = assetFile.getCanonicalPath

    if (!assetCanonicalPath.contains(documentationCanonicalPath)) {
      Left(AssetNotAllowed(s"Asset $assetRelativePath not allowed"))
    } else if (!assetFile.exists()) {
      Left(AssetNotFound(s"Asset $assetRelativePath not found"))
    } else {
      Right(assetFile)
    }
  }

} 
Example 11
Source File: GrpcMarshalling.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.javadsl

import java.util.concurrent.{ CompletableFuture, CompletionStage }
import java.util.Optional

import akka.NotUsed
import akka.actor.ActorSystem
import akka.actor.ClassicActorSystemProvider
import akka.grpc._
import akka.grpc.internal.{ CancellationBarrierGraphStage, GrpcResponseHelpers, MissingParameterException }
import akka.grpc.GrpcProtocol.{ GrpcProtocolReader, GrpcProtocolWriter }
import akka.http.javadsl.model.{ HttpRequest, HttpResponse }
import akka.japi.Function
import akka.stream.Materializer
import akka.stream.javadsl.{ Sink, Source }
import akka.util.ByteString

import com.github.ghik.silencer.silent

object GrpcMarshalling {

  def negotiated[T](
      req: HttpRequest,
      f: (GrpcProtocolReader, GrpcProtocolWriter) => CompletionStage[T]): Optional[CompletionStage[T]] =
    GrpcProtocol
      .negotiate(req)
      .map {
        case (maybeReader, writer) =>
          maybeReader.map(reader => f(reader, writer)).fold[CompletionStage[T]](failure, identity)
      }
      .fold(Optional.empty[CompletionStage[T]])(Optional.of)

  def unmarshal[T](
      data: Source[ByteString, AnyRef],
      u: ProtobufSerializer[T],
      mat: Materializer,
      reader: GrpcProtocolReader): CompletionStage[T] =
    data.via(reader.dataFrameDecoder).map(u.deserialize).runWith(Sink.headOption[T], mat).thenCompose[T] { opt =>
      if (opt.isPresent) CompletableFuture.completedFuture(opt.get)
      else failure(new MissingParameterException())
    }

  def unmarshalStream[T](
      data: Source[ByteString, AnyRef],
      u: ProtobufSerializer[T],
      @silent("never used") mat: Materializer,
      reader: GrpcProtocolReader): CompletionStage[Source[T, NotUsed]] = {
    CompletableFuture.completedFuture[Source[T, NotUsed]](
      data
        .mapMaterializedValue(_ => NotUsed)
        .via(reader.dataFrameDecoder)
        .map(japiFunction(u.deserialize))
        // In gRPC we signal failure by returning an error code, so we
        // don't want the cancellation bubbled out
        .via(new CancellationBarrierGraphStage)
        .mapMaterializedValue(japiFunction(_ => NotUsed)))
  }

  def marshal[T](
      e: T,
      m: ProtobufSerializer[T],
      writer: GrpcProtocolWriter,
      system: ClassicActorSystemProvider,
      eHandler: Function[ActorSystem, Function[Throwable, Trailers]] = GrpcExceptionHandler.defaultMapper)
      : HttpResponse =
    marshalStream(Source.single(e), m, writer, system, eHandler)

  def marshalStream[T](
      e: Source[T, NotUsed],
      m: ProtobufSerializer[T],
      writer: GrpcProtocolWriter,
      system: ClassicActorSystemProvider,
      eHandler: Function[ActorSystem, Function[Throwable, Trailers]] = GrpcExceptionHandler.defaultMapper)
      : HttpResponse =
    GrpcResponseHelpers(e.asScala, scalaAnonymousPartialFunction(eHandler))(m, writer, system)

  private def failure[R](error: Throwable): CompletableFuture[R] = {
    val future: CompletableFuture[R] = new CompletableFuture()
    future.completeExceptionally(error)
    future
  }
} 
Example 12
Source File: Settings.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.config

import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider}
import akka.http.scaladsl.model.Uri
import ch.epfl.bluebrain.nexus.iam.types.Permission
import com.github.ghik.silencer.silent
import com.typesafe.config.Config
import pureconfig.generic.auto._
import pureconfig.ConvertHelpers._
import pureconfig._


@SuppressWarnings(Array("LooksLikeInterpolatedString"))
class Settings(config: Config) extends Extension {

  @silent // not recognized as used... but it is below
  private implicit val uriConverter: ConfigConvert[Uri] =
    ConfigConvert.viaString[Uri](catchReadError(Uri(_)), _.toString)

  @silent // not recognized as used... but it is below
  private implicit val permissionConverter: ConfigConvert[Permission] =
    ConfigConvert.viaString[Permission](optF(Permission(_)), _.toString)

  val appConfig: AppConfig =
    ConfigSource.fromConfig(config).at("app").loadOrThrow[AppConfig]
}

object Settings extends ExtensionId[Settings] with ExtensionIdProvider {

  override def lookup(): ExtensionId[_ <: Extension] = Settings

  override def createExtension(system: ExtendedActorSystem): Settings = apply(system.settings.config)

  def apply(config: Config): Settings = new Settings(config)
} 
Example 13
Source File: TokenRejection.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.auth

import com.github.ghik.silencer.silent
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}


  final case object InvalidAccessToken
      extends TokenRejection(
        "The token is invalid; possible causes are: incorrect signature, the token is expired or the 'nbf' value was not met."
      )

  @silent // rejectionConfig is not recognized as being used
  implicit val tokenRejectionEncoder: Encoder[TokenRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[TokenRejection]
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }
} 
Example 14
Source File: AclEvent.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.acls

import java.time.Instant

import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig
import ch.epfl.bluebrain.nexus.iam.config.Contexts._
import ch.epfl.bluebrain.nexus.iam.types.Identity
import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject
import ch.epfl.bluebrain.nexus.rdf.Iri.Path
import ch.epfl.bluebrain.nexus.rdf.implicits._
import com.github.ghik.silencer.silent
import io.circe.Encoder
import io.circe.generic.extras.Configuration


  final case class AclDeleted(
      path: Path,
      rev: Long,
      instant: Instant,
      subject: Subject
  ) extends AclEvent

  object JsonLd {
    import io.circe.generic.extras.semiauto._

    @silent // defined implicits are not recognized as being used
    implicit def aclEventEncoder(implicit httpConfig: HttpConfig): Encoder[AclEvent] = {
      implicit val config: Configuration = Configuration.default
        .withDiscriminator("@type")
        .copy(transformMemberNames = {
          case "rev"     => "_rev"
          case "instant" => "_instant"
          case "subject" => "_subject"
          case "path"    => "_path"
          case other     => other
        })
      implicit val arrayEncoder: Encoder[AccessControlList] = AccessControlList.aclArrayEncoder
      implicit val subjectEncoder: Encoder[Subject]         = Identity.subjectIdEncoder
      deriveConfiguredEncoder[AclEvent]
        .mapJson { json =>
          json
            .addContext(iamCtxUri)
            .addContext(resourceCtxUri)
        }
    }
  }
} 
Example 15
Source File: AclRejection.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.acls

import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound}
import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom
import ch.epfl.bluebrain.nexus.iam.config.Contexts.errorCtxUri
import ch.epfl.bluebrain.nexus.iam.types.{Permission, ResourceRejection}
import ch.epfl.bluebrain.nexus.rdf.Iri.Path
import ch.epfl.bluebrain.nexus.rdf.implicits._
import com.github.ghik.silencer.silent
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}

sealed abstract class AclRejection(val msg: String) extends ResourceRejection

object AclRejection {

  
  final case class UnknownPermissions(permissions: Set[Permission])
      extends AclRejection(
        s"Some of the permissions specified are not known: '${permissions.mkString("\"", ", ", "\"")}'"
      )

  @silent // rejectionConfig is not recognized as being used
  implicit val aclRejectionEncoder: Encoder[AclRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[AclRejection].mapJson(_ addContext errorCtxUri)
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }

  implicit val aclRejectionStatusFrom: StatusFrom[AclRejection] =
    StatusFrom {
      case _: NothingToBeUpdated                        => BadRequest
      case _: AclIsEmpty                                => BadRequest
      case _: AclCannotContainEmptyPermissionCollection => BadRequest
      case _: AclNotFound                               => NotFound
      case _: IncorrectRev                              => Conflict
      case _: UnknownPermissions                        => BadRequest
    }
} 
Example 16
Source File: PermissionsState.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.permissions

import java.time.Instant

import ch.epfl.bluebrain.nexus.iam.config.AppConfig.{HttpConfig, PermissionsConfig}
import ch.epfl.bluebrain.nexus.iam.permissions.PermissionsState.{Current, Initial}
import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Subject}
import ch.epfl.bluebrain.nexus.iam.types.{Permission, ResourceMetadata}
import com.github.ghik.silencer.silent


  final case class Current(
      rev: Long,
      permissions: Set[Permission],
      createdAt: Instant,
      createdBy: Subject,
      updatedAt: Instant,
      updatedBy: Subject
  ) extends PermissionsState {

    override def resource(implicit http: HttpConfig, @silent pc: PermissionsConfig): Resource =
      resourceMetadata.map(_ => permissions)

    override def resourceMetadata(implicit http: HttpConfig): ResourceMetadata =
      ResourceMetadata(id, rev, types, createdAt, createdBy, updatedAt, updatedBy)
  }
} 
Example 17
Source File: PermissionsEvent.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.permissions

import java.time.Instant

import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig
import ch.epfl.bluebrain.nexus.iam.config.Contexts._
import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject
import ch.epfl.bluebrain.nexus.iam.types.{Identity, Permission}
import ch.epfl.bluebrain.nexus.rdf.implicits._
import com.github.ghik.silencer.silent
import io.circe.Encoder
import io.circe.generic.extras.Configuration


  final case class PermissionsDeleted(
      rev: Long,
      instant: Instant,
      subject: Subject
  ) extends PermissionsEvent

  object JsonLd {
    import io.circe.generic.extras.semiauto._

    @silent // defined implicits are not recognized as being used
    implicit def permissionsEventEncoder(implicit http: HttpConfig): Encoder[Event] = {
      implicit val config: Configuration = Configuration.default
        .withDiscriminator("@type")
        .copy(transformMemberNames = {
          case "rev"     => "_rev"
          case "instant" => "_instant"
          case "subject" => "_subject"
          case other     => other
        })
      implicit val subjectEncoder: Encoder[Subject] = Identity.subjectIdEncoder
      deriveConfiguredEncoder[Event]
        .mapJson { json =>
          json
            .addContext(iamCtxUri)
            .addContext(resourceCtxUri)
        }
    }
  }
} 
Example 18
Source File: localValueSuppression.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

object localValueSuppression {
  def method(): Unit = {
    @silent
    val stuff = {
      123
      ()
    }
    val other = {
      123
      ()
    }
  }
} 
Example 19
Source File: FinatraServerTests.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.server.finatra

import cats.data.NonEmptyList
import cats.effect.{ContextShift, IO, Resource, Timer}
import com.github.ghik.silencer.silent
import com.twitter.finagle.http.Request
import com.twitter.finatra.http.filters.{AccessLoggingFilter, ExceptionMappingFilter}
import com.twitter.finatra.http.{Controller, EmbeddedHttpServer, HttpServer}
import com.twitter.finatra.http.routing.HttpRouter
import com.twitter.util.{Future, FuturePool}
import sttp.tapir.Endpoint
import sttp.tapir.server.{DecodeFailureHandler, ServerDefaults, ServerEndpoint}
import sttp.tapir.server.tests.ServerTests
import sttp.tapir.tests.{Port, PortCounter}

import scala.concurrent.ExecutionContext
import scala.reflect.ClassTag
import scala.concurrent.duration._

class FinatraServerTests extends ServerTests[Future, Nothing, FinatraRoute] {
  override def streamingSupport: Boolean = false

  private val futurePool = FuturePool.unboundedPool

  implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
  implicit val contextShift: ContextShift[IO] = IO.contextShift(ec)
  implicit val timer: Timer[IO] = IO.timer(ec)

  override def pureResult[T](t: T): Future[T] = Future.value(t)

  override def suspendResult[T](t: => T): Future[T] =
    futurePool {
      t
    }

  override def route[I, E, O](
      e: ServerEndpoint[I, E, O, Nothing, Future],
      decodeFailureHandler: Option[DecodeFailureHandler] = None
  ): FinatraRoute = {
    implicit val serverOptions: FinatraServerOptions =
      FinatraServerOptions.default.copy(decodeFailureHandler = decodeFailureHandler.getOrElse(ServerDefaults.decodeFailureHandler))
    e.toRoute
  }

  override def routeRecoverErrors[I, E <: Throwable, O](e: Endpoint[I, E, O, Nothing], fn: I => Future[O])(implicit
      eClassTag: ClassTag[E]
  ): FinatraRoute = {
    e.toRouteRecoverErrors(fn)
  }

  override def server(routes: NonEmptyList[FinatraRoute], port: Port): Resource[IO, Unit] = FinatraServerTests.server(routes, port)

  override lazy val portCounter: PortCounter = new PortCounter(58000)
}

object FinatraServerTests {
  def server(routes: NonEmptyList[FinatraRoute], port: Port)(implicit ioTimer: Timer[IO]): Resource[IO, Unit] = {
    def waitUntilHealthy(s: EmbeddedHttpServer, count: Int): IO[EmbeddedHttpServer] =
      if (s.isHealthy) IO.pure(s)
      else if (count > 1000) IO.raiseError(new IllegalStateException("Server unhealthy"))
      else IO.sleep(10.milliseconds).flatMap(_ => waitUntilHealthy(s, count + 1))

    val bind = IO {
      class TestController extends Controller with TapirController {
        routes.toList.foreach(addTapirRoute)
      }

      class TestServer extends HttpServer {
        @silent("discarded")
        override protected def configureHttp(router: HttpRouter): Unit = {
          router
            .filter[AccessLoggingFilter[Request]]
            .filter[ExceptionMappingFilter[Request]]
            .add(new TestController)
        }
      }

      val server = new EmbeddedHttpServer(
        new TestServer,
        Map(
          "http.port" -> s":$port"
        ),
        // in the default implementation waitForWarmup suspends the thread for 1 second between healthy checks
        // we improve on that by checking every 10ms
        waitForWarmup = false
      )
      server.start()
      server
    }.flatMap(waitUntilHealthy(_, 0))

    Resource
      .make(bind)(httpServer => IO(httpServer.close()))
      .map(_ => ())
  }
} 
Example 20
Source File: ConsumerConfig.scala    From scala-server-toolkit   with MIT License 5 votes vote down vote up
package com.avast.sst.fs2kafka

import java.util.concurrent.TimeUnit.{MILLISECONDS, SECONDS}

import com.avast.sst.fs2kafka.ConsumerConfig._
import com.github.ghik.silencer.silent
import fs2.kafka.{AutoOffsetReset, CommitRecovery, IsolationLevel}
import org.apache.kafka.clients.consumer.{ConsumerConfig => ApacheConsumerConfig}

import scala.concurrent.duration.FiniteDuration
import scala.jdk.CollectionConverters._

@silent("dead code")
final case class ConsumerConfig(
    bootstrapServers: List[String],
    groupId: String,
    groupInstanceId: Option[String] = None,
    clientId: Option[String] = None,
    clientRack: Option[String] = None,
    autoOffsetReset: AutoOffsetReset = AutoOffsetReset.None,
    enableAutoCommit: Boolean = false,
    autoCommitInterval: FiniteDuration = defaultMillis(ApacheConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG),
    allowAutoCreateTopics: Boolean = default(ApacheConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG),
    closeTimeout: FiniteDuration = FiniteDuration(20, SECONDS),
    commitRecovery: CommitRecovery = CommitRecovery.Default,
    commitTimeout: FiniteDuration = FiniteDuration(15, SECONDS),
    defaultApiTimeout: FiniteDuration = defaultMillis(ApacheConsumerConfig.DEFAULT_API_TIMEOUT_MS_CONFIG),
    heartbeatInterval: FiniteDuration = defaultMillis(ApacheConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG),
    isolationLevel: IsolationLevel = defaultIsolationLevel,
    maxPrefetchBatches: Int = 2,
    pollInterval: FiniteDuration = FiniteDuration(50, MILLISECONDS),
    pollTimeout: FiniteDuration = FiniteDuration(50, MILLISECONDS),
    maxPollInterval: FiniteDuration = defaultMillis(ApacheConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG),
    maxPollRecords: Int = default(ApacheConsumerConfig.MAX_POLL_RECORDS_CONFIG),
    requestTimeout: FiniteDuration = defaultMillis(ApacheConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG),
    sessionTimeout: FiniteDuration = defaultMillis(ApacheConsumerConfig.SESSION_TIMEOUT_MS_CONFIG),
    properties: Map[String, String] = Map.empty
)

object ConsumerConfig {

  private val officialDefaults = ApacheConsumerConfig.configDef().defaultValues().asScala

  private def default[A](key: String): A = officialDefaults(key).asInstanceOf[A]

  private def defaultMillis(key: String): FiniteDuration = FiniteDuration(default[Int](key).toLong, MILLISECONDS)

  private val defaultIsolationLevel = default[String](ApacheConsumerConfig.ISOLATION_LEVEL_CONFIG) match {
    case "read_uncommitted" => IsolationLevel.ReadUncommitted
    case "read_committed"   => IsolationLevel.ReadCommitted
  }

} 
Example 21
Source File: ZioServerApp.scala    From scala-server-toolkit   with MIT License 5 votes vote down vote up
package com.avast.sst.bundle

import cats.effect.Resource
import com.github.ghik.silencer.silent
import org.http4s.server.Server
import org.slf4j.LoggerFactory
import zio._
import zio.interop.catz._


trait ZioServerApp extends CatsApp {

  private val logger = LoggerFactory.getLogger(this.getClass)

  def program: Resource[Task, Server[Task]]

  @silent("dead code")
  override def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = {
    program
      .use { server =>
        for {
          _ <- UIO.effectTotal(logger.info(s"Server started @ ${server.address.getHostString}:${server.address.getPort}"))
          _ <- Task.never
        } yield server
      }
      .fold(
        ex => {
          logger.error("Server initialization failed!", ex)
          ExitCode.failure
        },
        _ => ExitCode.success
      )
  }

} 
Example 22
Source File: ServerDefaultsTest.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.server

import com.github.ghik.silencer.silent
import org.scalatest.{FlatSpec, Matchers}
import sttp.tapir.Validator

class ServerDefaultsTest extends FlatSpec with Matchers {
  it should "create a validation error message for a nested field" in {
    // given
    @silent("never used")
    implicit val addressNumberValidator: Validator[Int] = Validator.min(1)
    @silent("fallback derivation")
    val personValidator = Validator.validatorForCaseClass[Person]

    // when
    val validationErrors = personValidator.validate(Person("John", Address("Lane", 0)))

    // then
    ServerDefaults.ValidationMessages.validationErrorsMessage(
      validationErrors
    ) shouldBe "expected address.number to be greater than or equal to 1, but was 0"
  }

  case class Person(name: String, address: Address)
  case class Address(street: String, number: Int)
} 
Example 23
Source File: ValidatorMagnoliaDerivation.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.generic.internal

import com.github.ghik.silencer.silent
import magnolia.{Magnolia, ReadOnlyCaseClass, SealedTrait}
import sttp.tapir.{Validator, generic}
import sttp.tapir.generic.Configuration

trait ValidatorMagnoliaDerivation {
  type Typeclass[T] = Validator[T]

  def combine[T](ctx: ReadOnlyCaseClass[Validator, T])(implicit genericDerivationConfig: Configuration): Validator[T] = {
    Validator.Product(ctx.parameters.map { p =>
      p.label -> new Validator.ProductField[T] {
        override type FieldType = p.PType
        override def name: Validator.FieldName = Validator.FieldName(p.label, genericDerivationConfig.toLowLevelName(p.label))
        override def get(t: T): FieldType = p.dereference(t)
        override def validator: Typeclass[FieldType] = p.typeclass
      }
    }.toMap)
  }

  @silent("never used")
  def dispatch[T](ctx: SealedTrait[Validator, T]): Validator[T] =
    Validator.Coproduct(new generic.SealedTrait[Validator, T] {
      override def dispatch(t: T): Typeclass[T] = ctx.dispatch(t) { v => v.typeclass.asInstanceOf[Validator[T]] }

      override def subtypes: Map[String, Typeclass[Any]] =
        ctx.subtypes.map(st => st.typeName.full -> st.typeclass.asInstanceOf[Validator[scala.Any]]).toMap
    })

  implicit def validatorForCaseClass[T]: Validator[T] = macro Magnolia.gen[T]

  def fallback[T]: Validator[T] = Validator.pass
} 
Example 24
Source File: SchemaMagnoliaDerivation.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.generic.internal

import com.github.ghik.silencer.silent
import magnolia._
import sttp.tapir.SchemaType._
import sttp.tapir.generic.{Configuration, Derived}
import sttp.tapir.{Schema, SchemaType}
import SchemaMagnoliaDerivation.deriveInProgress

import scala.collection.mutable
import scala.language.experimental.macros

trait SchemaMagnoliaDerivation {
  type Typeclass[T] = Schema[T]

  @silent("discarded")
  def combine[T](ctx: ReadOnlyCaseClass[Schema, T])(implicit genericDerivationConfig: Configuration): Schema[T] = {
    withProgressCache { cache =>
      val cacheKey = ctx.typeName.full
      if (cache.contains(cacheKey)) {
        Schema[T](SRef(typeNameToObjectInfo(ctx.typeName)))
      } else {
        try {
          cache.add(cacheKey)
          if (ctx.isValueClass) {
            Schema[T](ctx.parameters.head.typeclass.schemaType)
          } else {
            Schema[T](
              SProduct(
                typeNameToObjectInfo(ctx.typeName),
                ctx.parameters.map(p => (genericDerivationConfig.toLowLevelName(p.label), p.typeclass)).toList
              )
            )
          }
        } finally {
          cache.remove(cacheKey)
        }
      }
    }
  }

  private def typeNameToObjectInfo(typeName: TypeName): SchemaType.SObjectInfo = {
    def allTypeArguments(tn: TypeName): Seq[TypeName] = tn.typeArguments.flatMap(tn2 => tn2 +: allTypeArguments(tn2))
    SObjectInfo(typeName.full, allTypeArguments(typeName).map(_.short).toList)
  }

  private def withProgressCache[T](f: mutable.Set[String] => Schema[T]): Schema[T] = {
    var cache = deriveInProgress.get()
    val newCache = cache == null
    if (newCache) {
      cache = mutable.Set[String]()
      deriveInProgress.set(cache)
    }

    try f(cache)
    finally {
      if (newCache) {
        deriveInProgress.remove()
      }
    }
  }

  def dispatch[T](ctx: SealedTrait[Schema, T]): Schema[T] = {
    Schema(SCoproduct(typeNameToObjectInfo(ctx.typeName), ctx.subtypes.map(_.typeclass).toList, None))
  }

  implicit def schemaForCaseClass[T]: Derived[Schema[T]] = macro MagnoliaDerivedMacro.derivedGen[T]
}

object SchemaMagnoliaDerivation {
  private[internal] val deriveInProgress: ThreadLocal[mutable.Set[String]] = new ThreadLocal()
} 
Example 25
Source File: ReplaceFirstInFn.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.typelevel

import com.github.ghik.silencer.silent


trait ReplaceFirstInFn[I, FN_IK[_], J, FN_JK[_]] {
  def paramsAsArgsIk: ParamsAsArgs.Aux[_, FN_IK]
  def paramsAsArgsJk: ParamsAsArgs.Aux[_, FN_JK]
}

object ReplaceFirstInFn {
  @silent("never used")
  implicit def replaceFirst[FN_IK[_], I, IK, J, JK, FN_JK[_]](implicit
      p1: ParamsAsArgs.Aux[IK, FN_IK],
      r: ReplaceFirstInTuple[I, J, IK, JK],
      p2: ParamsAsArgs.Aux[JK, FN_JK]
  ): ReplaceFirstInFn[I, FN_IK, J, FN_JK] =
    new ReplaceFirstInFn[I, FN_IK, J, FN_JK] {
      override def paramsAsArgsIk: ParamsAsArgs.Aux[_, FN_IK] = p1
      override def paramsAsArgsJk: ParamsAsArgs.Aux[_, FN_JK] = p2
    }
} 
Example 26
Source File: RichToMonadOfEitherFunctionTest.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.server.http4s

import cats.effect.IO
import com.github.ghik.silencer.silent
import org.scalatest.{FunSuite, Matchers}

@silent("never used")
class RichToMonadOfEitherFunctionTest extends FunSuite with Matchers {
  case class Error(r: String)
  case class User(u: String)
  case class Result(r: String)

  test("should compose functions when both succeed") {
    // given
    def f1(p: String): IO[Either[Error, User]] =
      IO {
        Right(User(p))
      }
    def f2(u: User, i: Int, s: String): IO[Either[Error, Result]] =
      IO {
        Right(Result(List(u.toString, i.toString, s).mkString(",")))
      }

    // when
    val result = (f1 _).andThenFirstE((f2 _).tupled).apply(("john", 10, "x")).unsafeRunSync()

    // then
    result shouldBe Right(Result("User(john),10,x"))
  }

  test("should return error if first fails") {
    // given
    def f1(p: String): IO[Either[Error, User]] =
      IO {
        Left(Error("e1"))
      }
    def f2(u: User, i: Int, s: String): IO[Either[Error, Result]] =
      IO {
        Right(Result(List(u.toString, i.toString, s).mkString(",")))
      }

    // when
    val result = (f1 _).andThenFirstE((f2 _).tupled).apply(("john", 10, "x")).unsafeRunSync()

    // then
    result shouldBe Left(Error("e1"))
  }

  test("should return error if second fails") {
    // given
    def f1(p: String): IO[Either[Error, User]] =
      IO {
        Right(User(p))
      }
    def f2(u: User, i: Int, s: String): IO[Either[Error, Result]] =
      IO {
        Left(Error("e2"))
      }

    // when
    val result = (f1 _).andThenFirstE((f2 _).tupled).apply(("john", 10, "x")).unsafeRunSync()

    // then
    result shouldBe Left(Error("e2"))
  }
} 
Example 27
Source File: package.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.server.finatra

import _root_.cats.effect.Effect
import com.github.ghik.silencer.silent
import com.twitter.inject.Logging
import io.catbird.util.Rerunnable
import io.catbird.util.effect._
import sttp.tapir.Endpoint
import sttp.tapir.monad.MonadError
import sttp.tapir.server.ServerEndpoint

import scala.reflect.ClassTag

package object cats {
  implicit class RichFinatraCatsEndpoint[I, E, O](e: Endpoint[I, E, O, Nothing]) extends Logging {
    def toRoute[F[_]](logic: I => F[Either[E, O]])(implicit serverOptions: FinatraServerOptions, eff: Effect[F]): FinatraRoute = {
      e.serverLogic(logic).toRoute
    }

    @silent("never used")
    def toRouteRecoverErrors[F[_]](logic: I => F[O])(implicit
        eIsThrowable: E <:< Throwable,
        eClassTag: ClassTag[E],
        eff: Effect[F]
    ): FinatraRoute = {
      e.serverLogicRecoverErrors(logic).toRoute
    }
  }

  implicit class RichFinatraCatsServerEndpoint[I, E, O, F[_]](e: ServerEndpoint[I, E, O, Nothing, F]) extends Logging {
    def toRoute(implicit serverOptions: FinatraServerOptions, eff: Effect[F]): FinatraRoute = {
      new RichFinatraServerEndpoint(e.endpoint.serverLogic(i => eff.toIO(e.logic(new CatsMonadError)(i)).to[Rerunnable].run)).toRoute
    }

    private class CatsMonadError(implicit F: _root_.cats.MonadError[F, Throwable]) extends MonadError[F] {
      override def unit[T](t: T): F[T] = F.pure(t)
      override def map[T, T2](fa: F[T])(f: T => T2): F[T2] = F.map(fa)(f)
      override def flatMap[T, T2](fa: F[T])(f: T => F[T2]): F[T2] = F.flatMap(fa)(f)
      override def error[T](t: Throwable): F[T] = F.raiseError(t)
      override protected def handleWrappedError[T](rt: F[T])(h: PartialFunction[Throwable, F[T]]): F[T] = F.recoverWith(rt)(h)
    }
  }
} 
Example 28
Source File: messagePatterns.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

object messagePatterns {
  @silent("pure expression")
  def method(): Unit = {
    123
  }
  @silent("something else")
  def other(): Unit = {
    123
  }
} 
Example 29
Source File: package.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.openapi

import com.github.ghik.silencer.silent
import io.circe.generic.semiauto._
import io.circe.parser._
import io.circe.syntax._
import io.circe.{Encoder, Json}
import sttp.tapir.openapi.OpenAPI.ReferenceOr

import scala.collection.immutable.ListMap

package object circe extends TapirOpenAPICirceEncoders

trait TapirOpenAPICirceEncoders {
  // note: these are strict val-s, order matters!

  @silent("possible missing interpolator")
  implicit def encoderReferenceOr[T: Encoder]: Encoder[ReferenceOr[T]] = {
    case Left(Reference(ref)) => Json.obj(("$ref", Json.fromString(ref)))
    case Right(t)             => implicitly[Encoder[T]].apply(t)
  }

  implicit val encoderOAuthFlow: Encoder[OAuthFlow] = deriveEncoder[OAuthFlow]
  implicit val encoderOAuthFlows: Encoder[OAuthFlows] = deriveEncoder[OAuthFlows]
  implicit val encoderSecurityScheme: Encoder[SecurityScheme] = deriveEncoder[SecurityScheme]
  implicit val encoderExampleValue: Encoder[ExampleValue] = {
    case ExampleSingleValue(value)    => parse(value).right.getOrElse(Json.fromString(value))
    case ExampleMultipleValue(values) => Json.arr(values.map(v => parse(v).right.getOrElse(Json.fromString(v))): _*)
  }
  implicit val encoderSchemaType: Encoder[SchemaType.SchemaType] = Encoder.encodeEnumeration(SchemaType)
  implicit val encoderSchema: Encoder[Schema] = deriveEncoder[Schema]
  implicit val encoderReference: Encoder[Reference] = deriveEncoder[Reference]
  implicit val encoderHeader: Encoder[Header] = deriveEncoder[Header]
  implicit val encoderExample: Encoder[Example] = deriveEncoder[Example]
  implicit val encoderResponse: Encoder[Response] = deriveEncoder[Response]
  implicit val encoderEncoding: Encoder[Encoding] = deriveEncoder[Encoding]
  implicit val encoderMediaType: Encoder[MediaType] = deriveEncoder[MediaType]
  implicit val encoderRequestBody: Encoder[RequestBody] = deriveEncoder[RequestBody]
  implicit val encoderParameterStyle: Encoder[ParameterStyle.ParameterStyle] = Encoder.encodeEnumeration(ParameterStyle)
  implicit val encoderParameterIn: Encoder[ParameterIn.ParameterIn] = Encoder.encodeEnumeration(ParameterIn)
  implicit val encoderParameter: Encoder[Parameter] = deriveEncoder[Parameter]
  implicit val encoderResponseMap: Encoder[ListMap[ResponsesKey, ReferenceOr[Response]]] =
    (responses: ListMap[ResponsesKey, ReferenceOr[Response]]) => {
      val fields = responses.map {
        case (ResponsesDefaultKey, r)    => ("default", r.asJson)
        case (ResponsesCodeKey(code), r) => (code.toString, r.asJson)
      }

      Json.obj(fields.toSeq: _*)
    }
  implicit val encoderOperation: Encoder[Operation] = {
    // this is needed to override the encoding of `security: List[SecurityRequirement]`. An empty security requirement
    // should be represented as an empty object (`{}`), not `null`, which is the default encoding of `ListMap`s.
    implicit def encodeListMap[V: Encoder]: Encoder[ListMap[String, V]] = doEncodeListMap(nullWhenEmpty = false)
    deriveEncoder[Operation]
  }
  implicit val encoderPathItem: Encoder[PathItem] = deriveEncoder[PathItem]
  implicit val encoderComponents: Encoder[Components] = deriveEncoder[Components]
  implicit val encoderServerVariable: Encoder[ServerVariable] = deriveEncoder[ServerVariable]
  implicit val encoderServer: Encoder[Server] = deriveEncoder[Server]
  implicit val encoderExternalDocumentation: Encoder[ExternalDocumentation] = deriveEncoder[ExternalDocumentation]
  implicit val encoderTag: Encoder[Tag] = deriveEncoder[Tag]
  implicit val encoderInfo: Encoder[Info] = deriveEncoder[Info]
  implicit val encoderContact: Encoder[Contact] = deriveEncoder[Contact]
  implicit val encoderLicense: Encoder[License] = deriveEncoder[License]
  implicit val encoderOpenAPI: Encoder[OpenAPI] = deriveEncoder[OpenAPI]
  implicit val encoderDiscriminator: Encoder[Discriminator] = deriveEncoder[Discriminator]
  implicit def encodeList[T: Encoder]: Encoder[List[T]] = {
    case Nil        => Json.Null
    case l: List[T] => Json.arr(l.map(i => implicitly[Encoder[T]].apply(i)): _*)
  }
  implicit def encodeListMap[V: Encoder]: Encoder[ListMap[String, V]] = doEncodeListMap(nullWhenEmpty = true)

  private def doEncodeListMap[V: Encoder](nullWhenEmpty: Boolean): Encoder[ListMap[String, V]] = {
    case m: ListMap[String, V] if m.isEmpty && nullWhenEmpty => Json.Null
    case m: ListMap[String, V] =>
      val properties = m.mapValues(v => implicitly[Encoder[V]].apply(v)).toList
      Json.obj(properties: _*)
  }
} 
Example 30
Source File: MultipleEndpointsDocumentationAkkaServer.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.examples

import java.util.concurrent.atomic.AtomicReference

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import com.github.ghik.silencer.silent
import io.circe.generic.auto._
import sttp.tapir._
import sttp.tapir.docs.openapi._
import sttp.tapir.json.circe._
import sttp.tapir.openapi.OpenAPI
import sttp.tapir.openapi.circe.yaml._
import sttp.tapir.server.akkahttp._
import sttp.tapir.swagger.akkahttp.SwaggerAkka

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

object MultipleEndpointsDocumentationAkkaServer extends App {
  // endpoint descriptions
  case class Author(name: String)
  case class Book(title: String, year: Int, author: Author)

  val booksListing: Endpoint[Unit, Unit, Vector[Book], Nothing] = endpoint.get
    .in("books")
    .in("list" / "all")
    .out(jsonBody[Vector[Book]])

  val addBook: Endpoint[Book, Unit, Unit, Nothing] = endpoint.post
    .in("books")
    .in("add")
    .in(
      jsonBody[Book]
        .description("The book to add")
        .example(Book("Pride and Prejudice", 1813, Author("Jane Austen")))
    )

  // server-side logic
  val books = new AtomicReference(
    Vector(
      Book("The Sorrows of Young Werther", 1774, Author("Johann Wolfgang von Goethe")),
      Book("Iliad", -8000, Author("Homer")),
      Book("Nad Niemnem", 1888, Author("Eliza Orzeszkowa")),
      Book("The Colour of Magic", 1983, Author("Terry Pratchett")),
      Book("The Art of Computer Programming", 1968, Author("Donald Knuth")),
      Book("Pharaoh", 1897, Author("Boleslaw Prus"))
    )
  )

  val booksListingRoute = booksListing.toRoute(_ => Future.successful(Right(books.get())))
  @silent("discarded")
  val addBookRoute = addBook.toRoute(book => Future.successful(Right(books.getAndUpdate(books => books :+ book))))

  // generating the documentation in yml; extension methods come from imported packages
  val openApiDocs: OpenAPI = List(booksListing, addBook).toOpenAPI("The tapir library", "1.0.0")
  val openApiYml: String = openApiDocs.toYaml

  // starting the server
  implicit val actorSystem: ActorSystem = ActorSystem()
  import actorSystem.dispatcher

  val routes = {
    import akka.http.scaladsl.server.Directives._
    booksListingRoute ~ addBookRoute ~ new SwaggerAkka(openApiYml).routes
  }

  val bindAndCheck = Http().bindAndHandle(routes, "localhost", 8080).map { _ =>
    // testing
    println("Go to: http://localhost:8080/docs")
    println("Press any key to exit ...")
    scala.io.StdIn.readLine()
  }

  // cleanup
  Await.result(bindAndCheck.transformWith { r => actorSystem.terminate().transform(_ => r) }, 1.minute)
} 
Example 31
Source File: MultipleEndpointsDocumentationHttp4sServer.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.examples

import java.util.concurrent.atomic.AtomicReference

import cats.effect._
import cats.implicits._
import com.github.ghik.silencer.silent
import io.circe.generic.auto._
import org.http4s.HttpRoutes
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.syntax.kleisli._
import sttp.tapir._
import sttp.tapir.docs.openapi._
import sttp.tapir.json.circe._
import sttp.tapir.openapi.OpenAPI
import sttp.tapir.openapi.circe.yaml._
import sttp.tapir.server.http4s._
import sttp.tapir.swagger.http4s.SwaggerHttp4s

import scala.concurrent.ExecutionContext

object MultipleEndpointsDocumentationHttp4sServer extends App {
  // endpoint descriptions
  case class Author(name: String)
  case class Book(title: String, year: Int, author: Author)

  val booksListing: Endpoint[Unit, Unit, Vector[Book], Nothing] = endpoint.get
    .in("books")
    .in("list" / "all")
    .out(jsonBody[Vector[Book]])

  val addBook: Endpoint[Book, Unit, Unit, Nothing] = endpoint.post
    .in("books")
    .in("add")
    .in(
      jsonBody[Book]
        .description("The book to add")
        .example(Book("Pride and Prejudice", 1813, Author("Jane Austen")))
    )

  // server-side logic
  implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
  implicit val contextShift: ContextShift[IO] = IO.contextShift(ec)
  implicit val timer: Timer[IO] = IO.timer(ec)

  val books = new AtomicReference(
    Vector(
      Book("The Sorrows of Young Werther", 1774, Author("Johann Wolfgang von Goethe")),
      Book("Iliad", -8000, Author("Homer")),
      Book("Nad Niemnem", 1888, Author("Eliza Orzeszkowa")),
      Book("The Colour of Magic", 1983, Author("Terry Pratchett")),
      Book("The Art of Computer Programming", 1968, Author("Donald Knuth")),
      Book("Pharaoh", 1897, Author("Boleslaw Prus"))
    )
  )

  val booksListingRoutes: HttpRoutes[IO] = booksListing.toRoutes(_ => IO(books.get().asRight[Unit]))
  @silent("discarded")
  val addBookRoutes: HttpRoutes[IO] = addBook.toRoutes(book => IO((books.getAndUpdate(books => books :+ book): Unit).asRight[Unit]))
  val routes: HttpRoutes[IO] = booksListingRoutes <+> addBookRoutes

  // generating the documentation in yml; extension methods come from imported packages
  val openApiDocs: OpenAPI = List(booksListing, addBook).toOpenAPI("The tapir library", "1.0.0")
  val openApiYml: String = openApiDocs.toYaml

  // starting the server
  BlazeServerBuilder[IO](ec)
    .bindHttp(8080, "localhost")
    .withHttpApp(Router("/" -> (routes <+> new SwaggerHttp4s(openApiYml).routes[IO])).orNotFound)
    .resource
    .use { _ =>
      IO {
        println("Go to: http://localhost:8080/docs")
        println("Press any key to exit ...")
        scala.io.StdIn.readLine()
      }
    }
    .unsafeRunSync()
} 
Example 32
Source File: PriceServiceError.scala    From http4s-poc-api   with MIT License 5 votes vote down vote up
package errors

import cats.syntax.show._
import com.github.ghik.silencer.silent
import external.library.ThrowableMap
import external.library.instances.throwable._
import shapeless.{::, Generic, HNil}

sealed trait PriceServiceError extends Exception with Product with Serializable

object PriceServiceError {
  final case class UserErr(reason: String)                extends PriceServiceError
  final case class PreferenceErr(reason: String)          extends PriceServiceError
  final case class ProductErr(reason: String)             extends PriceServiceError
  final case class ProductPriceErr(reason: String)        extends PriceServiceError
  final case class InvalidShippingCountry(reason: String) extends PriceServiceError
  final case class CacheLookupError(reason: String)       extends PriceServiceError
  final case class CacheStoreError(reason: String)        extends PriceServiceError

  @silent implicit def stringThrowableMap[A](
    implicit ev: A <:< PriceServiceError,
    gen: Generic.Aux[A, String :: HNil]
  ): ThrowableMap[A] =
    new ThrowableMap[A] {
      def map(th: Throwable): A =
        gen from (th.show :: HNil)
    }
} 
Example 33
Source File: Main.scala    From http4s-poc-api   with MIT License 5 votes vote down vote up
package server

import java.util.concurrent.Executors

import com.github.ghik.silencer.silent
import external.{TeamOneHttpApi, TeamThreeCacheApi, TeamTwoHttpApi}
import io.circe.generic.auto._
import log.effect.zio.ZioLogWriter._
import model.DomainModel._
import org.http4s.circe._
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.syntax.kleisli._
import org.http4s.{EntityDecoder, EntityEncoder, HttpApp}
import service.PriceService
import zio.interop.catz._
import zio.interop.catz.implicits._
import zio.{ExitCode, RIO, Task, ZEnv, ZIO}

import scala.concurrent.ExecutionContext
import model.DomainModelCodecs._

@silent
object Main extends zio.interop.catz.CatsApp with Pools with Codecs {
  private[this] val priceService: RIO[String, PriceService[Task]] =
    log4sFromName map { log =>
      PriceService[Task](
        TeamThreeCacheApi.productCache,
        TeamOneHttpApi(),
        TeamTwoHttpApi(),
        log
      )
    }

  private[this] val httpApp: RIO[PriceService[Task], HttpApp[Task]] =
    ZIO.access { ps =>
      Router(
        "/pricing-api/prices"       -> PriceRoutes[Task].make(ps),
        "/pricing-api/health-check" -> HealthCheckRoutes[Task].make(ps.logger)
      ).orNotFound
    }

  private[this] val runningServer: RIO[HttpApp[Task], Unit] =
    ZIO.accessM { app =>
      BlazeServerBuilder[Task](serverPool)
        .bindHttp(17171, "0.0.0.0")
        .withConnectorPoolSize(connectorPoolSize)
        .enableHttp2(true)
        .withHttpApp(app)
        .serve
        .compile
        .drain
    }

  private[this] val serviceRuntime: RIO[String, Unit] =
    priceService >>> httpApp >>> runningServer

  def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] =
    serviceRuntime.fold(_ => ExitCode.failure, _ => ExitCode.success) provide "App log"
}

sealed trait Pools {

  protected val connectorPoolSize = Runtime.getRuntime.availableProcessors() * 2
  protected val mainThreadNumber  = Runtime.getRuntime.availableProcessors() + 1

  protected val serverPool = ExecutionContext.fromExecutor(
    Executors.newWorkStealingPool(mainThreadNumber)
  )
}

sealed trait Codecs {
  implicit val priceRequestPayloadDecoder: EntityDecoder[Task, PricesRequestPayload] =
    jsonOf[Task, PricesRequestPayload]

  implicit val priceResponsePayloadEncoder: EntityEncoder[Task, List[Price]] =
    jsonEncoderOf[Task, List[Price]]

  implicit val healthCheckResponsePayloadEncoder: EntityEncoder[Task, ServiceSignature] =
    jsonEncoderOf[Task, ServiceSignature]
} 
Example 34
Source File: Selector.scala    From zio-nio   with Apache License 2.0 5 votes vote down vote up
package zio.nio.channels

import java.io.IOException
import java.nio.channels.{ ClosedSelectorException, Selector => JSelector, SelectionKey => JSelectionKey }

import com.github.ghik.silencer.silent
import zio.duration.Duration
import zio.nio.channels.spi.SelectorProvider
import zio.nio.core.channels.SelectionKey
import zio.{ IO, Managed, UIO }

import scala.jdk.CollectionConverters._

class Selector(private[nio] val selector: JSelector) {

  final val provider: UIO[SelectorProvider] =
    IO.effectTotal(selector.provider()).map(new SelectorProvider(_))

  @silent
  final val keys: IO[ClosedSelectorException, Set[SelectionKey]] =
    IO.effect(selector.keys())
      .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_)))
      .refineToOrDie[ClosedSelectorException]

  @silent
  final val selectedKeys: IO[ClosedSelectorException, Set[SelectionKey]] =
    IO.effect(selector.selectedKeys())
      .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_)))
      .refineToOrDie[ClosedSelectorException]

  final def removeKey(key: SelectionKey): IO[ClosedSelectorException, Unit] =
    IO.effect(selector.selectedKeys().remove(key.selectionKey))
      .unit
      .refineToOrDie[ClosedSelectorException]

  
  final val select: IO[Exception, Int] =
    IO.effect(selector.select()).refineToOrDie[IOException]

  final val wakeup: IO[Nothing, Selector] =
    IO.effectTotal(selector.wakeup()).map(new Selector(_))

  final private[channels] val close: IO[IOException, Unit] =
    IO.effect(selector.close()).refineToOrDie[IOException].unit
}

object Selector {

  final val make: Managed[IOException, Selector] = {
    val open = IO.effect(new Selector(JSelector.open())).refineToOrDie[IOException]
    Managed.make(open)(_.close.orDie)
  }
} 
Example 35
Source File: Selector.scala    From zio-nio   with Apache License 2.0 5 votes vote down vote up
package zio.nio.core.channels

import java.io.IOException
import java.nio.channels.{ ClosedSelectorException, Selector => JSelector, SelectionKey => JSelectionKey }

import com.github.ghik.silencer.silent
import zio.duration.Duration
import zio.nio.core.channels.spi.SelectorProvider
import zio.{ IO, UIO }

import scala.jdk.CollectionConverters._

class Selector(private[nio] val selector: JSelector) {
  final val isOpen: UIO[Boolean] = IO.effectTotal(selector.isOpen)

  final val provider: UIO[SelectorProvider] =
    IO.effectTotal(selector.provider()).map(new SelectorProvider(_))

  @silent
  final val keys: IO[ClosedSelectorException, Set[SelectionKey]] =
    IO.effect(selector.keys())
      .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_)))
      .refineToOrDie[ClosedSelectorException]

  @silent
  final val selectedKeys: IO[ClosedSelectorException, Set[SelectionKey]] =
    IO.effect(selector.selectedKeys())
      .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_)))
      .refineToOrDie[ClosedSelectorException]

  final def removeKey(key: SelectionKey): IO[ClosedSelectorException, Unit] =
    IO.effect(selector.selectedKeys().remove(key.selectionKey))
      .unit
      .refineToOrDie[ClosedSelectorException]

  
  final val select: IO[Exception, Int] =
    IO.effect(selector.select()).refineToOrDie[IOException]

  final val wakeup: IO[Nothing, Selector] =
    IO.effectTotal(selector.wakeup()).map(new Selector(_))

  final val close: IO[IOException, Unit] =
    IO.effect(selector.close()).refineToOrDie[IOException].unit
}

object Selector {

  final val make: IO[IOException, Selector] =
    IO.effect(new Selector(JSelector.open())).refineToOrDie[IOException]
} 
Example 36
Source File: FileChannel.scala    From zio-nio   with Apache License 2.0 5 votes vote down vote up
package zio.nio.core.channels

import java.io.IOException
import java.nio.channels.{ FileChannel => JFileChannel }
import java.nio.file.OpenOption
import java.nio.file.attribute.FileAttribute

import com.github.ghik.silencer.silent
import zio.blocking.{ Blocking, _ }
import zio.nio.core.file.Path
import zio.nio.core.{ ByteBuffer, MappedByteBuffer }
import zio.{ IO, ZIO }

import scala.collection.JavaConverters._

final class FileChannel private[channels] (override protected[channels] val channel: JFileChannel)
    extends GatheringByteChannel
    with ScatteringByteChannel {
  def position: IO[IOException, Long] = IO.effect(channel.position()).refineToOrDie[IOException]

  def position(newPosition: Long): IO[Exception, Unit] =
    IO.effect(channel.position(newPosition)).unit.refineToOrDie[Exception]

  def size: IO[IOException, Long] = IO.effect(channel.size()).refineToOrDie[IOException]

  def truncate(size: Long): ZIO[Blocking, Exception, Unit] =
    effectBlocking(channel.truncate(size)).unit.refineToOrDie[Exception]

  def force(metadata: Boolean): ZIO[Blocking, IOException, Unit] =
    effectBlocking(channel.force(metadata)).refineToOrDie[IOException]

  def transferTo(position: Long, count: Long, target: GatheringByteChannel): ZIO[Blocking, Exception, Long] =
    effectBlocking(channel.transferTo(position, count, target.channel)).refineToOrDie[Exception]

  def transferFrom(src: ScatteringByteChannel, position: Long, count: Long): ZIO[Blocking, Exception, Long] =
    effectBlocking(channel.transferFrom(src.channel, position, count)).refineToOrDie[Exception]

  def read(dst: ByteBuffer, position: Long): ZIO[Blocking, Exception, Int] =
    dst
      .withJavaBuffer[Blocking, Throwable, Int](buffer => effectBlocking(channel.read(buffer, position)))
      .refineToOrDie[Exception]

  def write(src: ByteBuffer, position: Long): ZIO[Blocking, Exception, Int] =
    src
      .withJavaBuffer[Blocking, Throwable, Int](buffer => effectBlocking(channel.write(buffer, position)))
      .refineToOrDie[Exception]

  def map(mode: JFileChannel.MapMode, position: Long, size: Long): ZIO[Blocking, Exception, MappedByteBuffer] =
    ZIO
      .accessM[Blocking](_.get.effectBlocking(new MappedByteBuffer(channel.map(mode, position, size))))
      .refineToOrDie[Exception]

  def lock(
    position: Long = 0L,
    size: Long = Long.MaxValue,
    shared: Boolean = false
  ): ZIO[Blocking, Exception, FileLock] =
    effectBlocking(new FileLock(channel.lock(position, size, shared))).refineToOrDie[Exception]

  def tryLock(
    position: Long = 0L,
    size: Long = Long.MaxValue,
    shared: Boolean = false
  ): IO[Exception, Option[FileLock]] =
    ZIO.effect(Option(channel.tryLock(position, size, shared)).map(new FileLock(_))).refineToOrDie[Exception]
}

object FileChannel {

  @silent
  def open(
    path: Path,
    options: Set[_ <: OpenOption],
    attrs: FileAttribute[_]*
  ): ZIO[Blocking, Exception, FileChannel] =
    effectBlocking(new FileChannel(JFileChannel.open(path.javaPath, options.asJava, attrs: _*)))
      .refineToOrDie[Exception]

  def open(path: Path, options: OpenOption*): ZIO[Blocking, Exception, FileChannel] =
    effectBlocking(new FileChannel(JFileChannel.open(path.javaPath, options: _*)))
      .refineToOrDie[Exception]

  def fromJava(javaFileChannel: JFileChannel): ZIO[Blocking, Nothing, FileChannel] =
    effectBlocking(new FileChannel(javaFileChannel)).orDie

  type MapMode = JFileChannel.MapMode

  object MapMode {
    def READ_ONLY: FileChannel.MapMode  = JFileChannel.MapMode.READ_ONLY
    def READ_WRITE: FileChannel.MapMode = JFileChannel.MapMode.READ_WRITE
    def PRIVATE: FileChannel.MapMode    = JFileChannel.MapMode.PRIVATE
  }
} 
Example 37
Source File: RoutingEngine.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.routing

import com.avsystem.commons._
import com.avsystem.commons.misc.AbstractCase
import com.github.ghik.silencer.silent
import io.udash._
import io.udash.logging.CrossLogging
import io.udash.properties.PropertyCreator
import io.udash.utils.CallbacksHandler
import io.udash.utils.FilteringUtils._
import io.udash.view.ViewRenderer

import scala.annotation.tailrec

final case class StateChangeEvent[S <: State](currentState: S, oldState: S) extends AbstractCase


  def currentStateProperty: ReadableProperty[HierarchyRoot] = currentStateProp.readable

  @tailrec
  private def getStatePath(forState: Option[HierarchyRoot], acc: List[HierarchyRoot] = Nil): List[HierarchyRoot] = forState match {
    case Some(state) => getStatePath(state.parentState, state :: acc)
    case None => acc
  }

  private def getUpdatablePathSize(path: Iterator[HierarchyRoot], oldPath: Iterator[HierarchyRoot]): Int =
    path.zip(oldPath).takeWhile {
      case (h1, h2) => viewFactoryRegistry.matchStateToResolver(h1) == viewFactoryRegistry.matchStateToResolver(h2)
    }.length

  private def cleanup(state: Iterator[(View, Presenter[_])]): Unit = {
    state.foreach { case (view, presenter) =>
      Try(view.onClose()).failed.foreach(logger.warn("Error closing view.", _))
      Try(presenter.onClose()).failed.foreach(logger.warn("Error closing presenter.", _))
    }
  }

} 
Example 38
Source File: HttpReadsLegacyInstances.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent
import play.api.libs.json
import play.api.libs.json.{JsNull, JsValue}


trait HttpReadsLegacyInstances extends HttpReadsLegacyOption with HttpReadsLegacyJson

trait HttpReadsLegacyRawReads extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit val readRaw: HttpReads[HttpResponse] = new HttpReads[HttpResponse] {
    @silent("deprecated")
    def read(method: String, url: String, response: HttpResponse) = handleResponse(method, url)(response)
  }
}

object HttpReadsLegacyRawReads extends HttpReadsLegacyRawReads

trait HttpReadsLegacyOption extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit def readOptionOf[P](implicit rds: HttpReads[P]): HttpReads[Option[P]] = new HttpReads[Option[P]] {
    def read(method: String, url: String, response: HttpResponse) = response.status match {
      case 204 | 404 => None
      case _         => Some(rds.read(method, url, response))
    }
  }
}

trait HttpReadsLegacyJson extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit def readFromJson[O](implicit rds: json.Reads[O], mf: Manifest[O]): HttpReads[O] = new HttpReads[O] {
    def read(method: String, url: String, response: HttpResponse) =
      readJson(method, url, handleResponse(method, url)(response).json)
  }

  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  def readSeqFromJsonProperty[O](name: String)(implicit rds: json.Reads[O], mf: Manifest[O]) = new HttpReads[Seq[O]] {
    def read(method: String, url: String, response: HttpResponse) = response.status match {
      case 204 | 404 => Seq.empty
      case _ =>
        readJson[Seq[O]](method, url, (handleResponse(method, url)(response).json \ name).getOrElse(JsNull)) //Added JsNull here to force validate to fail - replicates existing behaviour
    }
  }

  private def readJson[A](method: String, url: String, jsValue: JsValue)(implicit rds: json.Reads[A], mf: Manifest[A]) =
    jsValue
      .validate[A]
      .fold(
        errs => throw new JsValidationException(method, url, mf.runtimeClass, errs.toString()),
        valid => valid
      )
} 
Example 39
Source File: ScalismoPublisher.scala    From scalismo-ui   with GNU General Public License v3.0 5 votes vote down vote up
package scalismo.ui.event

import com.github.ghik.silencer.silent
import scalismo.ui.util.EdtUtil

import scala.swing.Publisher


  @deprecated(message = "use method publishEvent instead", since = "always")
  @silent
  override def publish(e: Event): Unit = {
    doPublish(e)
  }

  // this is the preferred method to use
  def publishEvent(e: Event): Unit = {
    EdtUtil.onEdtWait(doPublish(e))
  }

  private def doPublish(e: Event): Unit = {
    // make sure that each listener is notified, even if the
    // listeners change during the handling.
    val copy = listeners.map(l => l)
    copy.foreach { l =>
      if (l.isDefinedAt(e)) l(e)
    }
  }
} 
Example 40
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 41
Source File: LoginController.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import com.github.ghik.silencer.silent
import io.flow.common.v0.models.UserReference
import io.flow.dependency.v0.models.GithubAuthenticationForm
import io.flow.dependency.www.lib
import io.flow.dependency.www.lib.{DependencyClientProvider, UiData}
import io.flow.play.controllers.IdentifiedCookie._
import io.flow.play.util.Config
import play.api.i18n._
import play.api.mvc._

import scala.concurrent.ExecutionContext

class LoginController @javax.inject.Inject()(
  val provider: DependencyClientProvider,
  val controllerComponents: ControllerComponents,
  config: Config
)(implicit ec: ExecutionContext, dependencyConfig: lib.GitHubConfig) extends play.api.mvc.BaseController with I18nSupport {

  def index(returnUrl: Option[String]) = Action { implicit request =>
    Ok(views.html.login.index(UiData(requestPath = request.path, config = config), returnUrl))
  }

  @silent
  def githubCallback(
    code: String,
    state: Option[String],
    returnUrl: Option[String]
  ): Action[AnyContent] = Action.async { implicit request =>
    provider.newClient(user = None, requestId = None).githubUsers.postGithub(
      GithubAuthenticationForm(
        code = code
      )
    ).map { user =>
      val url = returnUrl match {
        case None => {
          routes.ApplicationController.index().path
        }
        case Some(u) => {
          assert(u.startsWith("/"), s"Redirect URL[$u] must start with /")
          u
        }
      }
      Redirect(url).withIdentifiedCookieUser(user = UserReference(user.id))
    }.recover {
      case response: io.flow.dependency.v0.errors.GenericErrorsResponse =>
        Ok(views.html.login.index(UiData(requestPath = request.path, config = config), returnUrl, response.genericErrors.flatMap(_.messages)))
    }
  }

} 
Example 42
Source File: StreamModuleMock.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.test.mock.module

import com.github.ghik.silencer.silent

import zio.stream.ZSink
import zio.test.mock.{ Mock, Proxy }
import zio.{ Has, UIO, URLayer, ZLayer }


object StreamModuleMock extends Mock[StreamModule] {

  object Sink   extends Sink[Any, String, Int, Nothing, List[Int]]
  object Stream extends Stream[Any, String, Int]

  @silent("is never used")
  val compose: URLayer[Has[Proxy], StreamModule] =
    ZLayer.fromServiceM { proxy =>
      withRuntime.map { rts =>
        new StreamModule.Service {
          def sink(a: Int) =
            rts.unsafeRun(proxy(Sink, a).catchAll(error => UIO(ZSink.fail[String, Int](error).dropLeftover)))
          def stream(a: Int) = rts.unsafeRun(proxy(Stream, a))
        }
      }
    }
} 
Example 43
Source File: REPLSpec.scala    From zio   with Apache License 2.0 5 votes vote down vote up
import com.github.ghik.silencer.silent

import zio.test._

object REPLSpec extends DefaultRunnableSpec {

  @silent("Unused import")
  def spec = suite("REPLSpec")(
    test("settings compile") {
      import zio.Runtime.default._
      import zio._
      import zio.console._
      import zio.duration._
      @silent("never used")
      implicit class RunSyntax[A](io: ZIO[ZEnv, Any, A]) {
        def unsafeRun: A =
          Runtime.default.unsafeRun(io.provideLayer(ZEnv.live))
      }
      assertCompletes
    }
  )
} 
Example 44
Source File: StreamREPLSpec.scala    From zio   with Apache License 2.0 5 votes vote down vote up
import com.github.ghik.silencer.silent

import zio.test._

object StreamREPLSpec extends DefaultRunnableSpec {

  @silent("Unused import")
  def spec = suite("StreamREPLSpec")(
    test("settings compile") {
      import zio.Runtime.default._
      import zio._
      import zio.console._
      import zio.duration._
      import zio.stream._
      @silent("never used")
      implicit class RunSyntax[A](io: ZIO[ZEnv, Any, A]) {
        def unsafeRun: A =
          Runtime.default.unsafeRun(io.provideLayer(ZEnv.live))
      }
      assertCompletes
    }
  )
} 
Example 45
Source File: CallbackSequencer.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.properties

import com.github.ghik.silencer.silent

import scala.collection.mutable


final class CallbackSequencer {
  type Id = String

  private var starts: Int = 0
  private val queue: mutable.LinkedHashMap[Id, () => Any] = mutable.LinkedHashMap.empty

  private def start(): Unit =
    starts += 1

  private def end(): Unit =
    starts -= 1

  private def commit(): Unit = {
    if (starts == 1) {
      val used = mutable.HashSet[Id]()
      while (queue.nonEmpty) {
        queue.retain { case (id, callback) =>
          if (used.add(id)) {
            callback()
          }
          false //removes
        }: @silent("deprecated")
      }
    }
  }

  def queue(id: Id, fireListeners: () => Any): Unit = {
    sequence(queue += id -> fireListeners)
  }

  def sequence(code: => Any): Unit = {
    start()
    try {
      code
      commit()
    } finally {
      end()
    }
  }
}

object CallbackSequencer {
  private val tl: ThreadLocal[CallbackSequencer] = new ThreadLocal[CallbackSequencer]

  def apply(): CallbackSequencer = {
    if (tl.get() == null) tl.set(new CallbackSequencer)
    tl.get()
  }
} 
Example 46
Source File: HttpResponse.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent
import play.api.libs.json.{JsValue, Json}


// This trait will be replaced with a case class (Which will remove coupling to specific types, enable `.copy` etc (useful for testing))
// To not break clients, we will discourage use of extending HttpResponse, rather use the apply functions. We will be able to introduce
// the case class afterwards.
trait HttpResponse {
  def status: Int

  def body: String

  @deprecated("For reading use headers instead. If setting, use HttpResponse.apply instead. You should not extend HttpResponse, but create instances with HttpResponse.apply", "11.0.0")
  def allHeaders: Map[String, Seq[String]]

  // final to help migrate away from allHeaders (i.e. read only - set via HttpResponse.apply)
  @silent("deprecated")
  final def headers: Map[String, Seq[String]]
    = allHeaders

  def json: JsValue =
    Json.parse(body)

  def header(key: String): Option[String] =
    headers.get(key).flatMap(_.headOption)

  override def toString: String =
    s"HttpResponse status=$status"
}

object HttpResponse {
  @deprecated("Use alternative HttpResponse.apply functions instead", "11.0.0")
  def apply(
    responseStatus : Int,
    responseJson   : Option[JsValue]          = None,
    responseHeaders: Map[String, Seq[String]] = Map.empty,
    responseString : Option[String]           = None
  ) = new HttpResponse {
    override def status    : Int                      = responseStatus
    override def body      : String                   = responseString.orElse(responseJson.map(Json.prettyPrint)).orNull
    override def allHeaders: Map[String, Seq[String]] = responseHeaders
    override def json      : JsValue                  = responseJson.orNull
  }

  def apply(
    status : Int,
    body   : String
  ): HttpResponse =
    apply(
      status  = status,
      body    = body,
      headers = Map.empty
    )

  def apply(
    status : Int,
    body   : String,
    headers: Map[String, Seq[String]]
  ): HttpResponse = {
    val pStatus  = status
    val pBody    = body
    val pHeaders = headers
    new HttpResponse {
      override def status    : Int                      = pStatus
      override def body      : String                   = pBody
      override def allHeaders: Map[String, Seq[String]] = pHeaders
    }
  }

  def apply(
    status : Int,
    json   : JsValue,
    headers: Map[String, Seq[String]]
  ): HttpResponse = {
    val pStatus  = status
    val pJson    = json
    val pHeaders = headers
    new HttpResponse {
      override def status    : Int                      = pStatus
      override def body      : String                   = Json.prettyPrint(pJson)
      override def allHeaders: Map[String, Seq[String]] = pHeaders
      override def json      : JsValue                  = pJson
    }
  }

  def unapply(that: HttpResponse): Option[(Int, String, Map[String, Seq[String]])] =
    Some((that.status, that.body, that.headers))
} 
Example 47
Source File: TestRPC.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.rpc

import com.avsystem.commons.rpc.rpcName
import com.avsystem.commons.serialization.HasGenCodec
import com.github.ghik.silencer.silent
import io.udash.rpc.utils.Logged

import scala.concurrent.Future

case class Record(i: Int, fuu: String)
object Record extends HasGenCodec[Record]

case class CustomRPCException(i: Int) extends Throwable
object CustomRPCException extends HasGenCodec[CustomRPCException]

trait RPCMethods {
  @silent
  def handle: Unit

  def handleMore(): Unit

  @rpcName("doStuffBase")
  def doStuff(lol: Int, fuu: String)(cos: Option[Boolean]): Unit

  @rpcName("doStuffInteger")
  def doStuff(num: Int): Unit

  def takeCC(r: Record): Unit

  def srslyDude(): Unit
}


  def rpcImpl(onInvocation: (String, List[Any], Option[Any]) => Any): TestClientRPC =
    new TestClientRPC with RPCMethodsImpl {
      override def onInvocationInternal: (String, List[Any], Option[Any]) => Any = onInvocation

      override def innerRpc(name: String): InnerClientRPC = {
        onInvocationInternal("innerRpc", List(List(name)), None)
        new InnerClientRPC {
          def proc(): Unit =
            onFire("innerRpc.proc", List(Nil))
        }
      }
    }
} 
Example 48
Source File: RepeatDemo.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.guide.views.frontend.demos

import com.github.ghik.silencer.silent
import io.udash.web.guide.demos.AutoDemo
import io.udash.web.guide.styles.partials.GuideStyles
import scalatags.JsDom.all._

object RepeatDemo extends AutoDemo {

  private val (rendered, source) = {
    import io.udash._
    import io.udash.css.CssView._
    import org.scalajs.dom.window
    import scalatags.JsDom.all._

    import scala.util.Random

    val integers = SeqProperty(1, 2, 3, 4)

    window.setInterval(() => {
      val size = integers.get.size
      val idx = Random.nextInt(size)
      val amount = Random.nextInt(size - idx) + 1
      val count = Random.nextInt(5)
      integers.replace(idx, amount, Stream.range(idx, idx + amount * count + 1, amount): _*): @silent("deprecated")
    }, 2000)

    p(
      "Integers: ",
      span(id := "repeat-demo-integers")(repeat(integers)(p =>
        span(GuideStyles.highlightRed)(s"${p.get}, ").render
      )), br,
      "Integers (produce): ",
      produce(integers)(seq => span(id := "repeat-demo-integers-produce")(
        seq.map(p => span(GuideStyles.highlightRed)(s"$p, "))
      ).render)
    )
  }.withSourceCode

  override protected def demoWithSource(): (Modifier, Iterator[String]) = {
    import io.udash.css.CssView._
    (div(id := "repeat-demo", GuideStyles.frame)(rendered), source.linesIterator)
  }
} 
Example 49
Source File: ProduceDemo.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.guide.views.frontend.demos

import com.github.ghik.silencer.silent
import io.udash.web.guide.demos.AutoDemo
import io.udash.web.guide.styles.partials.GuideStyles
import scalatags.JsDom.all._

object ProduceDemo extends AutoDemo {

  private val (rendered, source) = {
    import io.udash._
    import io.udash.css.CssView._
    import org.scalajs.dom.window
    import scalatags.JsDom.all._

    import scala.util.Random

    @silent("deprecated")
    val names = Stream.continually(Stream("John", "Amy", "Bryan", "Diana")).flatten.iterator
    val name = Property(names.next())
    val integers = SeqProperty(1, 2, 3, 4)

    window.setInterval(() => {
      name.set(names.next())

      val size = integers.get.size
      val idx = Random.nextInt(size)
      val amount = Random.nextInt(size - idx) + 1
      val count = Random.nextInt(5)
      integers.replace(idx, amount, Stream.range(idx, idx + amount * count + 1, amount): _*): @silent("deprecated")
    }, 2000)

    p(
      "Name: ",
      produce(name)(value => b(id := "produce-demo-name")(value).render), br,
      "Integers: ",
      span(id := "produce-demo-integers")(
        produce(integers)(seq => span(GuideStyles.highlightRed)(seq.mkString(",")).render)
      )
    ).render
  }.withSourceCode

  override protected def demoWithSource(): (Modifier, Iterator[String]) = {
    import io.udash.css.CssView._
    (
      div(
        id := "produce-demo",
        GuideStyles.frame
      )(rendered),
      source.linesIterator
    )
  }
} 
Example 50
Source File: BindDemo.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.guide.views.frontend.demos

import com.github.ghik.silencer.silent
import io.udash.css.CssView
import io.udash.web.guide.demos.AutoDemo
import io.udash.web.guide.styles.partials.GuideStyles
import scalatags.JsDom.all._

object BindDemo extends AutoDemo with CssView {

  private val (rendered, source) = {
    import io.udash._
    import org.scalajs.dom.window
    import scalatags.JsDom.all._

    @silent("deprecated")
    val names = Stream.continually(Stream("John", "Amy", "Bryan", "Diana")).flatten.iterator

    val name = Property(names.next())
    window.setInterval(() => name.set(names.next()), 500)

    p("Name: ", bind(name))
  }.withSourceCode

  override protected def demoWithSource(): (Modifier, Iterator[String]) = {
    (
      div(
        id := "bind-demo",
        GuideStyles.frame
      )(rendered),
      source.linesIterator
    )
  }
} 
Example 51
Source File: NativeHelpers.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch.helpers

import com.github.ghik.silencer.silent
import org.scalajs.dom.Element
import org.scalajs.dom.raw.CSSStyleDeclaration

import scala.scalajs.js
import scala.scalajs.js.annotation.JSBracketAccess

private[outwatch] object JSDefined {
  // provides an extractor for js.UndefOr
  // https://gitter.im/scala-js/scala-js?at=5c3e221135350772cf375515
  def apply[A](a: A): js.UndefOr[A] = a
  def unapply[A](a: js.UndefOr[A]): UnapplyResult[A] = new UnapplyResult(a)

  final class UnapplyResult[+A](val self: js.UndefOr[A])
  extends AnyVal {
    @inline def isEmpty: Boolean = self eq js.undefined
    
    @inline def get: A = self.asInstanceOf[A]
  }
}

@js.native
@silent("never used|dead code")
private[outwatch] trait DictionaryRawApply[A] extends js.Object {
  @JSBracketAccess
  def apply(key: String): js.UndefOr[A] = js.native
}

private[outwatch] object NativeHelpers {
  implicit class WithRaw[A](val dict: js.Dictionary[A]) extends AnyVal {
    @inline def raw: DictionaryRawApply[A] = dict.asInstanceOf[DictionaryRawApply[A]]
  }

  implicit class RichElement(val elem: Element) extends AnyVal {
    @inline def style: CSSStyleDeclaration = elem.asInstanceOf[js.Dynamic].style.asInstanceOf[CSSStyleDeclaration] // HTMLElement already has .style, but SVGElement doesn't
    @inline def dataset: js.Dictionary[String] = elem.asInstanceOf[js.Dynamic].dataset.asInstanceOf[js.Dictionary[String]] //TODO: https://github.com/scala-js/scala-js-dom/pull/337
  }

  @inline def assign[T](value: T)(f: T => Unit): T = { f(value); value }

  @noinline def appendSeq[T](source: js.Array[T], other: collection.Seq[T]): js.Array[T] = if (other.isEmpty) source else other match {
    case wrappedOther:js.WrappedArray[T] =>
      if (source.isEmpty) wrappedOther.array else source.concat(wrappedOther.array)
    case _ =>
      val arr = new js.Array[T]()
      source.foreach(arr.push(_))
      other.foreach(arr.push(_))
      arr
  }

  @noinline def prependSeq[T](source: js.Array[T], other: collection.Seq[T]): js.Array[T] = if (other.isEmpty) source else other match {
    case wrappedOther:js.WrappedArray[T] =>
      if (source.isEmpty) wrappedOther.array else wrappedOther.array.concat(source)
    case _ =>
      val arr = new js.Array[T]()
      other.foreach(arr.push(_))
      source.foreach(arr.push(_))
      arr
  }
} 
Example 52
Source File: Macro.scala    From zio-macros   with Apache License 2.0 5 votes vote down vote up
package zio.macros.accessible

import com.github.ghik.silencer.silent
import zio.macros.core.ModulePattern

import scala.reflect.macros.whitebox.Context

private[macros] class Macro(val c: Context) extends ModulePattern {
  import c.universe._

  case class Config(name: Option[String])

  def apply(annottees: c.Tree*): c.Tree = {

    @silent("pattern var [^\\s]+ in method unapply is never used")
    val config: Config = c.prefix.tree match {
      case Apply(_, args) =>
        val name = args.collectFirst { case q"$cfg" => c.eval(c.Expr[String](cfg)) }.map { ident =>
          util.Try(c.typecheck(c.parse(s"object $ident {}"))) match {
            case util.Failure(_) =>
              c.abort(c.enclosingPosition, s"""Invalid identifier "$ident". Cannot generate accessors object.""")
            case util.Success(_) => ident
          }
        }

        Config(name)
      case other => c.abort(c.enclosingPosition, s"Invalid accessible macro call ${showRaw(other)}")
    }

    val trees            = extractTrees(annottees)
    val module           = extractModule(trees.module)
    val companion        = extractCompanion(trees.companion)
    val service          = extractService(companion.body)
    val capabilites      = extractCapabilities(service)
    val accessors        = generateCapabilityAccessors(module.name, module.serviceName, capabilites)
    val updatedCompanion = generateUpdatedCompanion(config, module, companion, accessors)

    q"""
       ${trees.module}
       $updatedCompanion
     """
  }

  private def generateCapabilityAccessors(
    moduleType: TypeName,
    serviceName: TermName,
    capabilities: List[Capability]
  ): List[Tree] =
    capabilities.map { capability =>
      val (name, e, a) = (capability.name, capability.error, capability.value)
      val mods =
        if (capability.impl == EmptyTree) Modifiers()
        else Modifiers(Flag.OVERRIDE)

      val returnType = tq"_root_.zio.ZIO[$moduleType, $e, $a]"
      val returnValue =
        capability.argLists match {
          case Some(argLists) if argLists.flatten.nonEmpty =>
            val argNames = argLists.map(_.map(_.name))
            q"_root_.zio.ZIO.accessM(_.$serviceName.$name(...$argNames))"
          case _ =>
            q"_root_.zio.ZIO.accessM(_.$serviceName.$name)"
        }

      capability.argLists match {
        case None            => q"$mods val $name: $returnType = $returnValue"
        case Some(Nil)       => q"$mods def $name: $returnType = $returnValue"
        case Some(List(Nil)) => q"$mods def $name(): $returnType = $returnValue"
        case Some(argLists)  => q"$mods def $name(...$argLists): $returnType = $returnValue"
      }
    }

  private def generateUpdatedCompanion(
    config: Config,
    module: ModuleSummary,
    companion: CompanionSummary,
    capabilityAccessors: List[Tree]
  ): Tree = {

    val accessor: Tree = config.name match {
      case Some(name) => c.parse(s"object $name extends Accessors")
      case None       => EmptyTree
    }

    q"""
      object ${companion.name} {

        ..${companion.body}

       trait Accessors extends Service[${module.name}] {
         ..$capabilityAccessors
       }

       $accessor
     }
    """
  }
} 
Example 53
Source File: LedgerWriter.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.participant.state.kvutils.api

import com.daml.ledger.api.health.ReportsHealth
import com.daml.ledger.participant.state.kvutils.Bytes
import com.daml.ledger.participant.state.v1.{ParticipantId, SubmissionResult}
import com.github.ghik.silencer.silent

import scala.concurrent.Future


  @silent("deprecated")
  def commit(
      correlationId: String,
      envelope: Bytes,
      metadata: CommitMetadata,
  ): Future[SubmissionResult] =
    commit(correlationId, envelope)

  @deprecated("Will be removed in 1.4.0", "1.3.0")
  def commit(
      correlationId: String,
      envelope: Bytes,
  ): Future[SubmissionResult] = commit(correlationId, envelope, CommitMetadata.Empty)
} 
Example 54
Source File: DispatcherImpl.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.akkastreams.dispatcher

import java.util.concurrent.atomic.AtomicReference

import akka.NotUsed
import akka.stream.scaladsl.Source
import com.github.ghik.silencer.silent
import org.slf4j.LoggerFactory

import scala.collection.immutable

final class DispatcherImpl[Index: Ordering](
    name: String,
    zeroIndex: Index,
    headAtInitialization: Index)
    extends Dispatcher[Index] {

  private val logger = LoggerFactory.getLogger(getClass)

  require(
    !indexIsBeforeZero(headAtInitialization),
    s"head supplied at Dispatcher initialization $headAtInitialization is before zero index $zeroIndex. " +
      s"This would imply that the ledger end is before the ledger begin, which makes this invalid configuration."
  )

  private sealed abstract class State extends Product with Serializable {
    def getSignalDispatcher: Option[SignalDispatcher]

    def getLastIndex: Index
  }

  // the following silent are due to
  // <https://github.com/scala/bug/issues/4440>
  @silent
  private final case class Running(lastIndex: Index, signalDispatcher: SignalDispatcher)
      extends State {
    override def getLastIndex: Index = lastIndex

    override def getSignalDispatcher: Option[SignalDispatcher] = Some(signalDispatcher)
  }

  @silent
  private final case class Closed(lastIndex: Index) extends State {
    override def getLastIndex: Index = lastIndex

    override def getSignalDispatcher: Option[SignalDispatcher] = None
  }

  // So why not broadcast the actual new index, instead of using a signaller?
  // The reason is if we do that, the new indices race with readHead
  // in a way that makes it hard to start up new subscriptions. In particular,
  // we can tolerate NewIndexSignals being out of order or dropped, maintaining the weaker invariant that,
  // if head is updated, at least one NewIndexSignal eventually arrives.

  private val state = new AtomicReference[State](Running(headAtInitialization, SignalDispatcher()))

  
    override def apply(newHead: Index): immutable.Iterable[(Index, Index)] =
      if (Ordering[Index].gt(newHead, max)) {
        val intervalBegin = max
        max = newHead
        List(intervalBegin -> newHead)
      } else Nil
  }

  private def indexIsBeforeZero(checkedIndex: Index): Boolean =
    Ordering[Index].gt(zeroIndex, checkedIndex)

  def close(): Unit =
    state.getAndUpdate {
      case Running(idx, _) => Closed(idx)
      case c: Closed => c
    } match {
      case Running(idx, disp) =>
        disp.signal()
        disp.close()
      case c: Closed => ()
    }

  private def closedError: IllegalStateException =
    new IllegalStateException(s"$name: Dispatcher is closed")

} 
Example 55
Source File: MongoObservableReactivePublisherTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package mongo.async

import com.avsystem.commons.concurrent.RunNowEC
import com.github.ghik.silencer.silent
import com.mongodb.async.{client => mongo}
import monix.execution.{Cancelable, Scheduler}
import org.mockito.ArgumentMatchers.{eq => eqTo, _}
import org.mockito.Mockito
import org.mockito.Mockito._
import org.mongodb.scala.{Completed, Document, FindObservable, MongoCollection, SingleObservable}
import org.scalactic.source.Position
import org.scalatest.freespec.AnyFreeSpec

import scala.concurrent.duration.Duration

@silent("deprecated")
class MongoObservableReactivePublisherTest extends AnyFreeSpec {

  abstract class MockedObservableTests(implicit position: Position) extends MongoObservableExtensions {

    def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit

    "should drop test collection" in {
      val collection = Mockito.mock(classOf[MongoCollection[Document]])
      when(collection.drop()).thenReturn(SingleObservable(Completed()))
      val dropSubscriber = TestSubscriber[Completed]()

      subscribe(collection.drop(), dropSubscriber)

      dropSubscriber.assertNoTerminalEvent()
      dropSubscriber.requestMore(1)
      dropSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      dropSubscriber.assertNoErrors()
      dropSubscriber.assertReceivedOnNext(Seq(Completed()))

      verify(collection).drop()
      verifyNoMoreInteractions(collection)
    }

    "should insert documents" in {
      val collection = Mockito.mock(classOf[MongoCollection[Document]])
      val insertSubscriber = TestSubscriber[Completed]()
      when(collection.insertMany(any())).thenReturn(SingleObservable(Completed()))

      val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) }
      subscribe(collection.insertMany(documents), insertSubscriber)
      insertSubscriber.requestMore(1)
      insertSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      insertSubscriber.assertNoErrors()
      insertSubscriber.assertReceivedOnNext(Seq(Completed()))

      verify(collection).insertMany(eqTo(documents))
      verifyNoMoreInteractions(collection)
    }

    "should find documents" in {
      val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) }
      val original = Mockito.mock(classOf[FindObservable[Document]])
      val findSubscriber = TestSubscriber[Document]()
      doNothing().when(original).subscribe(any())

      subscribe(original, findSubscriber)
      findSubscriber.assertNoTerminalEvent()
      findSubscriber.requestMore(101)
      documents.foreach(findSubscriber.onNext)
      findSubscriber.onComplete()
      findSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      findSubscriber.assertNoErrors()
      findSubscriber.assertReceivedOnNext(documents)


      verify(original).subscribe(any(classOf[mongo.Observer[_ >: Document]]))
      verifyNoMoreInteractions(original)
    }
  }

  "A Mongo-Reactive observable" - new MockedObservableTests {
    override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit =
      obs.asReactive.subscribe(testSubscriber)
  }
  "A Mongo-Monix observable" - new MockedObservableTests {
    override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit =
      obs.asMonix.subscribe(
        monix.reactive.observers.Subscriber.fromReactiveSubscriber(testSubscriber, Cancelable.empty)(Scheduler(RunNowEC))
      )
  }
} 
Example 56
Source File: classSuppression.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

object classSuppression {
  @silent
  class suppressed {
    def method(): Unit = {
      123
    }
  }
  class notSuppressed {
    def method(): Unit = {
      123
    }
  }

} 
Example 57
Source File: unusedSuppressions.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

object unusedSuppressions {
  @deprecated("", "") def defaultArg: Int = 42
  class A(i: Int = defaultArg: @silent)

  @silent def nothingToSuppress(): Unit = ()

  @silent def enoughSuppression(): Unit = {
    123
  }

  @silent def tooMuchSuppression(): Unit = {
    123: @silent
  }
} 
Example 58
Source File: lateWarning.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

object lateWarning {
  // main method in companion object of a trait will trigger a warning in compiler backend

  trait Suppressed
  @silent object Suppressed {
    def main(args: Array[String]) = ()
  }

  trait NotSuppressed
  object NotSuppressed {
    def main(args: Array[String]) = ()
  }
} 
Example 59
Source File: macroExpandeeSuppression.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package testdata

import com.github.ghik.silencer.silent

import scala.language.experimental.macros

object macroExpandeeSuppression {
  def discard(expr: Any): Unit = macro com.github.ghik.silencer.MacroImpls.discard

  discard {
    123: Unit
    456: @silent
  }

  discard {
    123
  }: @silent
} 
Example 60
Source File: ApiTypecheckingTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package redis

import com.avsystem.commons.redis.commands.Encoding
import com.github.ghik.silencer.silent

object ApiTypecheckingTest {

  locally {
    import RedisApi.Batches.StringTyped._

    val tupleBatch: RedisBatch[(Opt[String], Long)] =
      (get("key1"), incr("key2")).sequence

    val seqBatch: RedisBatch[Seq[Opt[String]]] =
      (1 to 10).map(i => get(s"key$i")).sequence

    val tupleCollectionBatch: RedisBatch[Seq[(Opt[String], Long)]] =
      (1 to 10).map(i => (get(s"stringKey$i"), incr(s"numberKey$i"))).sequence
  }


  locally {
    import RedisApi.Batches.StringTyped._

    // tuple of batches -> single batch of a tuple
    val tupleBatch: RedisBatch[(Opt[String], Long)] =
      RedisBatch.sequence(get("key1"), incr("key2"))

    // collection of batches -> single batch of a collection
    val seqBatch: RedisBatch[Seq[Opt[String]]] =
      RedisBatch.sequence((1 to 10).map(i => get(s"key$i")))

    // collection of tuples of batches -> single batch of collection of tuples
    val tupleCollectionBatch2: RedisBatch[Seq[(Opt[String], Long)]] =
      RedisBatch.sequence((1 to 10).map(i => (get(s"stringKey$i"), incr(s"numberKey$i"))))
  }

  locally {
    import RedisApi.Batches.StringTyped._

    // collection of batches -> single batch of a collection
    val seqBatch: RedisBatch[Seq[Opt[String]]] =
      RedisBatch.traverse(1 to 10)(i => get(s"key$i"))

    // collection of tuples of batches -> single batch of collection of tuples
    val tupleCollectionBatch2: RedisBatch[Seq[(Opt[String], Long)]] =
      RedisBatch.traverse(1 to 10)(i => RedisBatch.sequence(get(s"stringKey$i"), incr(s"numberKey$i")))
  }

  locally {
    val ser = RedisSerialization.Strings.valueType[Int]
    val api = RedisApi.Batches[ser.type]
    import api._
    val transactionOp: RedisOp[Unit] = for {
      // we're sending WATCH and GET commands in a single batch
      value <- watch("number") *> get("number").map(_.getOrElse(1))
      // SET command is wrapped in MULTI-EXEC block
      _ <- set("number", value * 3).transaction
    } yield ()
  }

  locally {
    val ser = RedisSerialization.Strings.valueType[Encoding]
    val api = RedisApi.Batches[ser.type]
    api.set("lol", Encoding.HashTable)
  }

  locally {
    import RedisApi.Batches.StringTyped._
    val keys = (0 to 5).map(i => s"key$i")
    val sumBatch1: RedisBatch[Long] = RedisBatch.foldLeft(keys.map(scard), 0L)(_ + _)
    val sumBatch2: RedisBatch[Long] = RedisBatch.foldLeftMap(keys, 0L)(scard)(_ + _)
  }

} 
Example 61
Source File: RedisMsgScalacheck.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package redis.protocol

import akka.util.ByteString
import com.github.ghik.silencer.silent
import org.scalacheck.util.Buildable
import org.scalacheck.{Arbitrary, Gen, Shrink}


object RedisMsgScalacheck {
  implicit val byteStringBuildable: Buildable[Byte, ByteString] =
    new Buildable[Byte, ByteString] {
      def builder: MBuilder[Byte, ByteString] = ByteString.newBuilder
    }

  implicit val shrinkSimpleString: Shrink[SimpleStringMsg] =
    Shrink(ss => Shrink.shrink(ss.string).map(SimpleStringMsg(_)))

  implicit val shrinkError: Shrink[ErrorMsg] =
    Shrink(err => Shrink.shrink(err.errorString).map(ErrorMsg(_)))

  implicit val shrinkBulkString: Shrink[BulkStringMsg] =
    Shrink(bs => Shrink.shrink(bs.string).map(BulkStringMsg(_)))

  implicit val shrinkArray: Shrink[ArrayMsg[RedisMsg]] =
    Shrink(arr => Shrink.shrink(arr.elements).map(ArrayMsg(_)))

  @silent("deprecated")
  implicit val shrinkRedisProtocolMsg: Shrink[RedisMsg] = Shrink {
    case ss: SimpleStringMsg => Shrink.shrink(ss)
    case er: ErrorMsg => Shrink.shrink(er)
    case NullBulkStringMsg => Stream.empty
    case bs: BulkStringMsg => Shrink.shrink(bs)
    case im: IntegerMsg => Shrink.shrink(im)
    case NullArrayMsg => Stream.empty
    case am: ArrayMsg[RedisMsg] => Shrink.shrink(am)
  }

  val simpleBytes = (Byte.MinValue.toInt to Byte.MaxValue.toInt)
    .filter(b => b != '\n'.toInt && b != '\r'.toInt).map(_.toByte)

  def byteGen = Gen.chooseNum(Byte.MinValue, Byte.MaxValue, '\r'.toByte, '\n'.toByte)
  def simpleByteGen = Gen.oneOf(simpleBytes)

  def bytesGen: Gen[ByteString] = Gen.buildableOf[ByteString, Byte](byteGen)
  def simpleBytesGen: Gen[ByteString] = Gen.buildableOf[ByteString, Byte](simpleByteGen)

  def simpleStringGen = simpleBytesGen.map(SimpleStringMsg(_))
  def errorGen = simpleBytesGen.map(ErrorMsg(_))
  def integerGen = Arbitrary.arbitrary[Long].map(IntegerMsg(_))

  def bulkStringGen: Gen[RedisMsg] = Gen.sized(s => Gen.choose(-1, s).flatMap {
    case -1 => Gen.const(NullBulkStringMsg)
    case n => Gen.buildableOfN[ByteString, Byte](n, byteGen).map(bs => BulkStringMsg(bs))
  })

  def arrayGen: Gen[RedisMsg] = Gen.sized(s => Gen.choose(-1, s).flatMap {
    case -1 => Gen.const(NullArrayMsg)
    case 0 => Gen.const(ArrayMsg(IndexedSeq.empty))
    case n => Gen.buildableOfN[IndexedSeq[RedisMsg], RedisMsg](n, Gen.resize(s / n, redisProtocolMsgGen))
      .map(els => ArrayMsg(els))
  })

  def redisProtocolMsgGen: Gen[RedisMsg] =
    Gen.oneOf(simpleStringGen, errorGen, integerGen, bulkStringGen, arrayGen)
} 
Example 62
Source File: ScalaParameterNameDiscoverer.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package spring

import java.lang.reflect.{Constructor, Executable, Method, Modifier}

import com.github.ghik.silencer.silent
import org.springframework.core.{JdkVersion, ParameterNameDiscoverer}

import scala.annotation.tailrec
import scala.ref.WeakReference
import scala.reflect.api.JavaUniverse
import scala.reflect.{ScalaLongSignature, ScalaSignature}

object ScalaParameterNameDiscoverer {
  final val ScalaSignatureClasses =
    List(classOf[ScalaSignature], classOf[ScalaLongSignature])

  @silent("deprecated")
  final val JdkAtLeast8 =
    JdkVersion.getMajorJavaVersion >= JdkVersion.JAVA_18

  // we don't want to keep the universe in memory forever, so we don't use scala.reflect.runtime.universe
  private var universeRef: WeakReference[JavaUniverse] = _

  private def universe: JavaUniverse = {
    universeRef.option.flatMap(_.get) match {
      case Some(result) => result
      case None =>
        val result = new scala.reflect.runtime.JavaUniverse
        universeRef = new WeakReference[JavaUniverse](result)
        result
    }
  }
}

class ScalaParameterNameDiscoverer extends ParameterNameDiscoverer {

  import ScalaParameterNameDiscoverer._

  @tailrec private def isScala(cls: Class[_]): Boolean = cls.getEnclosingClass match {
    case null => ScalaSignatureClasses.exists(ac => cls.getAnnotation(ac) != null)
    case encls => isScala(encls)
  }

  private def discoverNames(u: JavaUniverse)(executable: Executable, symbolPredicate: u.Symbol => Boolean): Array[String] = {
    import u._

    val declaringClass = executable.getDeclaringClass
    val mirror = runtimeMirror(declaringClass.getClassLoader)
    val ownerSymbol =
      if (Modifier.isStatic(executable.getModifiers)) mirror.moduleSymbol(declaringClass).moduleClass.asType
      else mirror.classSymbol(declaringClass)

    def argErasuresMatch(ms: MethodSymbol) =
      ms.paramLists.flatten.map(s => mirror.runtimeClass(s.typeSignature)) == executable.getParameterTypes.toList

    def paramNames(ms: MethodSymbol) =
      ms.paramLists.flatten.map(_.name.toString).toArray

    ownerSymbol.toType.members
      .find(s => symbolPredicate(s) && argErasuresMatch(s.asMethod))
      .map(s => paramNames(s.asMethod))
      .orNull
  }

  def getParameterNames(ctor: Constructor[_]): Array[String] =
    if (JdkAtLeast8 && ctor.getParameters.forall(_.isNamePresent))
      ctor.getParameters.map(_.getName)
    else if (isScala(ctor.getDeclaringClass))
      discoverNames(universe)(ctor, s => s.isConstructor)
    else null

  def getParameterNames(method: Method): Array[String] = {
    val declaringCls = method.getDeclaringClass
    if (JdkAtLeast8 && method.getParameters.forall(_.isNamePresent))
      method.getParameters.map(_.getName)
    else if (isScala(declaringCls)) {
      // https://github.com/scala/bug/issues/10650
      val forStaticForwarder =
        if (Modifier.isStatic(method.getModifiers))
          Class.forName(declaringCls.getName + "$", false, declaringCls.getClassLoader)
            .recoverToOpt[ClassNotFoundException]
            .flatMap(_.getMethod(method.getName, method.getParameterTypes: _*).recoverToOpt[NoSuchMethodException])
            .map(getParameterNames)
        else
          Opt.Empty
      forStaticForwarder.getOrElse(
        discoverNames(universe)(method, s => s.isMethod && s.name.toString == method.getName))
    }
    else null
  }
} 
Example 63
Source File: AttrNames.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package spring

import com.github.ghik.silencer.silent
import org.springframework.beans.factory.support.AbstractBeanDefinition


object AttrNames {
  final val AbstractAttr = "%abstract"
  final val ArgTypesAttr = "%arg-types"
  final val ArrayAttr = "%array"
  final val AutowireAttr = "%autowire"
  final val AutowireCandidateAttr = "%autowire-candidate"
  final val ClassAttr = "%class"
  final val ConstructAttr = "%construct"
  final val ConstructorArgsAttr = "%constructor-args"
  final val DependencyCheckAttr = "%dependency-check"
  final val DependsOnAttr = "%depends-on"
  final val DescriptionAttr = "%description"
  final val DestroyMethodAttr = "%destroy-method"
  final val EntriesAttr = "%entries"
  final val FactoryBeanAttr = "%factory-bean"
  final val FactoryMethodAttr = "%factory-method"
  final val IdrefAttr = "%idref"
  final val IndexAttr = "%index"
  final val InitMethodAttr = "%init-method"
  final val KeyAttr = "%key"
  final val KeyTypeAttr = "%key-type"
  final val LazyInitAttr = "%lazy-init"
  final val ListAttr = "%list"
  final val LookupMethodsAttr = "%lookup-methods"
  final val MergeAttr = "%merge"
  final val MetaAttr = "%meta"
  final val NameAttr = "%name"
  final val ParentAttr = "%parent"
  final val PrimaryAttr = "%primary"
  final val PropsAttr = "%props"
  final val QualifiersAttr = "%qualifiers"
  final val RefAttr = "%ref"
  final val ReplacedMethodsAttr = "%replaced-methods"
  final val ReplacerAttr = "%replacer"
  final val ScopeAttr = "%scope"
  final val SetAttr = "%set"
  final val TypeAttr = "%type"
  final val ValueAttr = "%value"
  final val ValueTypeAttr = "%value-type"
  final val ConfigAttr = "%config"

  final val BeanAttrs = Set(
    AbstractAttr,
    AutowireAttr,
    AutowireCandidateAttr,
    ClassAttr,
    ConstructAttr,
    ConstructorArgsAttr,
    DependencyCheckAttr,
    DependsOnAttr,
    DescriptionAttr,
    DestroyMethodAttr,
    FactoryBeanAttr,
    FactoryMethodAttr,
    InitMethodAttr,
    LazyInitAttr,
    LookupMethodsAttr,
    MetaAttr,
    NameAttr,
    ParentAttr,
    PrimaryAttr,
    QualifiersAttr,
    ReplacedMethodsAttr,
    ScopeAttr)

  final val AutowireMapping = Map(
    "no" -> AbstractBeanDefinition.AUTOWIRE_NO,
    "byName" -> AbstractBeanDefinition.AUTOWIRE_BY_NAME,
    "byType" -> AbstractBeanDefinition.AUTOWIRE_BY_TYPE,
    "constructor" -> AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR,
    "autodetect" -> AbstractBeanDefinition.AUTOWIRE_AUTODETECT: @silent
  )

  final val ReverseAutowireMapping = AutowireMapping.map(_.swap)

  final val DependencyCheckMapping = Map(
    "none" -> AbstractBeanDefinition.DEPENDENCY_CHECK_NONE,
    "simple" -> AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE,
    "objects" -> AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS,
    "all" -> AbstractBeanDefinition.DEPENDENCY_CHECK_ALL
  )

  final val ReverseDependencyCheckMapping = DependencyCheckMapping.map(_.swap)
} 
Example 64
Source File: LedgerIdRequirementTest.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.configuration

import com.github.ghik.silencer.silent
import org.scalatest.{Matchers, WordSpec}

@silent("deprecated")
class LedgerIdRequirementTest extends WordSpec with Matchers {

  "LedgerIdRequirement" when {
    "matching a specific value" should {
      "accept a matching ledger ID" in {
        val expected = "ledger-a"
        val requirement = LedgerIdRequirement.matching(expected)
        requirement.isAccepted(expected) shouldBe true
      }

      "reject any other ledger ID" in {
        val requirement = LedgerIdRequirement.matching("ledger-b")
        requirement.isAccepted("not-b") shouldBe false
      }

      "construct, matching the deprecated constructor" in {
        val requirement = LedgerIdRequirement("ledger-c", enabled = true)
        requirement shouldBe LedgerIdRequirement.matching("ledger-c")
      }

      "copy as usual" in {
        val requirement = LedgerIdRequirement.matching("ledger-d")
        val copied = requirement.copy(ledgerId = Some("ledger-e"))
        copied shouldBe LedgerIdRequirement.matching("ledger-e")
      }

      "copy, matching the deprecated constructor" in {
        val requirement = LedgerIdRequirement.matching("ledger-f")
        val copied = requirement.copy(ledgerId = "ledger-g")
        copied shouldBe LedgerIdRequirement.matching("ledger-g")
      }
    }

    "none" should {
      "allow any ledger ID" in {
        val requirement = LedgerIdRequirement.none
        requirement.isAccepted("any-ledger") shouldBe true
      }

      "construct, matching the deprecated constructor" in {
        val requirement = LedgerIdRequirement("ledger-1", enabled = false)
        requirement shouldBe LedgerIdRequirement.none
      }

      "copy as usual" in {
        val requirement = LedgerIdRequirement.matching("ledger-2")
        val copied = requirement.copy(ledgerId = Some("ledger-3"))
        copied shouldBe LedgerIdRequirement.matching("ledger-3")
      }

      "copy, matching the deprecated constructor" in {
        val requirement = LedgerIdRequirement.none
        val copied = requirement.copy(ledgerId = "ledger-4")
        copied shouldBe LedgerIdRequirement.none
      }
    }
  }
} 
Example 65
Source File: MongoObservableReactivePublisher.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package mongo.async

import com.github.ghik.silencer.silent
import com.mongodb.async.{client => mongo}
import monix.execution.atomic.AtomicBoolean
import org.{reactivestreams => reactive}

@silent("deprecated")
final class MongoObservableReactivePublisher[T](observable: mongo.Observable[T]) extends reactive.Publisher[T] {
  def subscribe(subscriber: reactive.Subscriber[_ >: T]): Unit = {
    observable.subscribe(
      new mongo.Observer[T]() {
        override def onSubscribe(subscription: mongo.Subscription): Unit = {
          subscriber.onSubscribe(new reactive.Subscription() {
            private final val cancelled: AtomicBoolean = AtomicBoolean(false)

            def request(n: Long): Unit = {
              if (!subscription.isUnsubscribed && n <= 0) {
                subscriber.onError(new IllegalArgumentException(
                  """3.9 While the Subscription is not cancelled,
                    |Subscription.request(long n) MUST throw a java.lang.IllegalArgumentException if the
                    |argument is <= 0.""".stripMargin
                ))
              } else {
                subscription.request(n)
              }
            }

            def cancel(): Unit = {
              if (!cancelled.getAndSet(true)) subscription.unsubscribe()
            }
          })
        }

        def onNext(result: T): Unit = subscriber.onNext(result)

        def onError(e: Throwable): Unit = subscriber.onError(e)

        def onComplete(): Unit = subscriber.onComplete()
      }
    )
  }
} 
Example 66
Source File: MongoObservableExtensions.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package mongo.async

import com.github.ghik.silencer.silent

trait MongoObservableExtensions {

  import MongoObservableExtensions._

  @silent("deprecated")
  implicit def mongoObservableOps[T](obs: com.mongodb.async.client.Observable[T]): MongoObservableOps[T] = new MongoObservableOps[T](obs)
}

object MongoObservableExtensions extends MongoObservableExtensions {
  @silent("deprecated")
  final class MongoObservableOps[T](private val obs: com.mongodb.async.client.Observable[T]) extends AnyVal {
    def asReactive: org.reactivestreams.Publisher[T] = new MongoObservableReactivePublisher[T](obs)
    def asMonix: monix.reactive.Observable[T] = monix.reactive.Observable.fromReactivePublisher(asReactive)
  }
} 
Example 67
Source File: Connector.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.connectors

import com.github.ghik.silencer.silent
import play.api.libs.ws.{WS, WSRequest}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.HeaderCarrierConverter

trait RequestBuilder {
  def buildRequest(url: String)(implicit hc: HeaderCarrier): WSRequest
}

object RequestBuilder {
  def headers(hc: HeaderCarrier): Seq[(String,String)] = {
    hc.headers.filter { case (name,value) => name != HeaderCarrierConverter.Path }
  }
}

trait PlayWSRequestBuilder extends RequestBuilder {
  @silent("deprecated")
  def buildRequest(url: String)(implicit hc: HeaderCarrier): WSRequest =
    WS.url(url)(play.api.Play.current)
      .withHeaders(RequestBuilder.headers(hc): _*)
}

trait WSClientRequestBuilder extends RequestBuilder {
  this: WSClientProvider =>
  def buildRequest(url: String)(implicit hc: HeaderCarrier): WSRequest = client.url(url).withHeaders(RequestBuilder.headers(hc): _*)
} 
Example 68
Source File: WSRequest.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.http.ws

import com.github.ghik.silencer.silent
import play.api.libs.ws.{DefaultWSProxyServer, WSClient, WSProxyServer, WSRequest => PlayWSRequest }
import play.api.{Configuration, Play}
import uk.gov.hmrc.http.HeaderCarrier

trait WSRequest extends WSRequestBuilder {

  import play.api.libs.ws.WS

  @silent("deprecated")
  def wsClient: WSClient =
    WS.client(play.api.Play.current)

  def buildRequest[A](url: String, headers: Seq[(String, String)] = Seq.empty)(implicit hc: HeaderCarrier): PlayWSRequest =
    wsClient.url(url)
      .withHeaders(applicableHeaders(url)(hc): _*)
      .withHeaders(headers: _*)
}

trait WSProxy extends WSRequest {

  def wsProxyServer: Option[WSProxyServer]

  override def buildRequest[A](url: String, headers: Seq[(String, String)])(implicit hc: HeaderCarrier): PlayWSRequest =
    wsProxyServer match {
      case Some(proxy) => super.buildRequest(url, headers).withProxyServer(proxy)
      case None        => super.buildRequest(url, headers)
    }
}

object WSProxyConfiguration {

  def apply(configPrefix: String, configuration: Configuration): Option[WSProxyServer] = {
    val proxyRequired = configuration.getBoolean(s"$configPrefix.proxyRequiredForThisEnvironment").getOrElse(true)

    if (proxyRequired) Some(parseProxyConfiguration(configPrefix, configuration)) else None
  }

  @silent("deprecated")
  def apply(configPrefix: String): Option[WSProxyServer] =
    apply(configPrefix, play.api.Play.current.configuration)

  private def parseProxyConfiguration(configPrefix: String, configuration: Configuration) =
    DefaultWSProxyServer(
      protocol =
        configuration.getString(s"$configPrefix.protocol").orElse(throw ProxyConfigurationException("protocol")),
      host      = configuration.getString(s"$configPrefix.host").getOrElse(throw ProxyConfigurationException("host")),
      port      = configuration.getInt(s"$configPrefix.port").getOrElse(throw ProxyConfigurationException("port")),
      principal = configuration.getString(s"$configPrefix.username"),
      password  = configuration.getString(s"$configPrefix.password")
    )

  case class ProxyConfigurationException(key: String)
      extends RuntimeException(s"Missing proxy configuration - key '$key' not found")
} 
Example 69
Source File: HttpErrorFunctionsSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent
import org.scalacheck.Gen
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.TryValues
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

import scala.util.Try

@silent("deprecated")
class HttpErrorFunctionsSpec
    extends AnyWordSpec
    with Matchers
    with ScalaCheckDrivenPropertyChecks
    with TableDrivenPropertyChecks
    with TryValues {

  "HttpErrorFunctions" should {
    "return the response if the status code is between 200 and 299" in new HttpErrorFunctions {
      forAll(Gen.choose(200, 299)) { statusCode: Int =>
        val expectedResponse = HttpResponse(statusCode, "")
        handleResponse(exampleVerb, exampleUrl)(expectedResponse) should be(expectedResponse)
      }
    }

    "return the correct exception if the status code is 400" in {
      expectA[BadRequestException](forStatus = 400)
    }

    "return the correct exception if the status code is 404" in {
      expectA[NotFoundException](forStatus   = 404)
    }

    "return the correct exception for all other status codes" in {
      forAll(Gen.choose(0, 199))(expectA[Exception](_))
      forAll(Gen.choose(400, 499).suchThat(!Seq(400, 404).contains(_)))(expectA[Upstream4xxResponse](_, Some(500)))
      forAll(Gen.choose(500, 599))(expectA[Upstream5xxResponse](_, Some(502)))
      forAll(Gen.choose(600, 1000))(expectA[Exception](_))
    }
  }

  val exampleVerb = "GET"
  val exampleUrl  = "http://example.com/something"
  val exampleBody = "this is the string body"

  def expectA[T: Manifest](forStatus: Int, reportStatus: Option[Int] = None): Unit = new HttpErrorFunctions {
    val e =
      Try(handleResponse(exampleVerb, exampleUrl)(HttpResponse(forStatus, exampleBody))).failure.exception
    e            should be(a[T])
    e.getMessage should (include(exampleUrl) and include(exampleVerb) and include(exampleBody))
    reportStatus.map { s =>
      e should have('upstreamResponseCode (forStatus))
      e should have('reportAs (s))
    }
  }
} 
Example 70
Source File: WSHttpResponse.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.http.ws

import com.github.ghik.silencer.silent
import play.api.libs.json.JsValue
import play.api.libs.ws.WSResponse
import uk.gov.hmrc.http.HttpResponse

@deprecated("Use WsHttpResponse.apply and HttpResponse instead", "11.0.0")
class WSHttpResponse(wsResponse: WSResponse) extends HttpResponse {

  @silent("deprecated") // allHeaders is required for Play 2.5
  override def allHeaders: Map[String, Seq[String]] = wsResponse.allHeaders

  override def status: Int = wsResponse.status

  override def json: JsValue = wsResponse.json

  override def body: String = wsResponse.body
}

object WSHttpResponse {
  @silent("deprecated") // allHeaders is required for Play 2.5
  def apply(wsResponse: WSResponse): HttpResponse =
    // Note that HttpResponse defines `def json` as `Json.parse(body)` - this may be different from wsResponse.json depending on version.
    // https://github.com/playframework/play-ws/commits/master/play-ws-standalone-json/src/main/scala/play/api/libs/ws/JsonBodyReadables.scala shows that is was redefined
    // to handle an encoding issue, but subsequently reverted.
    HttpResponse(
      status  = wsResponse.status,
      body    = wsResponse.body,
      headers = wsResponse.allHeaders
    )
} 
Example 71
Source File: HttpReads.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent

object HttpReads extends HttpReadsLegacyInstances {
  def apply[A : HttpReads] =
    implicitly[HttpReads[A]]

  def pure[A](a: A) =
    new HttpReads[A] {
      def read(method: String, url: String, response: HttpResponse): A =
        a
    }

  // i.e. HttpReads[A] = Reader[(Method, Url, HttpResponse), A]
  def ask: HttpReads[(String, String, HttpResponse)] =
    new HttpReads[(String, String, HttpResponse)] {
      def read(method: String, url: String, response: HttpResponse): (String, String, HttpResponse) =
        (method, url, response)
    }


  // readRaw is brought in like this rather than in a trait as this gives it
  // compilation priority during implicit resolution. This means, unless
  // specified otherwise a verb call will return a plain HttpResponse
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  @silent("deprecated")
  implicit val readRaw: HttpReads[HttpResponse] = HttpReadsLegacyRawReads.readRaw

  object Implicits extends HttpReadsInstances
}

trait HttpReads[A] {
  outer =>

  def read(method: String, url: String, response: HttpResponse): A

  def map[B](fn: A => B): HttpReads[B] =
    flatMap(a => HttpReads.pure(fn(a)))

  def flatMap[B](fn: A => HttpReads[B]): HttpReads[B] =
    new HttpReads[B] {
      def read(method: String, url: String, response: HttpResponse): B =
        fn(outer.read(method, url, response)).read(method, url, response)
    }
}