cats.effect.ExitCode Scala Examples

The following examples show how to use cats.effect.ExitCode. 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: ClientApp.scala    From fs2-chat   with MIT License 6 votes vote down vote up
package fs2chat
package client

import cats.effect.{Blocker, ExitCode, IO, IOApp}
import cats.implicits._
import com.comcast.ip4s._
import com.monovore.decline._
import fs2.io.tcp.SocketGroup

object ClientApp extends IOApp {
  private val argsParser: Command[(Username, SocketAddress[IpAddress])] =
    Command("fs2chat-client", "FS2 Chat Client") {
      (
        Opts
          .option[String]("username", "Desired username", "u")
          .map(Username.apply),
        Opts
          .option[String]("address", "Address of chat server")
          .withDefault("127.0.0.1")
          .mapValidated(p => IpAddress(p).toValidNel("Invalid IP address")),
        Opts
          .option[Int]("port", "Port of chat server")
          .withDefault(5555)
          .mapValidated(p => Port(p).toValidNel("Invalid port number"))
      ).mapN {
        case (desiredUsername, ip, port) =>
          desiredUsername -> SocketAddress(ip, port)
      }
    }

  def run(args: List[String]): IO[ExitCode] =
    argsParser.parse(args) match {
      case Left(help) => IO(System.err.println(help)).as(ExitCode.Error)
      case Right((desiredUsername, address)) =>
        Blocker[IO]
          .use { blocker =>
            Console[IO](blocker).flatMap { console =>
              SocketGroup[IO](blocker).use { socketGroup =>
                Client
                  .start[IO](console, socketGroup, address, desiredUsername)
                  .compile
                  .drain
              }
            }
          }
          .as(ExitCode.Success)
    }
} 
Example 2
Source File: Math2.scala    From skunk   with MIT License 5 votes vote down vote up
// Copyright (c) 2018-2020 by Rob Norris
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package example

import cats.Monad
import cats.effect.{ ExitCode, IO, IOApp, Resource }
import skunk.Session
import skunk.implicits._
import skunk.codec.numeric.{ int4, float8 }
import natchez.Trace.Implicits.noop

object Math2 extends IOApp {

  val session: Resource[IO, Session[IO]] =
    Session.single(
      host     = "localhost",
      port     = 5432,
      user     = "jimmy",
      database = "world",
      password = Some("banana"),
      debug    = true
    )

  // An algebra for doing math.
  trait Math[F[_]] {
    def add(a: Int, b: Int): F[Int]
    def sqrt(d: Double): F[Double]
  }

  object Math {

    object Statements {
      val add  = sql"select $int4 + $int4".query(int4)
      val sqrt = sql"select sqrt($float8)".query(float8)
    }

    def fromSession[F[_]: Monad](sess: Session[F]): Resource[F, Math[F]] =
      for {
        pAdd  <- sess.prepare(Statements.add)
        pSqrt <- sess.prepare(Statements.sqrt)
      } yield
        new Math[F] {
          def add(a: Int, b: Int) = pAdd.unique(a ~ b)
          def sqrt(d: Double)     = pSqrt.unique(d)
        }

  }

  def run(args: List[String]): IO[ExitCode] =
    session.flatMap(Math.fromSession(_)).use { m =>
      for {
        n  <- m.add(42, 71)
        d  <- m.sqrt(2)
        d2 <- m.sqrt(42)
        _  <- IO(println(s"The answers were $n and $d and $d2"))
      } yield ExitCode.Success
    }

} 
Example 3
Source File: Main.scala    From cats-stm   with Apache License 2.0 5 votes vote down vote up
package io.github.timwspence.cats.stm

import cats.effect.{ExitCode, IO, IOApp}
//import io.github.timwspence.cats.stm.{TVar, STM}
import scala.concurrent.duration._

object Main extends IOApp {

  override def run(args: List[String]): IO[ExitCode] =
    for {
      accountForTim   <- TVar.of[Long](100).commit[IO]
      accountForSteve <- TVar.of[Long](0).commit[IO]
      _               <- printBalances(accountForTim, accountForSteve)
      _               <- giveTimMoreMoney(accountForTim).start
      _               <- transfer(accountForTim, accountForSteve)
      _               <- printBalances(accountForTim, accountForSteve)
    } yield ExitCode.Success

  private def transfer(accountForTim: TVar[Long], accountForSteve: TVar[Long]): IO[Unit] =
    STM.atomically[IO] {
      for {
        balance <- accountForTim.get
        _       <- STM.check(balance > 100)
        _       <- accountForTim.modify(_ - 100)
        _       <- accountForSteve.modify(_ + 100)
      } yield ()
    }

  private def giveTimMoreMoney(accountForTim: TVar[Long]): IO[Unit] =
    for {
      _ <- IO.sleep(5000.millis)
      _ <- STM.atomically[IO](accountForTim.modify(_ + 1))
    } yield ()

  private def printBalances(accountForTim: TVar[Long], accountForSteve: TVar[Long]): IO[Unit] =
    for {
      (amountForTim, amountForSteve) <- STM.atomically[IO](for {
        t <- accountForTim.get
        s <- accountForSteve.get
      } yield (t, s))
      _ <- IO(println(s"Tim: $amountForTim"))
      _ <- IO(println(s"Steve: $amountForSteve"))
    } yield ()

} 
Example 4
Source File: Main.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.cli

import cats.Parallel
import cats.effect.{ContextShift, ExitCode, Timer}
import cats.syntax.all._
import monix.catnap.SchedulerEffect
import monix.eval.{Task, TaskApp}

// $COVERAGE-OFF$
object Main extends TaskApp {

  override def run(args: List[String]): Task[ExitCode] = {
    implicit val cs: ContextShift[Task] = SchedulerEffect.contextShift[Task](scheduler)
    implicit val tm: Timer[Task]        = SchedulerEffect.timer[Task](scheduler)
    implicit val pl: Parallel[Task]     = Task.catsParallel
    Cli(args, sys.env).recoverWith {
      case err: CliError => Task.delay(println(err.show)).as(ExitCode.Error)
    }
  }

} 
Example 5
Source File: Influx.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.cli.modules.influx

import cats.Parallel
import cats.effect.{ConcurrentEffect, ContextShift, ExitCode, Timer}
import cats.implicits._
import ch.epfl.bluebrain.nexus.cli.AbstractCommand
import com.monovore.decline.Opts
import distage.TagK
import izumi.distage.model.recursive.LocatorRef


final class Influx[F[_]: Timer: Parallel: ContextShift: TagK](locatorOpt: Option[LocatorRef])(implicit
    F: ConcurrentEffect[F]
) extends AbstractCommand[F](locatorOpt) {

  def subcommand: Opts[F[ExitCode]] =
    Opts.subcommand("influxdb", "influxDB projection.") {
      run
    }

  def run: Opts[F[ExitCode]] =
    Opts.subcommand("run", "Runs the influxDB projection") {
      locatorResource.map { _.use { locator => locator.get[InfluxProjection[F]].run.as(ExitCode.Success) } }
    }

}

object Influx {

  final def apply[F[_]: TagK: ConcurrentEffect: Timer: Parallel: ContextShift](
      locatorOpt: Option[LocatorRef] = None
  ): Influx[F] =
    new Influx[F](locatorOpt)

} 
Example 6
Source File: Postgres.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.cli.modules.postgres

import cats.Parallel
import cats.effect.{ConcurrentEffect, ContextShift, ExitCode, Timer}
import cats.implicits._
import ch.epfl.bluebrain.nexus.cli.AbstractCommand
import com.monovore.decline.Opts
import distage.TagK
import izumi.distage.model.recursive.LocatorRef


final class Postgres[F[_]: Timer: Parallel: ContextShift: TagK](locatorOpt: Option[LocatorRef])(implicit
    F: ConcurrentEffect[F]
) extends AbstractCommand[F](locatorOpt) {

  def subcommand: Opts[F[ExitCode]] =
    Opts.subcommand("postgres", "Postgres database projection.") {
      run
    }

  def run: Opts[F[ExitCode]] =
    Opts.subcommand("run", "Runs the postgres database projection") {
      locatorResource.map { _.use { locator => locator.get[PostgresProjection[F]].run.as(ExitCode.Success) } }
    }

}

object Postgres {

  final def apply[F[_]: TagK: ConcurrentEffect: Timer: Parallel: ContextShift](
      locatorOpt: Option[LocatorRef] = None
  ): Postgres[F] =
    new Postgres[F](locatorOpt)

} 
Example 7
Source File: Config.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.cli.modules.config

import cats.Parallel
import cats.effect.{ConcurrentEffect, ContextShift, ExitCode, Timer}
import cats.implicits._
import ch.epfl.bluebrain.nexus.cli.config.AppConfig
import ch.epfl.bluebrain.nexus.cli.{AbstractCommand, Console}
import com.monovore.decline.Opts
import com.typesafe.config.ConfigRenderOptions
import distage.TagK
import izumi.distage.model.recursive.LocatorRef
import pureconfig.ConfigWriter


final class Config[F[_]: Timer: Parallel: ContextShift: TagK](locatorOpt: Option[LocatorRef])(implicit
    F: ConcurrentEffect[F]
) extends AbstractCommand[F](locatorOpt) {

  def subcommand: Opts[F[ExitCode]] =
    Opts.subcommand("config", "Read or write the tool configuration.") {
      show
    }

  private def show: Opts[F[ExitCode]] =
    Opts.subcommand("show", "Print the current configuration") {
      locatorResource.map {
        _.use { locator =>
          val console = locator.get[Console[F]]
          val cfg     = locator.get[AppConfig]
          console.println(renderConfig(cfg)).as(ExitCode.Success)
        }
      }
    }

  private def renderConfig(cfg: AppConfig): String = {
    val opts = ConfigRenderOptions.concise().setComments(false).setJson(false).setFormatted(true)
    ConfigWriter[AppConfig].to(cfg).render(opts)
  }
}

object Config {
  final def apply[F[_]: TagK: ConcurrentEffect: Timer: Parallel: ContextShift](
      locatorOpt: Option[LocatorRef] = None
  ): Config[F] =
    new Config[F](locatorOpt)
} 
Example 8
Source File: CliSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.cli

import java.nio.file.{Files, Path}
import java.util.regex.Pattern.quote

import cats.effect.{ExitCode, IO}
import ch.epfl.bluebrain.nexus.cli.config.AppConfig
import ch.epfl.bluebrain.nexus.cli.dummies.TestConsole

class CliSpec extends AbstractCliSpec {

  "A CLI" should {
    "show the default config" in { (cli: Cli[IO], console: TestConsole[IO], cfg: AppConfig) =>
      for {
        code        <- cli.command(assemble("config show"))
        replacements = Map(
                         quote("{postgres-offset-file}") -> cfg.postgres.offsetFile.toString,
                         quote("{influx-offset-file}")   -> cfg.influx.offsetFile.toString
                       )
        expected     = contentOf("cli/config-show.txt", replacements)
        lines       <- console.stdQueue.dequeue1
        _            = lines.trim shouldEqual expected.trim
        _            = code shouldEqual ExitCode.Success
      } yield ()
    }
    "show the default help" in { (cli: Cli[IO], console: TestConsole[IO]) =>
      for {
        code    <- cli.command(assemble("--help"))
        expected = contentOf("cli/help-main.txt")
        lines   <- console.stdQueue.dequeue1
        _        = lines.trim shouldEqual expected.trim
        _        = code shouldEqual ExitCode.Success
      } yield ()
    }
  }

  override def copyConfigs: IO[(Path, Path, Path)] =
    IO {
      val parent       = Files.createTempDirectory(".nexus")
      val envFile      = parent.resolve("env.conf")
      val postgresFile = parent.resolve("postgres.conf")
      val influxFile   = parent.resolve("influx.conf")
      Files.copy(getClass.getClassLoader.getResourceAsStream("env.conf"), envFile)
      Files.copy(getClass.getClassLoader.getResourceAsStream("postgres-noprojects.conf"), postgresFile)
      Files.copy(getClass.getClassLoader.getResourceAsStream("influx-noprojects.conf"), influxFile)
      (envFile, postgresFile, influxFile)
    }

  def assemble(string: String): List[String] =
    string.split(" ").toList

} 
Example 9
Source File: RegressionRun.scala    From Conseil   with Apache License 2.0 5 votes vote down vote up
package tech.cryptonomic.conseil.smoke.tests

import cats.effect.{ExitCode, IO, IOApp}
import tech.cryptonomic.conseil.smoke.tests.suites.RegressionSuite


  override def run(args: List[String]): IO[ExitCode] = {
    val defaultConfigFileName = "conseil-regression-tests.conf"

    val (conf, platform, network) = args match {
      case platform :: network :: configfile :: _ => (configfile, platform, Some(network))
      case platform :: configfile :: Nil => (configfile, platform, None)
      case platform :: Nil => (defaultConfigFileName, platform, None)
    }

    val configPrint = IO(
      println(
        s"Running with configuration from $conf and ${network.fold("no syncing to tezos")(net => "syncing to tezos " + net)}"
      )
    )

    for {
      _ <- configPrint
      probe <- RegressionSuite(conf, platform, network)
      _ <- probe.runRegressionSuite
    } yield ExitCode.Success

  }
} 
Example 10
Source File: ClassBasedRouting.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin.examples

import cats.effect.{ExitCode, IO, IOApp}
import io.odin._
import io.odin.config._


object ClassBasedRouting extends IOApp {
  val logger: Logger[IO] =
    classRouting[IO](
      classOf[Foo[_]] -> consoleLogger[IO]().withMinimalLevel(Level.Warn),
      classOf[Bar[_]] -> consoleLogger[IO]().withMinimalLevel(Level.Info)
    ).withNoopFallback

  def run(args: List[String]): IO[ExitCode] = {
    (Foo(logger).log *> Bar(logger).log).as(ExitCode.Success)
  }
}

case class Foo[F[_]](logger: Logger[F]) {
  def log: F[Unit] = logger.info("foo")
}

case class Bar[F[_]](logger: Logger[F]) {
  def log: F[Unit] = logger.info("bar")
} 
Example 11
Source File: FilteringStackTrace.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin.examples

import cats.effect.{ExitCode, IO, IOApp}
import io.odin._
import io.odin.formatter.Formatter
import io.odin.formatter.options.ThrowableFormat


object FilteringStackTrace extends IOApp {
  val throwableFormat: ThrowableFormat = ThrowableFormat(
    ThrowableFormat.Depth.Fixed(3),
    ThrowableFormat.Indent.NoIndent,
    ThrowableFormat.Filter.Excluding("cats.effect.IOApp", "cats.effect.internals.IOAppPlatform")
  )
  val logger: Logger[IO] = consoleLogger(formatter = Formatter.create(throwableFormat, colorful = true))

  def run(args: List[String]): IO[ExitCode] =
    logger.error("This is an exception", new RuntimeException("here")).as(ExitCode.Success)
} 
Example 12
Source File: EnclosureBasedRouting.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin.examples

import cats.effect.{ExitCode, IO, IOApp}
import io.odin._
import io.odin.config._


object EnclosureBasedRouting extends IOApp {
  val logger: Logger[IO] =
    enclosureRouting(
      "io.odin.examples.EnclosureBasedRouting.foo" -> consoleLogger[IO]().withMinimalLevel(Level.Warn),
      "io.odin.examples.EnclosureBasedRouting.bar" -> consoleLogger[IO]().withMinimalLevel(Level.Info),
      "io.odin.examples" -> consoleLogger[IO]()
    ).withNoopFallback

  def zoo: IO[Unit] = logger.debug("Debug")
  def foo: IO[Unit] = logger.info("Never shown")
  def bar: IO[Unit] = logger.warn("Warning")

  def run(args: List[String]): IO[ExitCode] = {
    (zoo *> foo *> bar).as(ExitCode.Success)
  }
} 
Example 13
Source File: ServerApp.scala    From fs2-chat   with MIT License 5 votes vote down vote up
package fs2chat
package server

import cats.effect.{Blocker, ExitCode, IO, IOApp}
import cats.implicits._
import com.comcast.ip4s._
import com.monovore.decline._
import fs2.io.tcp.SocketGroup
import io.chrisdavenport.log4cats.slf4j.Slf4jLogger

object ServerApp extends IOApp {
  private val argsParser: Command[Port] =
    Command("fs2chat-server", "FS2 Chat Server") {
      Opts
        .option[Int]("port", "Port to bind for connection requests")
        .withDefault(5555)
        .mapValidated(p => Port(p).toValidNel("Invalid port number"))
    }

  def run(args: List[String]): IO[ExitCode] =
    argsParser.parse(args) match {
      case Left(help) => IO(System.err.println(help)).as(ExitCode.Error)
      case Right(port) =>
        Blocker[IO]
          .use { blocker =>
            SocketGroup[IO](blocker).use { socketGroup =>
              Slf4jLogger.create[IO].flatMap { implicit logger =>
                Server.start[IO](socketGroup, port).compile.drain
              }
            }
          }
          .as(ExitCode.Success)
    }
} 
Example 14
Source File: DynamoDBStreamer.scala    From fs2-aws   with MIT License 5 votes vote down vote up
import cats.effect.{ ExitCode, IO, IOApp }
import fs2.aws.dynamodb
import fs2.aws.dynamodb.parsers
import io.chrisdavenport.log4cats.SelfAwareStructuredLogger
import io.chrisdavenport.log4cats.slf4j.Slf4jLogger
import io.circe.Json
import io.github.howardjohn.scanamo.CirceDynamoFormat._

object DynamoDBStreamer extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    for {
      implicit0(logger: SelfAwareStructuredLogger[IO]) <- Slf4jLogger.fromName[IO]("example")
      _ <- dynamodb
            .readFromDynamDBStream[IO](
              "dynamo_db_example",
              "arn:aws:dynamodb:us-east-1:023006903388:table/nightly-sync-events-Production/stream/2020-01-27T22:49:13.204"
            )
            .evalMap(cr => parsers.parseDynamoEvent[IO, Json](cr.record))
            .evalTap(msg => logger.info(s"received $msg"))
            .compile
            .drain
    } yield ExitCode.Success
} 
Example 15
Source File: Commands.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.api.commands

import cats.effect.{ContextShift, ExitCode, IO}
import cats.implicits._
import com.azavea.franklin.crawler.StacImport
import com.monovore.decline._
import doobie.Transactor
import doobie.free.connection.{rollback, setAutoCommit, unit}
import doobie.util.transactor.Strategy
import org.flywaydb.core.Flyway

object Commands {

  final case class RunMigrations(databaseConfig: DatabaseConfig)

  final case class RunServer(apiConfig: ApiConfig, dbConfig: DatabaseConfig)

  final case class RunImport(
      catalogRoot: String,
      config: DatabaseConfig,
      dryRun: Boolean
  )

  private def runImportOpts(implicit cs: ContextShift[IO]): Opts[RunImport] =
    Opts.subcommand("import", "Import a STAC catalog") {
      (
        Options.catalogRoot,
        Options.databaseConfig,
        Options.dryRun
      ).mapN(RunImport)
    }

  private def runMigrationsOpts(implicit cs: ContextShift[IO]): Opts[RunMigrations] =
    Opts.subcommand("migrate", "Runs migrations against database") {
      Options.databaseConfig map RunMigrations
    }

  private def runServerOpts(implicit cs: ContextShift[IO]): Opts[RunServer] =
    Opts.subcommand("serve", "Runs web service") {
      (Options.apiConfig, Options.databaseConfig) mapN RunServer
    }

  def runMigrations(dbConfig: DatabaseConfig): IO[ExitCode] = IO {
    Flyway
      .configure()
      .dataSource(
        s"${dbConfig.jdbcUrl}",
        dbConfig.dbUser,
        dbConfig.dbPass
      )
      .locations("classpath:migrations/")
      .load()
      .migrate()
    ExitCode.Success
  }

  def runImport(
      stacCatalog: String,
      config: DatabaseConfig,
      dryRun: Boolean
  )(
      implicit contextShift: ContextShift[IO]
  ): IO[Unit] = {
    val xa =
      Transactor.strategy.set(
        Transactor.fromDriverManager[IO](
          config.driver,
          config.jdbcUrl,
          config.dbUser,
          config.dbPass
        ),
        if (dryRun) {
          Strategy.default.copy(before = setAutoCommit(false), after = rollback, always = unit)
        } else { Strategy.default }
      )

    new StacImport(stacCatalog).runIO(xa)
  }

  def applicationCommand(implicit cs: ContextShift[IO]): Command[Product] =
    Command("", "Your Friendly Neighborhood OGC API - Features and STAC Web Service") {
      runServerOpts orElse runMigrationsOpts orElse runImportOpts
    }

} 
Example 16
Source File: Math1.scala    From skunk   with MIT License 5 votes vote down vote up
// Copyright (c) 2018-2020 by Rob Norris
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package example

import cats.effect.{ Bracket, ExitCode, IO, IOApp, Resource }
import skunk.Session
import skunk.implicits._
import skunk.codec.numeric.{ int4, float8 }
import natchez.Trace.Implicits.noop

object Math1 extends IOApp {

  val session: Resource[IO, Session[IO]] =
    Session.single(
      host     = "localhost",
      port     = 5432,
      user     = "jimmy",
      database = "world",
      password = Some("banana")
    )

  // An algebra for doing math.
  trait Math[F[_]] {
    def add(a: Int, b: Int): F[Int]
    def sqrt(d: Double): F[Double]
  }

  object Math {

    object Statements {
      val add  = sql"select $int4 + $int4".query(int4)
      val sqrt = sql"select sqrt($float8)".query(float8)
    }

    // `Math` implementation that delegates its work to Postgres.
    def fromSession[F[_]: Bracket[?[_], Throwable]](sess: Session[F]): Math[F] =
      new Math[F] {
        def add(a: Int, b: Int) = sess.prepare(Statements.add).use(_.unique(a ~ b))
        def sqrt(d: Double)     = sess.prepare(Statements.sqrt).use(_.unique(d))
      }

  }

  def run(args: List[String]): IO[ExitCode] =
    session.map(Math.fromSession(_)).use { m =>
      for {
        n  <- m.add(42, 71)
        d  <- m.sqrt(2)
        d2 <- m.sqrt(42)
        _  <- IO(println(s"The answers were $n and $d and $d2"))
      } yield ExitCode.Success
    }

} 
Example 17
Source File: Stryker4sMain.scala    From stryker4s   with Apache License 2.0 5 votes vote down vote up
package stryker4s.command

import pureconfig.error.ConfigReaderException
import stryker4s.command.config.ProcessRunnerConfig
import stryker4s.config.ConfigReader
import stryker4s.run.threshold.ErrorStatus
import pureconfig.generic.auto._
import cats.effect.IOApp
import cats.effect.{ExitCode, IO}

object Stryker4sMain extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    IO {
      Stryker4sArgumentHandler.handleArgs(args)

      val processRunnerConfig: ProcessRunnerConfig =
        ConfigReader.readConfigOfType[ProcessRunnerConfig]() match {
          case Left(failures) => throw ConfigReaderException(failures)
          case Right(config)  => config
        }

      val result = new Stryker4sCommandRunner(processRunnerConfig).run()

      result match {
        case ErrorStatus => ExitCode.Error
        case _           => ExitCode.Success
      }
    }
} 
Example 18
Source File: ECBenchmark.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats.effect.benchmarks

import java.util.concurrent._
import cats.effect.{ExitCode, IO, IOApp, Resource, SyncIO}
import cats.implicits._
import org.openjdk.jmh.annotations._
import scala.concurrent.ExecutionContext

@State(Scope.Thread)
@BenchmarkMode(Array(Mode.Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
class ECBenchmark {
  trait Run { self: IOApp =>
    val size = 100000
    def run(args: List[String]) = {
      def loop(i: Int): IO[Int] =
        if (i < size) IO.shift.flatMap(_ => IO.pure(i + 1)).flatMap(loop)
        else IO.shift.flatMap(_ => IO.pure(i))

      IO(0).flatMap(loop).as(ExitCode.Success)
    }
  }

  private val ioApp = new IOApp with Run
  private val ioAppCtx = new IOApp.WithContext with Run {
    protected def executionContextResource: Resource[SyncIO, ExecutionContext] =
      Resource.liftF(SyncIO.pure(ExecutionContext.Implicits.global))
  }

  @Benchmark
  def app(): Unit = {
    val _ = ioApp.main(Array.empty)
  }

  @Benchmark
  def appWithCtx(): Unit = {
    val _ = ioAppCtx.main(Array.empty)
  }
} 
Example 19
Source File: Http4sMain.scala    From advanced-scala-code   with Apache License 2.0 5 votes vote down vote up
import java.util.UUID

import cats.effect.IO
import scala.util.Try

case class Person(name: String, age: Int)

object Endpoints {
  import org.http4s._
  import org.http4s.dsl.io._

  val helloWorldService = HttpRoutes.of[IO] {
    case GET -> Root / "hello" / IntVar(number) =>
      Ok(s"Hello, your number is $number")
  }

  val asyncRequest = HttpRoutes.of[IO] {
    case GET -> Root / "async" =>
      Ok {
        IO.async[String] { eitherCb =>
          import org.asynchttpclient.Dsl._
          val whenResponse = asyncHttpClient.
            prepareGet("https://httpbin.org/get").execute()
          whenResponse.toCompletableFuture.whenComplete((res, th) => {
            if (th != null) {
              eitherCb(Left(th))
            } else eitherCb(Right(res.getResponseBody))
          })
        }
      }
  }

  val jsonRequest = HttpRoutes.of[IO] {
    case GET -> Root / "json" =>
      import org.http4s.circe._         // EntityEncoder[IO, Json]
      import io.circe.generic.auto._    // automatic codecs for Person
      import io.circe.syntax._          // asJson method
      Ok {
        Person("Joe", 42).asJson
      }
  }

  val idService = HttpRoutes.of[IO] {
    case GET -> Root / "id" / UuidVar(id) =>
      Ok(s"Your ID is $id")
  }

  val timeService = HttpRoutes.of[IO] {
    case GET -> Root / "time" =>
      Ok(System.currentTimeMillis().toString)
  }

  object UuidVar {
    def unapply(s: String): Option[UUID] = {
      Try { UUID.fromString(s) }.toOption
    }
  }
}


import cats.effect.{ExitCode, IO, IOApp}
object Http4sMain extends IOApp {

  import Endpoints._
  import cats.implicits._
  import org.http4s.implicits._
  import org.http4s.server.blaze._
  import org.http4s.server.Router

  val api = helloWorldService <+> timeService <+> idService <+> asyncRequest <+> jsonRequest

  val httpApp = Router("/" -> api).orNotFound

  def run(args: List[String]): IO[ExitCode] =
    BlazeServerBuilder[IO]
      .bindHttp(8080)
      .withHttpApp(httpApp)
      .serve
      .compile
      .drain
      .as(ExitCode.Success)
} 
Example 20
Source File: ExampleMonixInterop.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.interop.monix

import caliban.GraphQL.graphQL
import caliban.ResponseValue.{ ObjectValue, StreamValue }
import caliban.RootResolver
import cats.effect.ExitCode
import monix.eval.{ Task, TaskApp }
import monix.reactive.Observable
import zio.{ Runtime, ZEnv }
import zio.interop.reactivestreams._

object ExampleMonixInterop extends TaskApp {

  import caliban.interop.monix.implicits._

  implicit val runtime: Runtime[ZEnv] = Runtime.default

  case class Number(value: Int)
  case class Queries(numbers: List[Number], randomNumber: Task[Number])
  case class Subscriptions(numbers: Observable[Int])

  val numbers      = List(1, 2, 3, 4).map(Number)
  val randomNumber = Task.eval(scala.util.Random.nextInt()).map(Number)
  val queries      = Queries(numbers, randomNumber)

  val subscriptions = Subscriptions(Observable.fromIterable(List(1, 2, 3)))
  val api           = graphQL(RootResolver(Some(queries), Option.empty[Unit], Some(subscriptions)))

  val query = """
  {
    numbers {
      value
    }

    randomNumber {
      value
    }
  }"""

  val subscription = """
  subscription {
    numbers
  }"""

  override def run(args: List[String]): Task[ExitCode] =
    for {
      interpreter <- api.interpreterAsync
      _           <- interpreter.checkAsync(query)
      result      <- interpreter.executeAsync(query)
      _           <- Task.eval(println(result.data))

      _      <- interpreter.checkAsync(subscription)
      result <- interpreter.executeAsync(subscription)
      _ <- result.data match {
            case ObjectValue(("numbers", StreamValue(stream)) :: Nil) =>
              // get back an observable
              val obs = Observable.fromReactivePublisher(runtime.unsafeRun(stream.toPublisher))
              obs.foreachL(println)
            case _ => Task.eval(println(s"Wrong result: ${result.data}"))
          }
    } yield ExitCode.Success
} 
Example 21
Source File: ExampleCatsInterop.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.interop.cats

import caliban.GraphQL.graphQL
import caliban.RootResolver
import cats.effect.{ ExitCode, IO, IOApp }
import zio.{ Runtime, ZEnv }

object ExampleCatsInterop extends IOApp {

  import caliban.interop.cats.implicits._

  implicit val runtime: Runtime[ZEnv] = Runtime.default

  case class Number(value: Int)

  case class Queries(numbers: List[Number], randomNumber: IO[Number])

  val numbers      = List(1, 2, 3, 4).map(Number)
  val randomNumber = IO(scala.util.Random.nextInt()).map(Number)

  val queries = Queries(numbers, randomNumber)
  val api     = graphQL(RootResolver(queries))

  val query = """
  {
    numbers {
      value
    }

    randomNumber {
      value
    }
  }"""

  override def run(args: List[String]): IO[ExitCode] =
    for {
      interpreter <- api.interpreterAsync[IO]
      _           <- interpreter.checkAsync[IO](query)
      result      <- interpreter.executeAsync[IO](query)
      _           <- IO(println(result.data))
    } yield ExitCode.Success
} 
Example 22
Source File: Server.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.example

import Swagger._
import cats.effect.ExitCode
import cats.effect.concurrent.Ref
import cats.instances.list._
import cats.syntax.foldable._
import cats.syntax.semigroupk._
import com.twitter.finagle
import finagle.{Http, http}
import com.twitter.finagle.http.Response
import com.twitter.util.{Await, Duration}
import monix.eval.{Task, TaskApp}
import ru.tinkoff.tschema.finagle.Runnable
import tofu.Void

object Server extends TaskApp {
  implicit val greeting: Greeting[Example] = Greeting[Example]

  val modules: List[ExampleModule] =
    List(GreetingModule[Example, Http](),
         TestModule,
         FiltersModule,
         FormFieldsModule,
         MultiParameters,
         ProxyModule,
         VersionModule,
         Authorize)

  val svc: Http[Response] = modules.foldMapK(_.route) <+> Swagger.route

  val server = for {
    srv  <- Runnable.run[Example](svc)
    list <- Example.delay(finagle.Http.serve("0.0.0.0:9191", srv))
    _    <- Example.delay(println(s"started at ${list.boundAddress}"))
    _    <- Example.delay(Await.ready(list, Duration.Top)).fork
    res  <- Example.fromTask(Task.never[Void])
  } yield res

  def run(args: List[String]): Task[ExitCode] =
    for {
      ref <- Ref[Task].of(0)
      _ <- server
            .onErrorHandle(ex => println(ex.getMessage))
            .run(ExampleEnv("lol", ref))
    } yield ExitCode.Success
} 
Example 23
Source File: Server.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.example

import cats.effect.ExitCode
import cats.effect.concurrent.Ref
import cats.instances.list._
import cats.syntax.foldable._
import cats.syntax.semigroupk._
import com.twitter.finagle
import com.twitter.finagle.http.Response
import com.twitter.util.{Await, Duration}
import monix.eval.{Task, TaskApp}
import ru.tinkoff.tschema.example.sample.SampleModule
import ru.tinkoff.tschema.finagle.RunHttp
import tofu.Void

object Server extends TaskApp {
  def modules[H[_]]: List[ExampleModule[Http]] =
    List(
      new Greeting[Http, Example](),
      new SampleModule[Http, Example](),
      new FiltersModule(),
      new FormFieldsModule(),
      new MultiParameters(),
      new ProxyModule(),
      new VersionModule(),
      new Authorize
    )

  val svc: Http[Response] = modules.foldMapK(_.route) <+> ExampleSwagger.route

  val server = for {
    srv <- RunHttp.run[Example](svc)
    list <- Example.delay(finagle.Http.serve("0.0.0.0:9191", srv))
    _ <- Example.delay(println(s"started at ${list.boundAddress}"))
    _ <- Example.delay(Await.ready(list, Duration.Top)).fork
    res <- Example.fromTask(Task.never[Void])
  } yield res

  def run(args: List[String]): Task[ExitCode] =
    for {
      ref <- Ref[Task].of(0)
      _ <- server
        .onErrorHandle(ex => println(ex.getMessage))
        .run(ExampleEnv("lol", ref))
    } yield ExitCode.Success
} 
Example 24
Source File: Main.scala    From puretracing   with Apache License 2.0 5 votes vote down vote up
import cats.effect.{ExitCode, IO, IOApp}
import com.softwaremill.sttp._
import com.softwaremill.sttp.asynchttpclient.cats.AsyncHttpClientCatsBackend
import puretracing.cats.instances.ReaderTPropagation
import puretracing.cats.opentracing.OpenTracingTracing
import io.jaegertracing.Configuration, Configuration.SamplerConfiguration, Configuration.ReporterConfiguration
import puretracing.sttp.InstrumentedBackend

object Main extends IOApp {

  override def run(args: List[String]): IO[ExitCode] = {
    val tracer =
      new Configuration("sttp-example")
        .withSampler(SamplerConfiguration.fromEnv().withType("const").withParam(1))
        .withReporter(ReporterConfiguration.fromEnv().withLogSpans(true))
        .getTracer

    val tracing = new ReaderTPropagation(new OpenTracingTracing[IO](tracer))
    import tracing.readerTPropagationInstance
    implicit val backend = InstrumentedBackend[tracing.Effect, Nothing](AsyncHttpClientCatsBackend())

    tracing.runWithRootSpan("main", Map.empty) {  // typically called by an http framework middleware
      sttp
        .body(Map("name" -> "John", "surname" -> "doe"))
        .post(uri"https://httpbin.org/post")
        .send()
        .flatMapF(_.body.fold(
          r => IO(println(r)),
          r => IO(Console.err.println(r))
        ))
        .map(_ => ExitCode.Success)
    }.guarantee(IO(tracer.close())).guarantee(IO(backend.close()))
  }
} 
Example 25
Source File: Example.scala    From puretracing   with Apache License 2.0 5 votes vote down vote up
import cats.effect.{ExitCode, IO, IOApp}
import puretracing.cats.instances.ReaderTPropagation
import puretracing.cats.opentracing.OpenTracingTracing
import io.jaegertracing.Configuration, Configuration.SamplerConfiguration, Configuration.ReporterConfiguration

object Main extends IOApp {
  def run(args: List[String]): IO[ExitCode] = {
    val tracer =
      new Configuration("pure-example")
        .withSampler(SamplerConfiguration.fromEnv().withType("const").withParam(1))
        .withReporter(ReporterConfiguration.fromEnv().withLogSpans(true))
        .getTracer

    val tracing = new ReaderTPropagation(new OpenTracingTracing[IO](tracer))
    import tracing.Effect
    import tracing.readerTPropagationInstance

    val algebra = new FooAlgebra(new BarAlgebra(new BazAlgebra[Effect]), new InstrumentedHttpClient[Effect])
    val app = algebra.foo().flatMap(Console[Effect].println)

    for { // Root span creation is typically job of an http framework middleware. We still need to implement inject and extract headers first
      root <- tracing.tracer.startRootSpan("main", Map.empty)
      _ <- app.run(root).guarantee(for {
        _ <- tracing.tracer.finish(root)
        _ <- IO(tracer.close())
      } yield ())
    } yield ExitCode.Success
  }
} 
Example 26
Source File: InvoicesServer.scala    From event-sourcing-kafka-streams   with MIT License 5 votes vote down vote up
package org.amitayh.invoices.web

import java.util.UUID

import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream
import fs2.concurrent.Topic
import org.amitayh.invoices.common.Config.Topics
import org.amitayh.invoices.common.domain.{Command, CommandResult, InvoiceSnapshot}
import org.amitayh.invoices.dao.{InvoiceList, MySqlInvoiceList}
import org.amitayh.invoices.web.PushEvents._
import org.http4s.implicits._
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder

object InvoicesServer extends IOApp {

  override def run(args: List[String]): IO[ExitCode] =
    stream.compile.drain.as(ExitCode.Success)

  private val stream: Stream[IO, ExitCode] = for {
    invoiceList <- Stream.resource(MySqlInvoiceList.resource[IO])
    producer <- Stream.resource(Kafka.producer[IO, UUID, Command](Topics.Commands))
    commandResultsTopic <- Stream.eval(Topic[IO, CommandResultRecord](None))
    invoiceUpdatesTopic <- Stream.eval(Topic[IO, InvoiceSnapshotRecord](None))
    server <- httpServer(invoiceList, producer, commandResultsTopic, invoiceUpdatesTopic) concurrently
      commandResults.through(commandResultsTopic.publish) concurrently
      invoiceUpdates.through(invoiceUpdatesTopic.publish)
  } yield server

  private def commandResults: Stream[IO, CommandResultRecord] =
    Kafka.subscribe[IO, UUID, CommandResult](
      topic = Topics.CommandResults,
      groupId = "invoices.websocket.command-results").map(Some(_))

  private def invoiceUpdates: Stream[IO, InvoiceSnapshotRecord] =
    Kafka.subscribe[IO, UUID, InvoiceSnapshot](
      topic = Topics.Snapshots,
      groupId = "invoices.websocket.snapshots").map(Some(_))

  private def httpServer(invoiceList: InvoiceList[IO],
                         producer: Kafka.Producer[IO, UUID, Command],
                         commandResultsTopic: Topic[IO, CommandResultRecord],
                         invoiceUpdatesTopic: Topic[IO, InvoiceSnapshotRecord]): Stream[IO, ExitCode] =
    BlazeServerBuilder[IO]
      .bindHttp(8080, "0.0.0.0")
      .withHttpApp(
        Router(
          "/api" -> InvoicesApi[IO].service(invoiceList, producer, commandResultsTopic),
          "/events" -> PushEvents[IO].service(commandResultsTopic, invoiceUpdatesTopic),
          "/" -> Statics[IO].service).orNotFound)
      .serve

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

import cats.effect.{ExitCode, Resource}
import monix.eval.{Task, TaskApp}
import org.slf4j.LoggerFactory


trait MonixResourceApp[A] extends TaskApp {

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

  def program: Resource[Task, A]

  override def run(args: List[String]): Task[ExitCode] = {
    program
      .use(_ => Task.unit)
      .redeem(
        ex => {
          logger.error("Application initialization failed!", ex)
          ExitCode.Error
        },
        _ => ExitCode.Success
      )
  }

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

import cats.effect.{ExitCode, Resource}
import monix.eval.{Task, TaskApp}
import org.http4s.server.Server
import org.slf4j.LoggerFactory


trait MonixServerApp extends TaskApp {

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

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

  override def run(args: List[String]): Task[ExitCode] = {
    program
      .use { server =>
        for {
          _ <- Task.delay(logger.info(s"Server started @ ${server.address.getHostString}:${server.address.getPort}"))
          _ <- Task.never[Unit]
        } yield server
      }
      .redeem(
        ex => {
          logger.error("Server initialization failed!", ex)
          ExitCode.Error
        },
        _ => ExitCode.Success
      )
  }

} 
Example 29
Source File: Recursive.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.Chat
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream


object Recursive extends IOApp {
  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(learnNaturals)
      }
      .compile.drain.as(ExitCode.Success)

  final val FIRST_NATURAL_NUMBER = 0

  def learnNaturals[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("naturals").chat)
      _    <- Scenario.eval(chat.send("Hi. Let's learn what natural numbers are there."))
      _    <- repeat(chat, FIRST_NATURAL_NUMBER)
    } yield ()

  def repeat[F[_]: TelegramClient](chat: Chat, i: Int): Scenario[F, Unit] =
    for {
      _ <- Scenario.eval(chat.send(s"Repeat after me: $i"))
      m <- Scenario.expect(text)
      _ <- if (m == i.toString) Scenario.eval(chat.send("Well done. Let's go to the next one!")) >> repeat(chat, i + 1)
      else Scenario.eval(chat.send("Not even close. You should try again")) >> repeat(chat, i)
    } yield ()
} 
Example 30
Source File: AppMain.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.app

import java.nio.file.Paths

import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._
import jbok.common.log.Logger

object AppMain extends IOApp {
  private[this] val log = Logger[IO]

  private val buildVersion: String = getClass.getPackage.getImplementationVersion

  private val banner: String = """
                         | _____   _______    _____ _           _
                         ||_   _| |__   __|  / ____| |         (_)
                         |  | |  ___ | |    | |    | |__   __ _ _ _ __
                         |  | | / _ \| |    | |    | '_ \ / _` | | '_ \
                         | _| || (_) | |    | |____| | | | (_| | | | | |
                         ||_____\___/|_|     \_____|_| |_|\__,_|_|_| |_|
                         |""".stripMargin

  private val version = s"v${buildVersion} © 2018 - 2019 The IoTChain Authors"

  override def run(args: List[String]): IO[ExitCode] =
    log.i(banner) >>
      log.i(version) >>
      AppModule
        .resource[IO](Paths.get(args.headOption.getOrElse("/etc/iotchain/config.yaml")))
        .use(_.get[FullNode[IO]].stream.compile.drain)
        .as(ExitCode.Success)
} 
Example 31
Source File: CliMain.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.app

import java.nio.file.Paths

import cats.effect.{ExitCode, IO, IOApp}
import javax.net.ssl.SSLContext
import jbok.app.cli.Cli
import jbok.common.config.Config
import jbok.common.log.{Level, Logger}
import jbok.core.api.JbokClientPlatform
import jbok.core.config.FullConfig
import monocle.macros.syntax.lens._

import scala.concurrent.duration._

object CliMain extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    Config[IO].read[FullConfig](Paths.get(args.head)).flatMap { config =>
      AppModule.resource[IO](config.lens(_.persist.driver).set("memory")).use { objects =>
        val config = objects.get[FullConfig]
        val ssl    = objects.get[Option[SSLContext]]
        JbokClientPlatform.resource[IO](config.service.uri, ssl).use { client =>
          val cli = new Cli[IO](client)
          for {
            _ <- Logger.setRootLevel[IO](Level.Error)
            _ <- cli.loop(5.seconds).compile.drain
          } yield ExitCode.Success
        }
      }
    }
} 
Example 32
Source File: TxGeneratorMain.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.app

import java.nio.file.Paths

import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._
import jbok.app.txgen.TxGenerator
import jbok.common.config.Config
import jbok.core.api.JbokClientPlatform
import jbok.core.config.FullConfig
import jbok.core.mining.TxGen
import jbok.crypto.signature.{ECDSA, KeyPair, Signature}
import monocle.macros.syntax.lens._

object TxGeneratorMain extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    Config[IO].read[FullConfig](Paths.get(args.head)).flatMap { config =>
      AppModule.resource[IO](config.lens(_.persist.driver).set("memory")).use { objects =>
        val config           = objects.get[FullConfig]
        implicit val chainId = config.genesis.chainId
        val keyPairs: List[KeyPair] = List(
          KeyPair(
            KeyPair.Public("a4991b82cb3f6b2818ce8fedc00ef919ba505bf9e67d96439b63937d24e4d19d509dd07ac95949e815b307769f4e4d6c3ed5d6bd4883af23cb679b251468a8bc"),
            KeyPair.Secret("1a3c21bb6e303a384154a56a882f5b760a2d166161f6ccff15fc70e147161788")
          )
        ) ++ Signature[ECDSA].generateKeyPair[IO]().replicateA(10).unsafeRunSync()

        JbokClientPlatform.resource[IO](config.service.uri).use { client =>
          for {
            txGen <- TxGen[IO](keyPairs, client)
            generator = new TxGenerator[IO](config, txGen, client)
            _ <- generator.stream.compile.drain
          } yield ExitCode.Success
        }
      }
    }
} 
Example 33
Source File: RocksKVStoreSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.persistent

import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._
import fs2._
import jbok.common.CommonArb._
import jbok.common.testkit._
import jbok.persistent.testkit._

object RocksKVStoreSpec extends IOApp {
  override def run(args: List[String]): IO[ExitCode] =
    testRocksKVStore().use { store =>
      // if we do not close the batch object after each writeBatch, we will get RocksDBException: unknown WriteBatch tag
      val kvs = Stream.repeatEval(IO(List.fill(100)(random[Array[Byte]])))
      val s = kvs
        .map { xs =>
          Stream.eval(store.writeBatch(ColumnFamily.default, xs.map(x => x -> x), Nil))
        }
        .parJoin(8)

      s.compile.drain.as(ExitCode.Success)
    }
} 
Example 34
Source File: JbokClientSpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.core.api

import cats.effect.{ExitCode, IO, IOApp}
import jbok.common.log.{Level, Logger}

object JbokClientSpec extends IOApp {
  Logger.setRootHandlers[IO](Logger.consoleHandler(minimumLevel = Some(Level.Info))).unsafeRunSync()

  override def run(args: List[String]): IO[ExitCode] = {
    val url = "http://localhost:30315"
    JbokClientPlatform.resource[IO](url, None).use { client =>
      for {
        _ <- client.personal.newAccount("")
        accounts <- client.personal.listAccounts
      } yield ExitCode.Success
    }
  }
} 
Example 35
Source File: StreamingProducerApp.scala    From Scala-Programming-Projects   with MIT License 5 votes vote down vote up
package coinyser

import cats.effect.{ExitCode, IO, IOApp}
import com.pusher.client.Pusher
import StreamingProducer._
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import scala.collection.JavaConversions._

object StreamingProducerApp extends IOApp {
  val topic = "transactions"

  val pusher = new Pusher("de504dc5763aeef9ff52")

  val props = Map(
    "bootstrap.servers" -> "localhost:9092",
    "key.serializer" -> "org.apache.kafka.common.serialization.IntegerSerializer",
    "value.serializer" -> "org.apache.kafka.common.serialization.StringSerializer")

  def run(args: List[String]): IO[ExitCode] = {
    val kafkaProducer = new KafkaProducer[Int, String](props)

    subscribe(pusher) { wsTx =>
      val tx = convertWsTransaction(deserializeWebsocketTransaction(wsTx))
      val jsonTx = serializeTransaction(tx)
      kafkaProducer.send(new ProducerRecord(topic, tx.tid, jsonTx))
    }.flatMap(_ => IO.never)
  }
} 
Example 36
Source File: Metadata.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala

import java.nio.file.Paths
import java.nio.file.StandardOpenOption

import cats.data.NonEmptyChain
import cats.effect.Blocker
import cats.effect.ExitCode
import cats.effect.IO
import cats.effect.IOApp
import cats.instances.string._
import com.mwz.sonar.scala.metadata._
import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRules
import com.mwz.sonar.scala.metadata.scalastyle.ScalastyleRulesRepository
import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRules
import com.mwz.sonar.scala.metadata.scapegoat.ScapegoatRulesRepository
import fs2.Stream
import fs2.io.file._
import fs2.text
import io.circe.Printer
import io.circe.generic.JsonCodec
import io.circe.syntax._

@JsonCodec
final case class SonarScalaMetadata(
  rules: Rules,
  repositories: Map[String, RulesRepository]
)

@JsonCodec
final case class Rules(
  scalastyle: NonEmptyChain[Rule],
  scapegoat: NonEmptyChain[Rule]
)

object Metadata extends IOApp {
  private val metadata: SonarScalaMetadata =
    SonarScalaMetadata(
      rules = Rules(sort(ScalastyleRules.rules), sort(ScapegoatRules.rules)),
      repositories = Map(
        ScalastyleRulesRepository.RepositoryKey ->
        ScalastyleRulesRepository.rulesRepository
          .copy(rules = sort(ScalastyleRulesRepository.rulesRepository.rules)),
        ScapegoatRulesRepository.RepositoryKey ->
        ScapegoatRulesRepository.rulesRepository
          .copy(rules = sort(ScapegoatRulesRepository.rulesRepository.rules))
      )
    )
  private val printer: Printer =
    Printer.spaces2SortKeys.copy(
      colonLeft = "",
      lbraceLeft = "",
      rbraceRight = "",
      lbracketLeft = "",
      lrbracketsEmpty = "",
      rbracketRight = "",
      arrayCommaLeft = "",
      objectCommaLeft = ""
    )

  // Chain is missing sortBy, which should be added in 2.2.0.
  private def sort(rules: NonEmptyChain[Rule]): NonEmptyChain[Rule] =
    NonEmptyChain.fromNonEmptyList(rules.toNonEmptyList.sortBy(_.name))

  def run(args: List[String]): IO[ExitCode] = {
    val write: Stream[IO, Unit] = Stream.resource(Blocker[IO]).flatMap { blocker =>
      Stream[IO, String](metadata.asJson.printWith(printer))
        .through(text.utf8Encode)
        .through(
          writeAll(
            Paths.get("sonar-scala-metadata.json"),
            blocker,
            List(StandardOpenOption.TRUNCATE_EXISTING)
          )
        )
    }
    write.compile.drain.as(ExitCode.Success)
  }
} 
Example 37
Source File: Server.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package com.example.server

import java.net.{ InetSocketAddress, InetAddress }
import java.nio.channels.AsynchronousChannelGroup
import java.util.concurrent.Executors

import scala.concurrent.duration._

import cats.implicits._
import cats.effect.{ IO, IOApp, ExitCode, Resource, Blocker }

import fs2.{ Stream, Chunk }
import fs2.io.tcp

import scodec.bits.BitVector
import scodec.Codec

import dev.tauri.seals.scodec.Codecs._

import com.example.proto._

object Server extends IOApp {

  final val bufferSize = 32 * 1024
  final val timeout = Some(2.seconds)
  final val maxClients = 200
  final val port = 8080

  val rnd = new scala.util.Random

  def addr(port: Int): InetSocketAddress =
    new InetSocketAddress(InetAddress.getLoopbackAddress, port)

  override def run(args: List[String]): IO[ExitCode] = {
    Blocker[IO].use { bl =>
      tcp.SocketGroup[IO](bl).use { sg =>
        serve(port, sg).compile.drain.as(ExitCode.Success)
      }
    }
  }

  def serve(port: Int, sg: tcp.SocketGroup): Stream[IO, Unit] = {
    Stream.resource(sg.serverResource[IO](addr(port))).flatMap {
      case (localAddr, sockets) =>
        val s = sockets.map { socket =>
          Stream.resource(socket).flatMap { socket =>
            val bvs: Stream[IO, BitVector] = socket.reads(bufferSize, timeout).chunks.map(ch => BitVector.view(ch.toArray))
            val tsk: IO[BitVector] = bvs.compile.toVector.map(_.foldLeft(BitVector.empty)(_ ++ _))
            val request: IO[Request] = tsk.flatMap { bv =>
              Codec[Request].decode(bv).fold(
                err => IO.raiseError(new Exception(err.toString)),
                result => IO.pure(result.value)
              )
            }
            val response: IO[Response] = request.flatMap(logic)
            val encoded: Stream[IO, Byte] = Stream.eval(response)
              .map(r => Codec[Response].encode(r).require)
              .flatMap { bv => Stream.chunk(Chunk.bytes(bv.bytes.toArray)) }
            encoded.through(socket.writes(timeout)).onFinalize(socket.endOfOutput)
          }
        }
        s.parJoin[IO, Unit](maxClients)
    }
  }

  def logic(req: Request): IO[Response] = req match {
    case RandomNumber(min, max) =>
      if (min < max) {
        IO {
          val v = rnd.nextInt(max - min + 1) + min
          Number(v)
        }
      } else if (min === max) {
        IO.pure(Number(min))
      } else {
        IO.raiseError(new IllegalArgumentException("min must not be greater than max"))
      }
    case ReSeed(s) =>
      IO {
        rnd.setSeed(s)
        Ok
      }
  }
} 
Example 38
Source File: Server.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package com.example.lib

import java.net.{ InetSocketAddress, InetAddress }

import scala.concurrent.duration._

import cats.implicits._
import cats.effect.{ IO, IOApp, ExitCode, Blocker }

import fs2.{ Stream, Chunk }
import fs2.io.tcp

import scodec.bits.BitVector
import scodec.stream.{ StreamEncoder, StreamDecoder }

import dev.tauri.seals.scodec.StreamCodecs._
import dev.tauri.seals.scodec.StreamCodecs.{ pipe => decPipe }

import Protocol.v1.{ Request, Response, Random, Seed, RandInt, Seeded }

object Server extends IOApp {

  final val bufferSize = 32 * 1024
  final val timeout = Some(2.seconds)
  final val maxClients = 200

  val rnd = new scala.util.Random

  def addr(port: Int): InetSocketAddress =
    new InetSocketAddress(InetAddress.getLoopbackAddress, port)

  val reqCodec: StreamDecoder[Request] = streamDecoderFromReified[Request]
  val resCodec: StreamEncoder[Response] = streamEncoderFromReified[Response]

  override def run(args: List[String]): IO[ExitCode] = {
    Blocker[IO].use { bl =>
      tcp.SocketGroup[IO](bl).use { sg =>
        serve(1234, sg).compile.drain.as(ExitCode.Success)
      }
    }
  }

  def serve(port: Int, sg: tcp.SocketGroup): Stream[IO, Unit] =
    serveAddr(port, sg).as(())

  def serveAddr(port: Int, sg: tcp.SocketGroup): Stream[IO, InetSocketAddress] = {
    Stream.resource(sg.serverResource[IO](addr(port))).flatMap {
      case (localAddr, sockets) =>
        val x = sockets.flatMap { socket =>
          Stream.resource(socket).map { socket =>
            val bvs: Stream[IO, BitVector] = socket.reads(bufferSize, timeout).chunks.map(ch => BitVector.view(ch.toArray))
            val requests: Stream[IO, Request] = bvs.through(decPipe[IO, Request])
            val responses: Stream[IO, Response] = requests.flatMap(req => Stream.eval(logic(req)))
            val encoded: Stream[IO, Byte] = resCodec.encode(responses).flatMap { bv =>
              Stream.chunk(Chunk.bytes(bv.bytes.toArray))
            }

            encoded.through(socket.writes(timeout)).onFinalize(socket.endOfOutput)
          }
        }

        Stream.emit(localAddr) ++ x.parJoin(maxClients).drain
    }
  }

  def logic(req: Request): IO[Response] = req match {
    case Random(min, max) =>
      if (min < max) {
        IO {
          val v = rnd.nextInt(max - min + 1) + min
          RandInt(v)
        }
      } else if (min === max) {
        IO.pure(RandInt(min))
      } else {
        IO.raiseError(new IllegalArgumentException("min must not be greater than max"))
      }
    case Seed(s) =>
      IO {
        rnd.setSeed(s)
        Seeded
      }
  }
} 
Example 39
Source File: main.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package com.example.messaging

import scala.concurrent.ExecutionContext.Implicits.global

import cats.implicits._
import cats.effect.{ IO, IOApp, ExitCode }

import org.http4s._
import org.http4s.dsl.io._
import org.http4s.client.Client
import org.http4s.circe._
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.server.Router
import org.http4s.implicits._

import dev.tauri.seals._
import dev.tauri.seals.circe.Codecs._

object Protocol {
  final case class Ping(seqNr: Long, payload: Vector[Int])
  final case class Pong(seqNr: Long)
  final case class PingIncompatible(seqNr: Long, payload: Vector[Int], flags: Int)
}

object MyClient extends IOApp {

  import org.http4s.client.blaze._
  import Protocol._

  override def run(args: List[String]): IO[ExitCode] = {
    BlazeClientBuilder[IO](global).resource.use { client =>
      for {
        pongGood <- ping(client, jsonEncoderOf[IO, Envelope[Ping]].toEntity(
          Envelope(Ping(42L, Vector(1, 2, 3, 4)))
        ))
        _ <- IO { assert(pongGood == Pong(42L)) }
        _ <- IO { println(pongGood) }
        pongBad <- ping(client, jsonEncoderOf[IO, Envelope[PingIncompatible]].toEntity(
          Envelope(PingIncompatible(99L, Vector(4, 5), 0))
        ))
        _ <- IO { println(pongBad) }
      } yield ExitCode.Success
    }
  }

  def ping(client: Client[IO], ping: Entity[IO]): IO[Pong] = {
    for {
      pong <- client
        .expect(Request(
          POST,
          Uri(authority = Some(Uri.Authority(port = Some(1234))), path = "/test"),
          body = ping.body
        ))(jsonOf[IO, Envelope[Pong]])
    } yield pong.value
  }
}

object MyServer extends IOApp {

  import org.http4s.server.blaze._
  import Protocol._

  val service = HttpRoutes.of[IO] {
    case p @ POST -> Root / "test" =>
      for {
        env <- p.as(implicitly, jsonOf[IO, Envelope[Ping]])
        resp <- Ok(Envelope(Pong(env.value.seqNr)))(implicitly, jsonEncoderOf)
      } yield resp
  }

  override def run(args: List[String]): IO[ExitCode] = {
    BlazeServerBuilder[IO]
      .bindHttp(1234, "localhost")
      .withHttpApp(Router("/" -> service).orNotFound)
      .serve
      .compile
      .drain
      .as(ExitCode.Success)
  }
} 
Example 40
Source File: Main.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package com.example.streaming

import java.io.{ InputStream, OutputStream, FileInputStream, FileOutputStream }

import cats.implicits._
import cats.effect.{ IO, IOApp, Blocker, ExitCode }

import fs2.{ Stream, Chunk, Pure }

import dev.tauri.seals.scodec.StreamCodecs._

object Main extends IOApp {

  sealed trait Color
  final case object Brown extends Color
  final case object Grey extends Color

  sealed trait Animal
  final case class Elephant(name: String, tuskLength: Float) extends Animal
  final case class Quokka(name: String, color: Color = Brown) extends Animal
  final case class Quagga(name: String, speed: Double) extends Animal

  def transform(from: InputStream, to: OutputStream)(f: Animal => Stream[Pure, Animal]): IO[Unit] = {
    Blocker[IO].use { blocker =>
      val input = fs2.io.readInputStream(
        IO.pure(from),
        chunkSize = 1024,
        blocker = blocker
      )
      val sIn: Stream[IO, Animal] = input.through(streamDecoderFromReified[Animal].toPipeByte[IO]).flatMap(f)
      val sOut: Stream[IO, Unit] = streamEncoderFromReified[Animal].encode(sIn).flatMap { bv =>
        Stream.chunk(Chunk.bytes(bv.bytes.toArray))
      }.through(fs2.io.writeOutputStream(
        IO.pure(to),
        blocker = blocker,
        closeAfterUse = true
      ))
      sOut.compile.drain
    }
  }

  val transformer: Animal => Stream[Pure, Animal] = {
    case Elephant(n, tl) => Stream(Elephant(n, tl + 17))
    case Quokka(n, Brown) => Stream(Quokka(n, Grey))
    case q @ Quokka(_, _) => Stream(q)
    case Quagga(_, _) => Stream.empty
  }

  override def run(args: List[String]): IO[ExitCode] = {
    val (from, to) = args match {
      case List(from, to, _*) =>
        (from, to)
      case List(from) =>
        (from, "out.bin")
      case _ =>
        ("in.bin", "out.bin")
    }

    val task = transform(new FileInputStream(from), new FileOutputStream(to))(transformer)
    task.as(ExitCode.Success)
  }
} 
Example 41
Source File: TimerAlarm.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.syntax._
import canoe.models.messages.TextMessage
import cats.effect.{ExitCode, IO, IOApp, Timer}
import cats.syntax.functor._
import fs2.Stream

import scala.util.Try
import scala.concurrent.duration._


object TimerAlarm extends IOApp {
  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client => Bot.polling[IO].follow(alarm) }
      .compile.drain.as(ExitCode.Success)

  def alarm[F[_]: TelegramClient: Timer]: Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("alarm").chat)
      _    <- Scenario.eval(chat.send("Tell me in how many seconds you want to be notified?"))
      in   <- Scenario.expect(textMessage)
      sec = Try(in.text.toInt).toOption.filter(_ > 0)
      _ <- sec match {
        case Some(i) => setTimer(in, i)
        case None    => Scenario.eval(in.reply("I'm sorry, but I couldn't get that (expecting positive number)"))
      }
    } yield ()

  def setTimer[F[_]: TelegramClient: Timer](m: TextMessage, i: Int): Scenario[F, Unit] =
    for {
      _ <- Scenario.eval(m.chat.send(s"Timer is set. You will receive a reply after $i seconds"))
      _ <- Scenario.eval(Timer[F].sleep(i.seconds))
      _ <- Scenario.eval(m.reply("Time's up."))
    } yield ()
} 
Example 42
Source File: CustomExtractor.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.messages.UserMessage
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream

object CustomExtractor extends IOApp {
  val token: String = "<your telegram token>"
  val userIdToGreet: Int = -1

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(greetParticularUser(userIdToGreet))
      }
      .compile
      .drain
      .as(ExitCode.Success)

  def greetParticularUser[F[_]: TelegramClient](userId: Int): Scenario[F, Unit] =
    for {
      msg <- Scenario.expect(particularUsersMessages(userId))
      _   <- Scenario.eval(msg.chat.send(s"I was waiting for you ${name(msg)}"))
    } yield ()

  def particularUsersMessages(userId: Int): Expect[UserMessage] = {
    case m: UserMessage if m.from.map(_.id).contains(userId) => m
  }

  def name(msg: UserMessage): String = msg.from.map(_.firstName).getOrElse("unknown")
} 
Example 43
Source File: NetworkBuilderMain.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.app

import java.nio.file.Paths

import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._
import jbok.common.math.N
import jbok.core.CoreModule
import jbok.core.config.{GenesisBuilder, NetworkBuilder}
import jbok.core.models.{Address, ChainId}
import jbok.crypto.signature.{ECDSA, KeyPair, Signature}

object NetworkBuilderMain extends IOApp {
  override def run(args: List[String]): IO[ExitCode] = {
    def randomKP: KeyPair =
      Signature[ECDSA].generateKeyPair[IO]().unsafeRunSync()

    val miner0 = randomKP
    val miner1 = randomKP
    val miner2 = randomKP

    val coinbase0 = Address(randomKP)
    val coinbase1 = Address(randomKP)
    val coinbase2 = Address(randomKP)

    val alloc = KeyPair(
      KeyPair.Public("a4991b82cb3f6b2818ce8fedc00ef919ba505bf9e67d96439b63937d24e4d19d509dd07ac95949e815b307769f4e4d6c3ed5d6bd4883af23cb679b251468a8bc"),
      KeyPair.Secret("1a3c21bb6e303a384154a56a882f5b760a2d166161f6ccff15fc70e147161788")
    )

    val genesis = GenesisBuilder()
      .withChainId(ChainId(10))
      .addAlloc(Address(alloc), N("1" + "0" * 27))
      .addAlloc(Address(miner0), N("1" + "0" * 27))
      .addMiner(Address(miner0))
//      .addMiner(Address(miner1))
//      .addMiner(Address(miner2))
      .build

    val config = CoreModule.testConfig.copy(genesis = genesis)

    val home = System.getProperty("user.home")
    val root = Paths.get(home).resolve(".iotchain")

    val builder = NetworkBuilder(config)
      .withBlockPeriod(10000)
      .addNode(miner0, coinbase0, root.resolve("node-0"), "127.0.0.2")
      .addNode(miner1, coinbase1, root.resolve("node-1"), "127.0.0.3")
      .addNode(miner2, coinbase2, root.resolve("node-2"), "127.0.0.4")

    builder.dump.as(ExitCode.Success)
  }
} 
Example 44
Source File: Greetings.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream


object Greetings extends IOApp {

  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client => Bot.polling[IO].follow(greetings) }
      .compile.drain.as(ExitCode.Success)

  def greetings[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("hi").chat)
      _    <- Scenario.eval(chat.send("Hello. What's your name?"))
      name <- Scenario.expect(text)
      _    <- Scenario.eval(chat.send(s"Nice to meet you, $name"))
    } yield ()
} 
Example 45
Source File: ConcurrentScenarios.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.syntax._
import cats.effect.concurrent.Semaphore
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.all._
import fs2.Stream


object ConcurrentScenarios extends IOApp {

  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Stream.eval(Semaphore[IO](0)).flatMap { sem =>
          // Both scenarios use shared semaphore
          // to achieve the interaction across different chats.
          Bot.polling[IO].follow(pop(sem), push(sem))
        }
      }
      .compile.drain.as(ExitCode.Success)

  def pop[F[_]: TelegramClient](semaphore: Semaphore[F]): Scenario[F, Unit] =
    for {
      m <- Scenario.expect(command("pop"))
      _ <- Scenario.eval(m.chat.send("Waiting for available elements.."))
      _ <- Scenario.eval(semaphore.acquire)
      _ <- Scenario.eval(m.reply("Done."))
    } yield ()

  def push[F[_]: TelegramClient](semaphore: Semaphore[F]): Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("push").chat)
      _    <- Scenario.eval(semaphore.release)
      _    <- Scenario.eval(chat.send("Pushed one element."))
    } yield ()
} 
Example 46
Source File: Webhook.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.all._
import fs2.Stream


  val url: String = "<your server url>"

  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Stream.resource(Bot.hook[IO](url)).flatMap(_.follow(greetings))
      }
      .compile.drain.as(ExitCode.Success)

  def greetings[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("hi").chat)
      _    <- Scenario.eval(chat.send("Hello. What's your name?"))
      name <- Scenario.expect(text)
      _    <- Scenario.eval(chat.send(s"Nice to meet you, $name"))
    } yield ()
} 
Example 47
Source File: SemanticBlocking.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.Chat
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp, Timer}
import cats.syntax.functor._
import fs2.Stream

import scala.concurrent.duration._
import scala.util.Try


object SemanticBlocking extends IOApp {

  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(count)
      }
      .compile.drain.as(ExitCode.Success)

  def count[F[_]: TelegramClient: Timer]: Scenario[F, Unit] =
    for {
      m <- Scenario.expect(command("count"))
      start = Try(m.text.split(" ")(1).toInt).getOrElse(10)
      _ <- repeat(m.chat, start)
    } yield ()

  def repeat[F[_]: TelegramClient: Timer](chat: Chat, i: Int): Scenario[F, Unit] =
    if (i <= 0) Scenario.eval(chat.send("Done.")).void
    else
      for {
        _ <- Scenario.eval(chat.send(s"$i.."))
        _ <- Scenario.eval(Timer[F].sleep(1.second))
        _ <- repeat(chat, i - 1)
      } yield ()
} 
Example 48
Source File: NoScenario.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.InlineQuery
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream


object NoScenario extends IOApp {

  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].updates.through(pipes.inlineQueries).evalTap(answerInlineQuery(_).void)
      }
      .compile.drain.as(ExitCode.Success)

  def answerInlineQuery[F[_]: TelegramClient](query: InlineQuery): F[Boolean] =
    query.answer(results = List())
} 
Example 49
Source File: Registration.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.Chat
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream


object Registration extends IOApp {

  val token: String = "<your telegram token>"

  trait Service[F[_]] {
    def userExists(username: String): F[Boolean]

    def register(username: String, password: String): F[User]
  }

  trait User {
    def name: String
  }

  val service: Service[IO] = ???

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(signup(service))
      }
      .compile.drain.as(ExitCode.Success)

  def signup[F[_]: TelegramClient](service: Service[F]): Scenario[F, Unit] =
    for {
      chat <- Scenario.expect(command("signup").chat)
      user <- registerUser(chat, service).stopOn(command("cancel").isDefinedAt)
      _    <- Scenario.eval(chat.send(s"Registration completed. Welcome, ${user.name}"))
    } yield ()

  def registerUser[F[_]: TelegramClient](chat: Chat, service: Service[F]): Scenario[F, User] =
    for {
      name <- provideUsername(chat, service)
      pass <- providePass(chat)
      user <- Scenario.eval(service.register(name, pass))
    } yield user

  def provideUsername[F[_]: TelegramClient](chat: Chat, service: Service[F]): Scenario[F, String] =
    for {
      _      <- Scenario.eval(chat.send("Enter your nickname"))
      nick   <- Scenario.expect(text)
      exists <- Scenario.eval(service.userExists(nick))
      res <-
        if (exists)
          Scenario.eval(chat.send("User with such nick already exists. Please try another one")) >>
            provideUsername(chat, service)
        else Scenario.pure[F](nick)
    } yield res

  def providePass[F[_]: TelegramClient](chat: Chat): Scenario[F, String] =
    for {
      _         <- Scenario.eval(chat.send("Enter your password (after you send the message it will be deleted)"))
      pass      <- enterPass(chat)
      _         <- Scenario.eval(chat.send("Repeat your password"))
      reentered <- enterPass(chat)
      r <-
        if (pass == reentered) Scenario.eval(chat.send("Your password is stored.")).as(pass)
        else Scenario.eval(chat.send("Provided passwords don't match. Try again")) >> providePass(chat)
    } yield r

  def enterPass[F[_]: TelegramClient](chat: Chat): Scenario[F, String] =
    for {
      passwordMessage <- Scenario.expect(textMessage)
      _               <- Scenario.eval(passwordMessage.delete)
    } yield passwordMessage.text

} 
Example 50
Source File: Echo.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.messages.{AnimationMessage, StickerMessage, TelegramMessage, TextMessage}
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import cats.syntax.functor._
import fs2.Stream


object Echo extends IOApp {
  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(echos)
      }
      .compile
      .drain
      .as(ExitCode.Success)

  def echos[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      msg <- Scenario.expect(any)
      _   <- Scenario.eval(echoBack(msg))
    } yield ()

  def echoBack[F[_]: TelegramClient](msg: TelegramMessage): F[_] = msg match {
    case textMessage: TextMessage           => msg.chat.send(textMessage.text)
    case animationMessage: AnimationMessage => msg.chat.send(animationMessage.animation)
    case stickerMessage: StickerMessage     => msg.chat.send(stickerMessage.sticker)
    case _                                  => msg.chat.send("Sorry! I can't echos that back.")
  }
} 
Example 51
Source File: DiceExample.scala    From canoe   with MIT License 5 votes vote down vote up
package samples

import canoe.api._
import canoe.models.{Darts, Dice}
import canoe.syntax._
import cats.effect.{ExitCode, IO, IOApp}
import fs2.Stream


object DiceExample extends IOApp {
  val token: String = "<your telegram token>"

  def run(args: List[String]): IO[ExitCode] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot.polling[IO].follow(echos)
      }
      .compile
      .drain
      .as(ExitCode.Success)

  def echos[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      msg <- Scenario.expect(any)
      _   <- Scenario.eval(msg.chat.send(Dice))
      _   <- Scenario.eval(msg.chat.send(Darts))
    } yield ()

} 
Example 52
Source File: StewardAlg.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.application

import better.files.File
import cats.Monad
import cats.effect.ExitCode
import cats.implicits._
import fs2.Stream
import io.chrisdavenport.log4cats.Logger
import org.scalasteward.core.buildtool.sbt.SbtAlg
import org.scalasteward.core.git.GitAlg
import org.scalasteward.core.io.{FileAlg, WorkspaceAlg}
import org.scalasteward.core.nurture.NurtureAlg
import org.scalasteward.core.repocache.RepoCacheAlg
import org.scalasteward.core.update.PruningAlg
import org.scalasteward.core.util
import org.scalasteward.core.util.DateTimeAlg
import org.scalasteward.core.util.logger.LoggerOps
import org.scalasteward.core.vcs.data.Repo

final class StewardAlg[F[_]](implicit
    config: Config,
    dateTimeAlg: DateTimeAlg[F],
    fileAlg: FileAlg[F],
    gitAlg: GitAlg[F],
    logger: Logger[F],
    nurtureAlg: NurtureAlg[F],
    pruningAlg: PruningAlg[F],
    repoCacheAlg: RepoCacheAlg[F],
    sbtAlg: SbtAlg[F],
    selfCheckAlg: SelfCheckAlg[F],
    streamCompiler: Stream.Compiler[F, F],
    workspaceAlg: WorkspaceAlg[F],
    F: Monad[F]
) {
  private def printBanner: F[Unit] = {
    val banner =
      """|  ____            _         ____  _                             _
         | / ___|  ___ __ _| | __ _  / ___|| |_ _____      ____ _ _ __ __| |
         | \___ \ / __/ _` | |/ _` | \___ \| __/ _ \ \ /\ / / _` | '__/ _` |
         |  ___) | (_| (_| | | (_| |  ___) | ||  __/\ V  V / (_| | | | (_| |
         | |____/ \___\__,_|_|\__,_| |____/ \__\___| \_/\_/ \__,_|_|  \__,_|""".stripMargin
    val msg = List(" ", banner, s" v${org.scalasteward.core.BuildInfo.version}", " ")
      .mkString(System.lineSeparator())
    logger.info(msg)
  }

  private def readRepos(reposFile: File): F[List[Repo]] =
    fileAlg.readFile(reposFile).map { maybeContent =>
      val regex = """-\s+(.+)/([^/]+)""".r
      val content = maybeContent.getOrElse("")
      content.linesIterator.collect {
        case regex(owner, repo) => Repo(owner.trim, repo.trim)
      }.toList
    }

  private def steward(repo: Repo): F[Either[Throwable, Unit]] = {
    val label = s"Steward ${repo.show}"
    logger.infoTotalTime(label) {
      for {
        _ <- logger.info(util.string.lineLeftRight(label))
        _ <- repoCacheAlg.checkCache(repo)
        (attentionNeeded, updates) <- pruningAlg.needsAttention(repo)
        result <- {
          if (attentionNeeded) nurtureAlg.nurture(repo, updates)
          else gitAlg.removeClone(repo).as(().asRight[Throwable])
        }
      } yield result
    }
  }

  def runF: F[ExitCode] =
    logger.infoTotalTime("run") {
      for {
        _ <- printBanner
        _ <- selfCheckAlg.checkAll
        exitCode <- sbtAlg.addGlobalPlugins {
          for {
            _ <- workspaceAlg.cleanWorkspace
            repos <- readRepos(config.reposFile)
            result <- Stream.emits(repos).evalMap(steward).compile.foldMonoid
          } yield result.fold(_ => ExitCode.Error, _ => ExitCode.Success)
        }
      } yield exitCode
    }
} 
Example 53
Source File: Launcher.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
import cats.effect.ExitCode
import cats.effect.IO
import cats.effect.IOApp

object Launcher extends IOApp {

  def run(args: List[String]): IO[ExitCode] =
    args match {
      case List("EchoBot", token) =>
        new EchoBot[IO](token).startPolling.map(_ => ExitCode.Success)
      case List("CommandsBot", token) =>
        new CommandsBot[IO](token).startPolling.map(_ => ExitCode.Success)
      case List(name, _) =>
        IO.raiseError(new Exception(s"Unknown bot $name"))
      case _ =>
        IO.raiseError(new Exception("Usage:\nLauncher $botName $token"))
    }
} 
Example 54
Source File: CpgServerMain.scala    From codepropertygraph   with Apache License 2.0 5 votes vote down vote up
package io.shiftleft.cpgserver

import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._
import org.http4s.implicits._
import org.http4s.server.blaze.BlazeServerBuilder

import io.shiftleft.cpgserver.config.ServerConfiguration
import io.shiftleft.cpgserver.cpg.DummyCpgProvider
import io.shiftleft.cpgserver.query.{DefaultAmmoniteExecutor, ServerAmmoniteExecutor}
import io.shiftleft.cpgserver.route.{CpgRoute, HttpErrorHandler, SwaggerRoute}

object CpgServerMain extends IOApp {

  private val banner: String =
    """| ██████╗██████╗  ██████╗     ███████╗███████╗██████╗ ██╗   ██╗███████╗██████╗
       |██╔════╝██╔══██╗██╔════╝     ██╔════╝██╔════╝██╔══██╗██║   ██║██╔════╝██╔══██╗
       |██║     ██████╔╝██║  ███╗    ███████╗█████╗  ██████╔╝██║   ██║█████╗  ██████╔╝
       |██║     ██╔═══╝ ██║   ██║    ╚════██║██╔══╝  ██╔══██╗╚██╗ ██╔╝██╔══╝  ██╔══██╗
       |╚██████╗██║     ╚██████╔╝    ███████║███████╗██║  ██║ ╚████╔╝ ███████╗██║  ██║
       | ╚═════╝╚═╝      ╚═════╝     ╚══════╝╚══════╝╚═╝  ╚═╝  ╚═══╝  ╚══════╝╚═╝  ╚═╝
       |""".stripMargin

  private val cpgProvider: DummyCpgProvider =
    new DummyCpgProvider

  private val ammoniteExecutor: ServerAmmoniteExecutor =
    new DefaultAmmoniteExecutor

  private implicit val httpErrorHandler: HttpErrorHandler =
    CpgRoute.CpgHttpErrorHandler

  private val serverConfig: ServerConfiguration =
    ServerConfiguration.config.getOrElse(ServerConfiguration.default)

  private val httpRoutes =
    CpgRoute(cpgProvider, ammoniteExecutor, serverConfig.files).routes <+> SwaggerRoute().routes

  override def run(args: List[String]): IO[ExitCode] = {
    BlazeServerBuilder[IO]
      .withBanner(List(banner))
      .bindHttp(serverConfig.port, serverConfig.host)
      .withHttpApp(httpRoutes.orNotFound)
      .serve
      .compile
      .drain
      .as(ExitCode.Success)
  }
} 
Example 55
Source File: Playing.scala    From docspell   with GNU General Public License v3.0 5 votes vote down vote up
package docspell.files

import cats.effect.{Blocker, ExitCode, IO, IOApp}
import docspell.common.MimeTypeHint

import scala.concurrent.ExecutionContext

object Playing extends IOApp {
  val blocker = Blocker.liftExecutionContext(ExecutionContext.global)

  def run(args: List[String]): IO[ExitCode] =
    IO {
      //val ods = ExampleFiles.examples_sample_ods.readURL[IO](8192, blocker)
      //val odt = ExampleFiles.examples_sample_odt.readURL[IO](8192, blocker)
      val rtf = ExampleFiles.examples_sample_rtf.readURL[IO](8192, blocker)

      val x = for {
        odsm1 <-
          TikaMimetype
            .detect(
              rtf,
              MimeTypeHint.filename(ExampleFiles.examples_sample_rtf.path.segments.last)
            )
        odsm2 <- TikaMimetype.detect(rtf, MimeTypeHint.none)
      } yield (odsm1, odsm2)
      println(x.unsafeRunSync())
      ExitCode.Success
    }
}