scala.io.StdIn Scala Examples

The following examples show how to use scala.io.StdIn. 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: AbstractWebServer.scala    From ohara   with Apache License 2.0 6 votes vote down vote up
package oharastream.ohara.shabondi.common

import akka.Done
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.{Directives, Route}
import akka.http.scaladsl.settings.ServerSettings
import oharastream.ohara.common.util.Releasable

import scala.concurrent._
import scala.concurrent.duration.Duration
import scala.io.StdIn
import scala.util.{Failure, Success}


private[shabondi] abstract class AbstractWebServer extends Directives with Releasable {
  implicit protected val actorSystem: ActorSystem = ActorSystem(Logging.simpleName(this).replaceAll("\\$", ""))

  protected def routes: Route

  protected def postBinding(binding: ServerBinding): Unit = {
    val hostname = binding.localAddress.getHostName
    val port     = binding.localAddress.getPort
    actorSystem.log.info(s"Server online at http://$hostname:$port/")
  }

  protected def postBindingFailure(cause: Throwable): Unit = {
    actorSystem.log.error(cause, s"Error starting the server ${cause.getMessage}")
  }

  protected def waitForShutdownSignal()(implicit ec: ExecutionContext): Future[Done] = {
    val promise = Promise[Done]()
    sys.addShutdownHook {
      promise.trySuccess(Done)
    }
    Future {
      blocking {
        if (StdIn.readLine("Press <RETURN> to stop Shabondi WebServer...\n") != null)
          promise.trySuccess(Done)
      }
    }
    promise.future
  }

  protected def postServerShutdown(): Unit = actorSystem.log.info("Shutting down the server")

  def start(bindInterface: String, port: Int): Unit = {
    start(bindInterface, port, ServerSettings(actorSystem))
  }

  def start(bindInterface: String, port: Int, settings: ServerSettings): Unit = {
    implicit val executionContext: ExecutionContextExecutor = actorSystem.dispatcher

    val bindingFuture: Future[Http.ServerBinding] = Http().bindAndHandle(
      handler = routes,
      interface = bindInterface,
      port = port,
      settings = settings
    )

    bindingFuture.onComplete {
      case Success(binding) =>
        postBinding(binding)
      case Failure(cause) =>
        postBindingFailure(cause)
    }

    Await.ready(
      bindingFuture.flatMap(_ => waitForShutdownSignal()),
      Duration.Inf
    )

    bindingFuture
      .flatMap(_.unbind())
      .onComplete { _ =>
        postServerShutdown()
        actorSystem.terminate()
      }
  }

  override def close(): Unit = actorSystem.terminate()
} 
Example 2
Source File: FreeMonad.scala    From advanced-scala-code   with Apache License 2.0 5 votes vote down vote up
import scala.io.StdIn
import scalaz.concurrent.Task


trait ActionA[A]
case class ReadAction() extends ActionA[String]
case class WriteAction(output: String) extends ActionA[Unit]

object FreeMonad {
  def main(args: Array[String]) {

    import cats.free.Free
    type ActionF[A] = Free[ActionA, A]

    import cats.free.Free.liftF
    def read(): ActionF[String] = liftF[ActionA, String](ReadAction())
    def write(output: String): ActionF[Unit] = liftF[ActionA, Unit](WriteAction(output))

    val result = for {
      _ <- write("Write your name: ")
      name <- read()
      res <- write(s"Hello $name")
    } yield res
    // result: Free[ActionA, Unit]

    import cats.arrow.FunctionK
    import cats.{Id, Monad}


    val idInterpreter: FunctionK[ActionA, Id] =
      new FunctionK[ActionA, Id] {
      override def apply[A](fa: ActionA[A]): Id[A] = fa match {
        case ReadAction() =>
          val input = StdIn.readLine()
          input
        case WriteAction(output) =>
          println(output)
      }
    }

    def taskInterpreter: FunctionK[ActionA, Task] =
      new FunctionK[ActionA, Task] {
      def apply[A](fa: ActionA[A]): Task[A] = (fa match {
        case ReadAction() => Task.delay {
          val input = StdIn.readLine()
          input
        }
        case WriteAction(output) => Task.delay {
          println(output)
        }
      }).asInstanceOf[Task[A]]
    }

    implicit val taskMonad = new Monad[Task] {
      override def tailRecM[A,B](a: A)(f: A => Task[Either[A,B]]): Task[B] =
        Task.suspend(f(a)).flatMap {
          case Left(continueA) => tailRecM(continueA)(f)
          case Right(b) => Task.now(b)
        }
      override def flatMap[A, B](fa: Task[A])(f: (A) => Task[B]):
        Task[B] = fa.flatMap(f)
      override def pure[A](x: A): Task[A] = Task.now(x)
    }

    result.foldMap(taskInterpreter).unsafePerformSync

  }
} 
Example 3
Source File: Graph2.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, ClosedShape }
import akka.stream.scaladsl.{ Broadcast, Flow, GraphDSL, RunnableGraph, Sink, Source }

import scala.io.StdIn

object Graph2 extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  val topHeadSink = Sink.head[Int]
  val bottomHeadSink = Sink.head[Int]
  val sharedDoubler = Flow[Int].map(_ * 2)

  val g = RunnableGraph.fromGraph(GraphDSL.create(topHeadSink, bottomHeadSink)((_, _)) {
    implicit builder => (topHS, bottomHS) =>
      import GraphDSL.Implicits._

      val broadcast = builder.add(Broadcast[Int](2))
      Source.single(1) ~> broadcast.in

      broadcast ~> sharedDoubler ~> topHS.in
      broadcast ~> sharedDoubler ~> bottomHS.in

      ClosedShape
  })

  val (topF, bottomF) = g.run()
  topF.foreach(v => println(s"top is $v"))
  bottomF.foreach(v => println(s"bottom is $v"))

  StdIn.readLine()
  system.terminate()
} 
Example 4
Source File: SimplifiedAPI.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.actor.{ Actor, ActorSystem, Props }
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Broadcast, Merge, Sink, Source }

import scala.io.StdIn

class Remotely extends Actor {
  override def receive: Receive = {
    case value => println(s"receive: $value")
  }
}

object SimplifiedAPI extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  val merged = Source.combine(Source(List(1)), Source(List(2)))(Merge(_))
  val mergedResult = merged.runWith(Sink.fold(0)(_ + _))
  mergedResult.foreach(println)

  val sendRemotely =
    Sink.actorRef(system.actorOf(Props[Remotely], "remotely"), "Done")
  val localProcessing = Sink.foreach[Int](v => println(s"foreach($v)"))
  Source(List(0, 1, 1)).runWith(Sink.combine(sendRemotely, localProcessing)(strategy => Broadcast[Int](strategy)))

  StdIn.readLine()
  system.terminate()
} 
Example 5
Source File: PartialGraph2.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Broadcast, Flow, GraphDSL, Sink, Source, Zip }
import akka.stream.{ ActorMaterializer, FlowShape, SourceShape }

import scala.io.StdIn

object PartialGraph2 extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  val pairs: Source[(Int, Int), NotUsed] = Source.fromGraph(GraphDSL.create() { implicit b =>
    import GraphDSL.Implicits._

    // prepare graph elements
    val zip = b.add(Zip[Int, Int]())

    def ints = Source.fromIterator(() => Iterator.from(1))

    // connect the graph
    ints.filter(_ % 2 != 0) ~> zip.in0
    ints.filter(_ % 2 == 0) ~> zip.in1

    // expose port
    SourceShape(zip.out)
  })

  val firstPair = pairs.runWith(Sink.head)
  firstPair.foreach(println)

  val pairUpWithToString = Flow.fromGraph(GraphDSL.create() { implicit b =>
    import GraphDSL.Implicits._
    val broadcast = b.add(Broadcast[Int](2))
    val zip = b.add(Zip[Int, String]())

    broadcast.out(0)  ~> zip.in0
    broadcast.out(1).map(_.toString) ~> zip.in1

    FlowShape(broadcast.in, zip.out)
  })

  Source(List(1)).via(pairUpWithToString).runWith(Sink.head).foreach(println)

  StdIn.readLine()
  system.terminate()
} 
Example 6
Source File: GraphComponent.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.actor.ActorSystem
import akka.stream.FanInShape.{ Init, Name }
import akka.stream._
import akka.stream.scaladsl.{ Balance, Flow, GraphDSL, Merge, MergePreferred, RunnableGraph, Sink, Source }

import scala.collection.immutable
import scala.io.StdIn

case class PriorityWorkerPoolShape[In, Out](jobsIn: Inlet[In], priorityJobsIn: Inlet[In], resultsOut: Outlet[Out])
    extends Shape {
  override def inlets: immutable.Seq[Inlet[_]] = jobsIn :: priorityJobsIn :: Nil

  override def outlets: immutable.Seq[Outlet[_]] = resultsOut :: Nil

  override def deepCopy(): Shape =
    PriorityWorkerPoolShape(jobsIn.carbonCopy(), priorityJobsIn.carbonCopy(), resultsOut.carbonCopy())
}

case class PriorityWorkerPoolShape2[In, Out](_init: Init[Out] = Name("PriorityWorkerPoolShape2"))
    extends FanInShape[Out](_init) {
  override protected def construct(init: Init[Out]): FanInShape[Out] =
    PriorityWorkerPoolShape2(init)

  val jobsIn: Inlet[In] = newInlet[In]("jobsIn")
  val priorityJobsIn: Inlet[In] = newInlet[In]("priorityJobsIn")
  // Outlet[Out] 使用名字 "out" 将被自动创建
}

object PriorityWorkerPool {
  def apply[In, Out](worker: Flow[In, Out, Any], workerCount: Int) =
    GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      val priorityMerge = b.add(MergePreferred[In](1))
      val balance = b.add(Balance[In](workerCount))
      val resultsMerge = b.add(Merge[Out](workerCount))

      for (i <- 0 until workerCount)
        balance.out(i) ~> worker ~> resultsMerge.in(i)

      // 在合并优先和普通作业后发送到平衡器
      priorityMerge ~> balance

      PriorityWorkerPoolShape(priorityMerge.in(0), priorityMerge.preferred, resultsMerge.out)
    }
}

object GraphComponent extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  val worker1 = Flow[String].map("step 1 " + _)
  val worker2 = Flow[String].map("step 2 " + _)

  val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b =>
    import GraphDSL.Implicits._

    val priorityPool1 = b.add(PriorityWorkerPool(worker1, 4))
    val priorityPool2 = b.add(PriorityWorkerPool(worker2, 2))

    Source(1 to 10).map("job: " + _) ~> priorityPool1.jobsIn
    Source(1 to 10).map("priority job: " + _) ~> priorityPool1.priorityJobsIn

    priorityPool1.resultsOut ~> priorityPool2.jobsIn
    Source(1 to 10).map("one-step, priority " + _) ~> priorityPool2.priorityJobsIn

    priorityPool2.resultsOut ~> Sink.foreach(println)
    ClosedShape
  })

  g.run()

  StdIn.readLine()
  system.terminate()
} 
Example 7
Source File: Graph1.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, ClosedShape }
import akka.stream.scaladsl.{ Broadcast, Flow, GraphDSL, Merge, RunnableGraph, Sink, Source }

import scala.collection.immutable
import scala.io.StdIn

object Graph1 extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val graph = g(1 to 2)

  graph.run()

  StdIn.readLine()
  system.terminate()

  def g(data: immutable.Iterable[Int]) =
    RunnableGraph.fromGraph(GraphDSL.create() { implicit b: GraphDSL.Builder[NotUsed] =>
      import GraphDSL.Implicits._
      val in = Source(data)
      val out = Sink.foreach(println)

      val bcast = b.add(Broadcast[Int](2))
      val merge = b.add(Merge[Int](2))

      val f1, f2, f3, f4 = Flow[Int].map(_ + 10)

      in ~> f1 ~> bcast ~> f2 ~> merge ~> f3 ~> out
      bcast ~> f4 ~> merge

      ClosedShape
    })
} 
Example 8
Source File: EchoDemo.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.streamio

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Flow, Framing, Sink, Source, Tcp }
import akka.util.ByteString
import example.akkastream.streamio.EchoServer.system

import scala.concurrent.Future
import scala.io.StdIn

object EchoServer extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val connections = Tcp().bind("localhost", 8888)
  connections.runForeach { connection =>
    println(s"New connection from: ${connection.remoteAddress}")

    val echo: Flow[ByteString, ByteString, NotUsed] = Flow[ByteString]
      .via(Framing.delimiter(ByteString("\n"), 256, true))
      .map(_.utf8String)
      .map(_ + "!!!\n")
      .map(ByteString(_))

    connection.handleWith(echo)
  }

  StdIn.readLine()
  system.terminate()
}

object EchoClient extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val connection = Tcp().outgoingConnection("localhost", 8888)

  val replParser =
    Flow[String].takeWhile(_ != "q").concat(Source.single("BYE")).map { elem =>
      println(s"send msg: $elem")
      ByteString(s"$elem\n")
    }

  val repl = Flow[ByteString]
    .via(Framing.delimiter(ByteString("\n"), maximumFrameLength = 256, allowTruncation = true))
    .map(_.utf8String)
    .map(text => println("Server: " + text))
    .map(_ => StdIn.readLine("> "))
    .via(replParser)

  val connected: Future[Tcp.OutgoingConnection] = connection.join(repl).run()

  //  StdIn.readLine()
  //  system.terminate()
}

object EchoDemo {} 
Example 9
Source File: PartialGraph.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.graph

import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Balance, Broadcast, Flow, GraphDSL, Keep, Merge, RunnableGraph, Sink, Source }
import akka.stream.{ ActorMaterializer, FlowShape, SourceShape }

import scala.concurrent.Future
import scala.io.StdIn

object PartialGraph extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  def partial =
    GraphDSL
      .create() { implicit b =>
        import GraphDSL.Implicits._

        val B = b.add(Broadcast[Int](2))
        val C = b.add(Merge[Int](2))
        val D = Flow[Int].map(_ + 1)
        val E = b.add(Balance[Int](2))
        val F = b.add(Merge[Int](2))

        C <~ F
        B ~> C ~> F
        B ~> D ~> E ~> F

        FlowShape(B.in, E.out(1))
      }
      .named("partial")

  // 转换partial从FlowShape到Flow,可访问流DSL(比如:.filter() 函数)
  val flow = Flow.fromGraph(partial)

  val source = Source.fromGraph(GraphDSL.create() { implicit b =>
    import GraphDSL.Implicits._
    val merge = b.add(Merge[Int](2))
    Source.single(0) ~> merge
    Source(List(2, 3, 4)) ~> merge
    SourceShape(merge.out)
  })

  val sink: Sink[Int, Future[Int]] = Flow[Int].map(_ * 2).drop(10).named("nestedFlow").toMat(Sink.head)(Keep.right)

  val closed: RunnableGraph[Future[Int]] =
    source.via(flow.filter(_ > 1)).toMat(sink)(Keep.right)

  closed.run().foreach(println)

  StdIn.readLine()
  system.terminate()
} 
Example 10
Source File: Deadlocks.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.graph

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, ClosedShape, OverflowStrategy }
import akka.stream.scaladsl.{
  Broadcast,
  Concat,
  Flow,
  GraphDSL,
  Merge,
  MergePreferred,
  RunnableGraph,
  Sink,
  Source,
  ZipWith
}

import scala.io.StdIn

object Deadlocks extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val source = Source(1 to 10)

  
      concat <~ bcast
      ClosedShape
    })
    .run()

  StdIn.readLine()
  system.terminate()
} 
Example 11
Source File: BalancingPoolDemo.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example

import akka.actor.{ Actor, ActorLogging, ActorRef, ActorSystem, Props }
import example.Worker.FibonacciNumber

import scala.annotation.tailrec
import scala.concurrent.duration._
import scala.io.StdIn

object Worker {
  case class FibonacciNumber(nbr: Int, delay: FiniteDuration)

  case class GetResult(nr: Int, source: ActorRef)

  def props: Props = Props(new Worker)
}

class Worker extends Actor with ActorLogging {
  import Worker._
  import context.dispatcher

  override def preStart(): Unit =
    log.info(s"$self started")

  override def postStop(): Unit =
    log.info(s"$self stopped")

  override def receive: Receive = {
    case FibonacciNumber(nr, delay) =>
      context.system.scheduler.scheduleOnce(delay, self, GetResult(nr, sender()))

    case GetResult(nr, source) =>
      val result = fibonacci(nr)
      log.info(s"$nr! = $result")
  }

  private def fibonacci(n: Int): Int = {
    @tailrec
    def fib(n: Int, b: Int, a: Int): Int = n match {
      case 0 => a
      case _ =>
        fib(n - 1, a + b, b)
    }
    fib(n, 1, 0)
  }
}

object BalancingPoolDemo extends App {
  implicit val system = ActorSystem()

  val worker = system.actorOf(Worker.props, "worker")
  worker ! FibonacciNumber(50, 50.millis)
  worker ! FibonacciNumber(33, 50.millis)
  worker ! FibonacciNumber(68, 50.millis)
  worker ! FibonacciNumber(53, 50.millis)
  worker ! FibonacciNumber(45, 50.millis)

  StdIn.readLine()
  system.terminate()
} 
Example 12
Source File: AkkaHttpServer.scala    From learn-akka   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.learn.akka.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
import com.allaboutscala.learn.akka.http.routes.{DonutRoutes, ServerVersion}
import com.typesafe.scalalogging.LazyLogging

import scala.io.StdIn
import scala.util.{Failure, Success}


object AkkaHttpServer extends App with LazyLogging {

  implicit val system = ActorSystem("akka-http-rest-server")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  // these should ideally be in some configuration file
  val host = "127.0.0.1"
  val port = 8080

  implicit val globalRejectionHandler =
    RejectionHandler.newBuilder()
      .handle { case ValidationRejection(msg, route) =>
        complete(StatusCodes.InternalServerError, s"The operation is not supported, error = $msg")
      }
      .handleNotFound {
        complete(StatusCodes.NotFound, "The path is not supported.")
      }
      .result()


  implicit val globalExceptionHandler = ExceptionHandler {
    case e: RuntimeException => complete(s"A runtime exception occurred with, msg = ${e.getMessage}")
  }


//  // routes
//  val serverUpRoute: Route = get {
//    complete("Akka HTTP Server is UP.")
//  }

  val serverVersion = new ServerVersion()
  val serverVersionRoute = serverVersion.route()
  val serverVersionRouteAsJson = serverVersion.routeAsJson()
  val serverVersionJsonEncoding = serverVersion.routeAsJsonEncoding()
  val donutRoutes = new DonutRoutes().route()

  val routes: Route =  donutRoutes ~ serverVersionRoute ~ serverVersionRouteAsJson ~ serverVersionJsonEncoding//
  // ~ serverUpRoute

  val httpServerFuture = Http().bindAndHandle(routes, host, port)
  httpServerFuture.onComplete {
    case Success(binding) =>
      logger.info(s"Akka Http Server is UP and is bound to ${binding.localAddress}")

    case Failure(e) =>
      logger.error(s"Akka Http server failed to start", e)
      system.terminate()
  }

  StdIn.readLine() // let it run until user presses return
  httpServerFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
} 
Example 13
Source File: Server.scala    From chat-with-akka-http-websockets   with Apache License 2.0 5 votes vote down vote up
package chat

import akka.NotUsed
import akka.actor._
import akka.http.scaladsl._
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._

import scala.concurrent.duration._
import scala.concurrent.Await
import scala.io.StdIn

object Server {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()

    val chatRoom = system.actorOf(Props(new ChatRoom), "chat")

    def newUser(): Flow[Message, Message, NotUsed] = {
      // new connection - new user actor
      val userActor = system.actorOf(Props(new User(chatRoom)))

      val incomingMessages: Sink[Message, NotUsed] =
        Flow[Message].map {
          // transform websocket message to domain message
          case TextMessage.Strict(text) => User.IncomingMessage(text)
        }.to(Sink.actorRef[User.IncomingMessage](userActor, PoisonPill))

      val outgoingMessages: Source[Message, NotUsed] =
        Source.actorRef[User.OutgoingMessage](10, OverflowStrategy.fail)
        .mapMaterializedValue { outActor =>
          // give the user actor a way to send messages out
          userActor ! User.Connected(outActor)
          NotUsed
        }.map(
          // transform domain message to web socket message
          (outMsg: User.OutgoingMessage) => TextMessage(outMsg.text))

      // then combine both to a flow
      Flow.fromSinkAndSource(incomingMessages, outgoingMessages)
    }

    val route =
      path("chat") {
        get {
          handleWebSocketMessages(newUser())
        }
      }

    val binding = Await.result(Http().bindAndHandle(route, "127.0.0.1", 8080), 3.seconds)


    // the rest of the sample code will go here
    println("Started server at 127.0.0.1:8080, press enter to kill server")
    StdIn.readLine()
    system.terminate()
  }
} 
Example 14
Source File: Pure.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.pure

import cats.effect._
import cats.implicits._
//import cats.syntax.all._
import com.typesafe.config._
import com.wegtam.books.pfhais.pure.api._
import com.wegtam.books.pfhais.pure.config._
import com.wegtam.books.pfhais.pure.db._
import doobie._
import eu.timepit.refined.auto._
import org.http4s.implicits._
import org.http4s.server.Router
import org.http4s.server.blaze._
import pureconfig._

import scala.io.StdIn

object Pure extends IOApp {

  @SuppressWarnings(
    Array(
      "org.wartremover.warts.Any",
      "scalafix:DisableSyntax.null"
    )
  )
  def run(args: List[String]): IO[ExitCode] = {
    val migrator: DatabaseMigrator[IO] = new FlywayDatabaseMigrator

    val program = for {
      (apiConfig, dbConfig) <- IO {
        val cfg = ConfigFactory.load(getClass().getClassLoader())
        // TODO Think about alternatives to `Throw`.
        (
          loadConfigOrThrow[ApiConfig](cfg, "api"),
          loadConfigOrThrow[DatabaseConfig](cfg, "database")
        )
      }
      ms <- migrator.migrate(dbConfig.url, dbConfig.user, dbConfig.pass)
      tx = Transactor
        .fromDriverManager[IO](dbConfig.driver, dbConfig.url, dbConfig.user, dbConfig.pass)
      repo           = new DoobieRepository(tx)
      productRoutes  = new ProductRoutes(repo)
      productsRoutes = new ProductsRoutes(repo)
      routes         = productRoutes.routes <+> productsRoutes.routes
      httpApp        = Router("/" -> routes).orNotFound
      server         = BlazeServerBuilder[IO].bindHttp(apiConfig.port, apiConfig.host).withHttpApp(httpApp)
      fiber          = server.resource.use(_ => IO(StdIn.readLine())).as(ExitCode.Success)
    } yield fiber
    program.attempt.unsafeRunSync match {
      case Left(e) =>
        IO {
          println("*** An error occured! ***")
          if (e ne null) {
            println(e.getMessage)
          }
          ExitCode.Error
        }
      case Right(r) => r
    }
  }
} 
Example 15
Source File: Impure.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.impure

import akka.actor._
import akka.http.scaladsl._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import com.wegtam.books.pfhais.impure.api._
import com.wegtam.books.pfhais.impure.db._
import eu.timepit.refined.auto._
import org.flywaydb.core.Flyway
import slick.basic._
import slick.jdbc._

import scala.io.StdIn
import scala.concurrent.ExecutionContext

object Impure {

  
  @SuppressWarnings(Array("org.wartremover.warts.Any"))
  def main(args: Array[String]): Unit = {
    implicit val system: ActorSystem    = ActorSystem()
    implicit val mat: ActorMaterializer = ActorMaterializer()
    implicit val ec: ExecutionContext   = system.dispatcher

    val url = "jdbc:postgresql://" +
      system.settings.config.getString("database.db.properties.serverName") +
      ":" + system.settings.config.getString("database.db.properties.portNumber") +
      "/" + system.settings.config.getString("database.db.properties.databaseName")
    val user           = system.settings.config.getString("database.db.properties.user")
    val pass           = system.settings.config.getString("database.db.properties.password")
    val flyway: Flyway = Flyway.configure().dataSource(url, user, pass).load()
    val _              = flyway.migrate()

    val dbConfig: DatabaseConfig[JdbcProfile] =
      DatabaseConfig.forConfig("database", system.settings.config)
    val repo = new Repository(dbConfig)

    val productRoutes  = new ProductRoutes(repo)
    val productsRoutes = new ProductsRoutes(repo)
    val routes         = productRoutes.routes ~ productsRoutes.routes

    val host       = system.settings.config.getString("api.host")
    val port       = system.settings.config.getInt("api.port")
    val srv        = Http().bindAndHandle(routes, host, port)
    val pressEnter = StdIn.readLine()
    srv.flatMap(_.unbind()).onComplete(_ => system.terminate())
  }

} 
Example 16
Source File: PartialGraph.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.actor.ActorSystem
import akka.stream.scaladsl.{ GraphDSL, RunnableGraph, Sink, Source, ZipWith }
import akka.stream.{ ActorMaterializer, ClosedShape, UniformFanInShape }

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object PartialGraph extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  val pickMaxOfThree = GraphDSL.create() { implicit b =>
    import GraphDSL.Implicits._

    // ZipWith 最后一个泛型是输出参数类型。
    val zip1 = b.add(ZipWith[Int, Int, Int](math.max))
    val zip2 = b.add(ZipWith[Int, Int, Int](math.max))
    zip1.out ~> zip2.in0
    UniformFanInShape(zip2.out, zip1.in0, zip1.in1, zip2.in1)
  }

  val resultSink = Sink.head[Int]

  val g = RunnableGraph.fromGraph(GraphDSL.create(resultSink) { implicit b => sink =>
    import GraphDSL.Implicits._

    val pm3 = b.add(pickMaxOfThree)

    Source.single(4) ~> pm3.in(0)
    Source.single(2) ~> pm3.in(1)
    Source.single(3) ~> pm3.in(2)
    pm3.out ~> sink.in

    ClosedShape
  })

  val result = Await.result(g.run, 300.millis)
  println(s"result: $result")

  StdIn.readLine()
  system.terminate()
} 
Example 17
Source File: ConsoleMonad.scala    From advanced-scala-code   with Apache License 2.0 5 votes vote down vote up
import cats.Monad

import scala.io.StdIn


trait ConsoleAction[A] {
  def bind[B](f: A => ConsoleAction[B]): ConsoleAction[B]
}

case class ReadFromConsole() extends ConsoleAction[String] {
  override def bind[B](f: (String) => ConsoleAction[B]): ConsoleAction[B] = {
    val input = StdIn.readLine()
    f(input)
  }
}

case class WriteToConsole(output: String) extends ConsoleAction[Unit] {
  override def bind[B](f: (Unit) => ConsoleAction[B]): ConsoleAction[B] = {
    println(output)
    f()
  }
}

case class NopConsole() extends ConsoleAction[Unit] {
  override def bind[B](f: (Unit) => ConsoleAction[B]): ConsoleAction[B] = {
    f()
  }
}

object ConsoleMonad {
  def main(args: Array[String]) {
    implicit val consoleMonad = new Monad[ConsoleAction] {
      override def flatMap[A, B](fa: ConsoleAction[A])(f: (A) => ConsoleAction[B]):
        ConsoleAction[B] = fa.bind(f)
      override def pure[A](x: A): ConsoleAction[A] =
        NopConsole().asInstanceOf[ConsoleAction[A]]
      // Not stack-safe
      override def tailRecM[A, B](a: A)(f: (A) => ConsoleAction[Either[A, B]]):
        ConsoleAction[B] = flatMap(f(a)) {
        case Left(next) => tailRecM(next)(f)
        case Right(b) => pure(b)
      }
    }

    import cats.syntax.flatMap._
    import cats.syntax.functor._

    for {
      _ <- WriteToConsole("Write your name: ")
      name <- ReadFromConsole()
      _ <- WriteToConsole(s"Hello $name")
    } yield ()
  }
} 
Example 18
Source File: ExampleApp.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.akkahttp

import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import caliban.ExampleData.sampleCharacters
import caliban.ExampleService.ExampleService
import caliban.interop.circe.AkkaHttpCirceAdapter
import caliban.{ ExampleApi, ExampleService }
import zio.clock.Clock
import zio.console.Console
import zio.internal.Platform
import zio.Runtime


  val route =
    path("api" / "graphql") {
      adapter.makeHttpService(interpreter)
    } ~ path("ws" / "graphql") {
      adapter.makeWebSocketService(interpreter)
    } ~ path("graphiql") {
      getFromResource("graphiql.html")
    }

  val bindingFuture = Http().bindAndHandle(route, "localhost", 8088)
  println(s"Server online at http://localhost:8088/\nPress RETURN to stop...")
  StdIn.readLine()
  bindingFuture
    .flatMap(_.unbind())
    .onComplete(_ => system.terminate())

} 
Example 19
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpjackson

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    // provide an implicit ObjectMapper if you want serialization/deserialization to use it
    // instead of a default ObjectMapper configured only with DefaultScalaModule provided
    // by JacksonSupport
    //
    // for example:
    //
    // implicit val objectMapper = new ObjectMapper()
    //   .registerModule(DefaultScalaModule)
    //   .registerModule(new GuavaModule())

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import Directives._
    import JacksonSupport._

    pathSingleSlash {
      post {

        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 20
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpcirce

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{ HttpRequest, RequestEntity }
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source

import scala.io.StdIn
import scala.concurrent.duration._

object ExampleApp {

  private final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    system.terminate()
  }

  private def route(implicit sys: ActorSystem) = {
    import Directives._
    import FailFastCirceSupport._
    import io.circe.generic.auto._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          import sys._

          Marshal(Source.single(Foo("a"))).to[RequestEntity]

          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 21
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpavro4s

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{ HttpRequest, RequestEntity }
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import com.sksamuel.avro4s.{ FromRecord, SchemaFor, ToRecord }

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final object Foo {
    implicit val schemaFor  = SchemaFor[Foo]
    implicit val toRecord   = ToRecord[Foo]
    implicit val fromRecord = FromRecord[Foo]
  }
  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import AvroSupport._
    import Directives._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          import sys._

          Marshal(Source.single(Foo("a"))).to[RequestEntity]

          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 22
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpjson4s

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import org.json4s.{ DefaultFormats, jackson }

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import Directives._
    import Json4sSupport._

    implicit val serialization = jackson.Serialization // or native.Serialization
    implicit val formats       = DefaultFormats

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 23
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpavsystemgencodec

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.{ Materialzer, Materializer }
import com.avsystem.commons.serialization.GenCodec

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.io.StdIn

object ExampleApp {

  final object Foo {
    implicit val codec: GenCodec[Foo] = GenCodec.materialize[Foo]
  }

  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val mat    = Materialzer()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit mat: Materializer) = {
    import Directives._
    import GenCodecSupport._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    }
  }
} 
Example 24
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpplayjson

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import play.api.libs.json.{ Format, JsValue, Json }

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final object Foo {
    implicit val fooFormat: Format[Foo] = Json.format[Foo]
  }
  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import Directives._
    import PlayJsonSupport._

    implicit val prettyPrint: JsValue => String = Json.prettyPrint

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 25
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpjsoniterscala

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.{ Directives, Route }
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system: ActorSystem = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem): Route = {
    import Directives._
    import JsoniterScalaSupport._
    import com.github.plokhotnyuk.jsoniter_scala.core._
    import com.github.plokhotnyuk.jsoniter_scala.macros._

    // here you should provide implicit codecs for in/out messages of all routes

    implicit val codec: JsonValueCodec[Foo] = JsonCodecMaker.make[Foo](CodecMakerConfig)

    // also, you can provide an implicit reader/writer configs to override defaults:
    //
    // implicit val readerConfig = ReaderConfig.withThrowReaderExceptionWithStackTrace(true)
    // implicit val writerConfig = WriterConfig.withIndentionStep(2)

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 26
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpargonaut

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{ HttpRequest, RequestEntity }
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import argonaut.Argonaut.casecodec1
import argonaut.CodecJson

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object ExampleApp {

  final object Foo {
    implicit val fooCodec: CodecJson[Foo] =
      casecodec1(Foo.apply, Foo.unapply)("bar")
  }
  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit sys: ActorSystem) = {
    import ArgonautSupport._
    import Directives._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          import sys._

          Marshal(Source.single(Foo("a"))).to[RequestEntity]

          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 27
Source File: ExampleApp.scala    From akka-http-json   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.akkahttpupickle

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.Source
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn
import upickle.default.{ ReadWriter, macroRW }

object ExampleApp {

  final object Foo {
    implicit val rw: ReadWriter[Foo] = macroRW
  }

  final case class Foo(bar: String)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    Await.ready(system.terminate(), Duration.Inf)
  }

  def route(implicit system: ActorSystem) = {
    import Directives._
    import UpickleSupport._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    } ~ pathPrefix("stream") {
      post {
        entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] =>
          complete(fooSource.throttle(1, 2.seconds))
        }
      } ~ get {
        pathEndOrSingleSlash {
          complete(
            Source(0 to 5)
              .throttle(1, 1.seconds)
              .map(i => Foo(s"bar-$i"))
          )
        } ~ pathPrefix("remote") {
          onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) {
            response => complete(Unmarshal(response).to[SourceOf[Foo]])
          }
        }
      }
    }
  }
} 
Example 28
Source File: ExampleTest.scala    From Swallow   with Apache License 2.0 5 votes vote down vote up
package examples

import akka.actor._
import swallow.Util.KMAkkaKit
import swallow.core.KMActorMessages.{ReceiverGetFlow, TestFlow}
import swallow.core.{KMDataType, KMFlow, KMFlowInfo, KMNode}

import scala.io.StdIn


object ExampleTest {

  def main(args: Array[String]): Unit = {

    val testActor =  KMAkkaKit.initActorRefWith("TestSystem", "0.0.0.0", 17233, Props(new ExampleTest), "testActor")

    val flowId: String = "FLOW-000001"
    val taskId: String = "TASK-000001"
    val master: String = "akka.tcp://[email protected]:17200/user/masterActor"
    val from: String = "akka.tcp://[email protected]:17201/user/senderActor"
    val to: String = "akka.tcp://[email protected]:17202/user/receiverActor"
    val content: String = "****** Hello Akka !!! ******"
    val description: String = "Version 0.4-SNAPSHOT"
    val dataType: KMDataType.DataType = KMDataType.FAKE

    val flowInfo = new KMFlowInfo(flowId, taskId, master, from, to, content, description, dataType)
    val flow = KMFlow.initWithFlowInfo(flowInfo)


    StdIn.readLine()
    testActor ! TestFlow(flow)
  }

}

class ExampleTest extends Actor with ActorLogging {
  override def receive: Receive = {
    case TestFlow(flow) =>
      log.info(s"[LocalActor] transferFlow; [From sender]: $sender")
      log.info(s"[Flow Info] from: ${flow.flowInfo.from}; to: ${flow.flowInfo.to}; content: ${flow.flowInfo.content}")

      val remoteActor = context.actorSelection(s"${flow.flowInfo.to}")
      remoteActor ! ReceiverGetFlow(flow)
  }
} 
Example 29
Source File: ExampleMaster.scala    From Swallow   with Apache License 2.0 5 votes vote down vote up
package examples



import akka.actor.{ActorSystem, Props}
import com.typesafe.config.ConfigFactory
import swallow.Util.KMAkkaKit

import scala.io.StdIn
import swallow.core.{KMDataType, KMFlow, KMFlowInfo}
import swallow.master.{KMJobDispatcher, KMMaster}

object ExampleMaster {
  def main(args: Array[String]): Unit = {

    val masterSystem = KMAkkaKit.initActorSystemWith("MasterSystem", "0.0.0.0", 17200)
    KMAkkaKit.initActorRefWith(masterSystem, KMMaster.props, "masterActor")

    val flowId: String = "FLOW-000001"
    val taskId: String = "TASK-000001"
    val master: String = "akka.tcp://[email protected]:17200/user/masterActor"
    val from: String = "akka.tcp://[email protected]:17201/user/senderActor"
    val to: String = "akka.tcp://[email protected]:17202/user/receiverActor"
    val content: String = "****** Hello Akka !!! ******"
    val description: String = "Version 0.4-SNAPSHOT"
    val dataType: KMDataType.DataType = KMDataType.FAKE

    val flowInfo = new KMFlowInfo(flowId, taskId, master, from, to, content, description, dataType)
    val flow = KMFlow.initWithFlowInfo(flowInfo)


    Thread.sleep(5000)
    println("****** Press Enter To Continue. ******")
    StdIn.readLine()

    KMJobDispatcher.dispatchNewFlow(masterSystem, flow)

    StdIn.readLine()
    masterSystem.terminate()
  }
} 
Example 30
Source File: KMClusterApp.scala    From Swallow   with Apache License 2.0 5 votes vote down vote up
package examples



import com.typesafe.config.ConfigFactory
import akka.actor.ActorSystem
import akka.actor.Props

import scala.io.StdIn

object KMClusterApp {

  def main(args: Array[String]): Unit = {
    if (args.isEmpty)
      startup(Seq("2551", "2552"))
    else
      startup(args)

    StdIn.readLine()
  }

  def startup(ports: Seq[String]): Unit = {
    ports foreach { port =>
      // Override the configuration of the port
      val config = ConfigFactory.parseString("akka.remote.netty.tcp.port=" + port).
        withFallback(ConfigFactory.load().getConfig("clusterActor"))

      // Create an Akka system
      val system = ActorSystem("ClusterSystem", config)
      // Create an actor that handles cluster domain events
      system.actorOf(Props[KMClusterListener], name = "clusterListener")
    }
  }

} 
Example 31
Source File: ComposeFreeMonads.scala    From Freasy-Monad   with MIT License 5 votes vote down vote up
package examples.cats

import cats.data._
import cats.free._
import cats._
import freasymonad.cats.free

import scala.collection.mutable.ListBuffer
import scala.io.StdIn

// example based off https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/freemonad.md#composing-free-monads-adts
object ComposeFreeMonads extends App {

  @free trait Interact {
    type InteractF[A] = Free[Adt, A]
    sealed trait Adt[A]
    def ask(prompt: String): InteractF[String]
    def tell(msg: String): InteractF[Unit]
  }

  @free trait DataSource {
    type DataSourceF[A] = Free[Adt, A]
    sealed trait Adt[A]
    def addCat(a: String): DataSourceF[Unit]
    def getAllCats: DataSourceF[List[String]]
    def addAndGetAllCats(a: String): DataSourceF[List[String]] =
     for {
       _ <- addCat(a)
       c <- getAllCats
     } yield c
  }

  type CatsApp[A] = EitherK[DataSource.Adt, Interact.Adt, A]

  // program1 and program2 are the same.
  // This library lets you choose which style you like.
  def program1(implicit I: Interact.Injects[CatsApp], D : DataSource.Injects[CatsApp]): Free[CatsApp, Unit] = {
    import I._, D._
    for {
      cat  <- ask("What's the kitty's name?")
      cats <- addAndGetAllCats(cat)
      _    <- tell(cats.toString)
    } yield ()
  }

  val program2: Free[CatsApp, Unit] = {
    import Interact.injectOps._, DataSource.injectOps._
    for {
      cat  <- ask[CatsApp]("What's the kitty's name?")
      cats <- addAndGetAllCats[CatsApp](cat)
      _    <- tell[CatsApp](cats.toString)
    } yield ()
  }

  val consoleCats: Interact.Interp[Id] = new Interact.Interp[Id] {
    def ask(prompt: String): Id[String] = {
      println(prompt)
      StdIn.readLine()
    }
    def tell(msg: String): Id[Unit] = println(msg)
  }

  val inMemoryDatasource: DataSource.Interp[Id] = new DataSource.Interp[Id] {
    private[this] val memDataSet = new ListBuffer[String]
    def addCat(a: String): Id[Unit] = memDataSet.append(a)
    def getAllCats: Id[List[String]] = memDataSet.toList
  }

  val interpreter: CatsApp ~> Id = inMemoryDatasource or consoleCats

  program1.foldMap(interpreter)
  program2.foldMap(interpreter)
} 
Example 32
Source File: package.scala    From Principles-of-Reactive-Programming   with GNU General Public License v3.0 5 votes vote down vote up
import scala.language.postfixOps
import scala.io.StdIn
import scala.util._
import scala.util.control.NonFatal
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.async.Async.{async, await}


    def apply() = new CancellationTokenSource {
      val p = Promise[Unit]()
      val cancellationToken = new CancellationToken {
        def isCancelled = p.future.value != None
      }
      def unsubscribe() {
        p.trySuccess(())
      }
    }
  }
} 
Example 33
Source File: Main.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package com.omearac

import akka.actor.{ActorSystem, Props}
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import com.omearac.consumers.ConsumerStreamManager.InitializeConsumerStream
import com.omearac.consumers.{ConsumerStreamManager, DataConsumer, EventConsumer}
import com.omearac.http.HttpService
import com.omearac.producers.ProducerStreamManager.InitializeProducerStream
import com.omearac.producers.{DataProducer, EventProducer, ProducerStreamManager}
import com.omearac.settings.Settings
import com.omearac.shared.AkkaStreams
import com.omearac.shared.KafkaMessages.{ExampleAppEvent, KafkaMessage}

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



object Main extends App with HttpService with AkkaStreams {
  implicit val system = ActorSystem("akka-reactive-kafka-app")
  val log = Logging(system, this.getClass.getName)

  //Start the akka-http server and listen for http requests
  val akkaHttpServer = startAkkaHTTPServer()

  //Create the Producer Stream Manager and Consumer Stream Manager
  val producerStreamManager = system.actorOf(Props(new ProducerStreamManager), "producerStreamManager")
  val consumerStreamManager = system.actorOf(Props(new ConsumerStreamManager), "consumerStreamManager")

  //Create actor to publish event messages to kafka stream.
  val eventProducer = system.actorOf(EventProducer.props, "eventProducer")
  producerStreamManager ! InitializeProducerStream(eventProducer, ExampleAppEvent)

  //Create actor to consume event messages from kafka stream.
  val eventConsumer = system.actorOf(EventConsumer.props, "eventConsumer")
  consumerStreamManager ! InitializeConsumerStream(eventConsumer, ExampleAppEvent)

  //Create actor to publish data messages to kafka stream.
  val dataProducer = system.actorOf(DataProducer.props, "dataProducer")
  producerStreamManager ! InitializeProducerStream(dataProducer, KafkaMessage)

  //Create actor to consume data messages from kafka stream.
  val dataConsumer = system.actorOf(DataConsumer.props, "dataConsumer")
  consumerStreamManager ! InitializeConsumerStream(dataConsumer, KafkaMessage)

  //Shutdown
  shutdownApplication()

  private def startAkkaHTTPServer(): Future[ServerBinding] = {
    val settings = Settings(system).Http
    val host = settings.host

    println(s"Specify the TCP port do you want to host the HTTP server at (e.g. 8001, 8080..etc)? \nHit Return when finished:")
    val portNum = StdIn.readInt()

    println(s"Waiting for http requests at http://$host:$portNum/")
    Http().bindAndHandle(routes, host, portNum)
  }

  private def shutdownApplication(): Unit = {
    scala.sys.addShutdownHook({
      println("Terminating the Application...")
      akkaHttpServer.flatMap(_.unbind())
      system.terminate()
      Await.result(system.whenTerminated, 30 seconds)
      println("Application Terminated")
    })
  }
} 
Example 34
Source File: CodebaseAnalyzerAkkaApp.scala    From CodeAnalyzerTutorial   with Apache License 2.0 5 votes vote down vote up
package tutor

import akka.actor.{ActorRef, ActorSystem}
import tutor.CodebaseAnalyzeAggregatorActor.AnalyzeDirectory

import scala.io.StdIn

object CodebaseAnalyzerAkkaApp extends App {

  val system = ActorSystem("CodebaseAnalyzer")
  val codebaseAnalyzerControllerActor: ActorRef = system.actorOf(CodebaseAnalyzerControllerActor.props())

  var shouldContinue = true
  try {
    while (shouldContinue) {
      println("please input source file folder or :q to quit")
      val input = StdIn.readLine()
      if (input == ":q") {
        shouldContinue = false
      } else {
        codebaseAnalyzerControllerActor ! AnalyzeDirectory(input)
      }
    }
  } finally {
    println("good bye!")
    system.terminate()
  }
} 
Example 35
Source File: Ch01.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
package ch01

import java.util.concurrent.atomic.AtomicLong

import scala.io.StdIn
import scala.util.{Try, Using}

case class User(name: String, surname: String, email: String)

object Ch01 extends App {

  "10".toIntOption
  "TrUe".toBooleanOption

  val bool = "Not True"
  bool.toBooleanOption

  scala.util.Using

  val user = User("John", "Doe", "[email protected]")
  user.productElementNames.mkString(", ")
  user.productElementName(3)

  val tuple = (1, "two", false)

  tuple.productElementNames.mkString(", ")
  tuple.productElementName(1)

  def naiveToJsonString(p: Product): String =
    (for { i <- 0 until p.productArity } yield
      s""""${p.productElementName(i)}": "${p.productElement(i)}"""")
      .mkString("{ ", ", ", " }")

  naiveToJsonString(user)

  import scala.util.chaining._

  import UserDb._
  val userId = 1L
  save(update(getById(userId)))

  getById(userId).pipe(update).pipe(save)

  val doEverything = (getById _).andThen(update).andThen(save)
  doEverything(userId)

  val lastTick = new AtomicLong(0)
  def start(): Unit = lastTick.set(System.currentTimeMillis())
  def measure[A](a: A): Unit = {
    val now = System.currentTimeMillis()
    val before = lastTick.getAndSet(now)
    println(s"$a: ${now - before} ms elapsed")
  }

  start()
  val result = StdIn.readLine().pipe(_.toIntOption).tap(measure)
  val anotherResult = StdIn.readLine().pipe(_.toIntOption).tap(measure)

  final case class Resource(name: String) extends AutoCloseable {
    override def close(): Unit = println(s"Closing $name")
    def lines = List(s"$name line 1", s"$name line 2")
  }
  val List(r1, r2, r3) = List("first", "2", "3").map(Resource)

  val lines: Try[Seq[String]] = for {
    u1 <- Using(r1)
    u2 <- Using(r2)
    u3 <- Using(r3)
  } yield {
    u1.lines ++ u2.lines ++ u3.lines
  }

  println(lines)

}

object UserDb {
  def getById(id: Long): User = ???
  def update(u: User): User = ???
  def save(u: User): Boolean = ???
} 
Example 36
Source File: Server.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package sample

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import scala.io.StdIn

object Server {

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("my-system")
    implicit val executionContext = system.dispatcher

    val bindingFuture = Http().bindAndHandle(Api.routes, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine()
    bindingFuture
      .flatMap(_.unbind())
      .onComplete(_ => system.terminate())
  }
} 
Example 37
Source File: DonutStoreHttpController.scala    From scala-for-beginners   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.donutstore.httpserver

import akka.http.scaladsl.Http
import com.typesafe.scalalogging.LazyLogging

import scala.io.StdIn
import scala.util.{Failure, Success}



trait DonutStoreHttpController extends LazyLogging {
  this: DonutStoreServices =>

  def startAndBind(): Unit = {
    logger.info("Initializing and binding Akka HTTP server")
    val httpServerFuture = Http().bindAndHandle(donutApiRoutes, cfg.httpServer.ip, cfg.httpServer.port)
    httpServerFuture.onComplete {
      case Success(binding) =>
        logger.info(s"Akka Http Server is bound to ${binding.localAddress}")
        logger.info(s"To stop the server, press the [Enter] key in IntelliJ's console.")

      case Failure(e) =>
        logger.error(s"Akka Http server failed to bind to ${cfg.httpServer.ip}:${cfg.httpServer.port}",e)
        system.terminate()
    }

    // pressing enter key will kill the server
    StdIn.readLine()
    for {
      serverBinding <- httpServerFuture
      _             <- serverBinding.unbind()
      terminated    <- system.terminate()
    } yield logger.info(s"Akka Http server was terminated = $terminated")
  }
} 
Example 38
Source File: DonutStoreHttpController.scala    From scala-for-beginners   with Apache License 2.0 5 votes vote down vote up
package com.allaboutscala.donutstore.httpserver


import akka.http.scaladsl.Http
import com.typesafe.scalalogging.LazyLogging

import scala.io.StdIn
import scala.util.{Failure, Success}



trait DonutStoreHttpController extends LazyLogging {
  this: DonutStoreServices =>

  def startAndBind(): Unit = {
    logger.info("Initializing and binding Akka HTTP server")
    val httpServerFuture = Http().bindAndHandle(donutApiRoutes, cfg.httpServer.ip, cfg.httpServer.port)
    httpServerFuture.onComplete {
      case Success(binding) =>
        logger.info(s"Akka Http Server is bound to ${binding.localAddress}")
        logger.info(s"To stop the server, press the [Enter] key in IntelliJ's console.")

      case Failure(e) =>
        logger.error(s"Akka Http server failed to bind to ${cfg.httpServer.ip}:${cfg.httpServer.port}",e)
        system.terminate()
    }

    // pressing enter key will kill the server
    StdIn.readLine()
    for {
      serverBinding <- httpServerFuture
      _             <- serverBinding.unbind()
      terminated    <- system.terminate()
    } yield logger.info(s"Akka Http server was terminated = $terminated")
  }
} 
Example 39
Source File: SetSessionScala.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.example.session

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.softwaremill.session.CsrfDirectives._
import com.softwaremill.session.CsrfOptions._
import com.softwaremill.session.SessionDirectives._
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session._
import com.typesafe.scalalogging.StrictLogging

import scala.io.StdIn

object SetSessionScala extends App with StrictLogging {
  implicit val system = ActorSystem("example")
  implicit val materializer = ActorMaterializer()

  import system.dispatcher

  val sessionConfig = SessionConfig.default(
    "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe")
  implicit val sessionManager = new SessionManager[MyScalaSession](sessionConfig)
  implicit val refreshTokenStorage = new InMemoryRefreshTokenStorage[MyScalaSession] {
    def log(msg: String) = logger.info(msg)
  }

  def mySetSession(v: MyScalaSession) = setSession(refreshable, usingCookies, v)

  val myRequiredSession = requiredSession(refreshable, usingCookies)
  val myInvalidateSession = invalidateSession(refreshable, usingCookies)

  val routes =
    randomTokenCsrfProtection(checkHeader) {
      pathPrefix("api") {
        path("do_login") {
          post {
            entity(as[String]) { body =>
              logger.info(s"Logging in $body")
              mySetSession(MyScalaSession(body)) {
                setNewCsrfToken(checkHeader) { ctx =>
                  ctx.complete("ok")
                }
              }
            }
          }
        }
      }
    }

  val bindingFuture = Http().bindAndHandle(routes, "localhost", 8080)

  println("Server started, press enter to stop. Visit http://localhost:8080 to see the demo.")
  StdIn.readLine()

  import system.dispatcher

  bindingFuture
    .flatMap(_.unbind())
    .onComplete { _ =>
      system.terminate()
      println("Server stopped")
    }
} 
Example 40
Source File: SessionInvalidationScala.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.example.session

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.softwaremill.session.SessionDirectives._
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session._
import com.typesafe.scalalogging.StrictLogging

import scala.io.StdIn

object SessionInvalidationScala extends App with StrictLogging {
  implicit val system = ActorSystem("example")
  implicit val materializer = ActorMaterializer()

  import system.dispatcher

  val sessionConfig = SessionConfig.default(
    "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe")
  implicit val sessionManager = new SessionManager[MyScalaSession](sessionConfig)
  implicit val refreshTokenStorage = new InMemoryRefreshTokenStorage[MyScalaSession] {
    def log(msg: String) = logger.info(msg)
  }

  def mySetSession(v: MyScalaSession) = setSession(refreshable, usingCookies, v)

  val myRequiredSession = requiredSession(refreshable, usingCookies)
  val myInvalidateSession = invalidateSession(refreshable, usingCookies)

  val routes =
    path("logout") {
      post {
        myRequiredSession { session =>
          myInvalidateSession { ctx =>
            logger.info(s"Logging out $session")
            ctx.complete("ok")
          }
        }
      }
    }

  val bindingFuture = Http().bindAndHandle(routes, "localhost", 8080)

  println("Server started, press enter to stop. Visit http://localhost:8080 to see the demo.")
  StdIn.readLine()

  import system.dispatcher

  bindingFuture
    .flatMap(_.unbind())
    .onComplete { _ =>
      system.terminate()
      println("Server stopped")
    }
} 
Example 41
Source File: ScalaExample.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.example

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.softwaremill.example.session.MyScalaSession
import com.softwaremill.session.CsrfDirectives._
import com.softwaremill.session.CsrfOptions._
import com.softwaremill.session.SessionDirectives._
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session._
import com.typesafe.scalalogging.StrictLogging

import scala.io.StdIn

object Example extends App with StrictLogging {
  implicit val system = ActorSystem("example")
  implicit val materializer = ActorMaterializer()

  import system.dispatcher

  val sessionConfig = SessionConfig.default(
    "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe")
  implicit val sessionManager = new SessionManager[MyScalaSession](sessionConfig)
  implicit val refreshTokenStorage = new InMemoryRefreshTokenStorage[MyScalaSession] {
    def log(msg: String) = logger.info(msg)
  }

  def mySetSession(v: MyScalaSession) = setSession(refreshable, usingCookies, v)

  val myRequiredSession = requiredSession(refreshable, usingCookies)
  val myInvalidateSession = invalidateSession(refreshable, usingCookies)

  val routes =
    path("") {
      redirect("/site/index.html", Found)
    } ~
      randomTokenCsrfProtection(checkHeader) {
        pathPrefix("api") {
          path("do_login") {
            post {
              entity(as[String]) { body =>
                logger.info(s"Logging in $body")

                mySetSession(MyScalaSession(body)) {
                  setNewCsrfToken(checkHeader) { ctx =>
                    ctx.complete("ok")
                  }
                }
              }
            }
          } ~
            // This should be protected and accessible only when logged in
            path("do_logout") {
              post {
                myRequiredSession { session =>
                  myInvalidateSession { ctx =>
                    logger.info(s"Logging out $session")
                    ctx.complete("ok")
                  }
                }
              }
            } ~
            // This should be protected and accessible only when logged in
            path("current_login") {
              get {
                myRequiredSession { session => ctx =>
                  logger.info("Current session: " + session)
                  ctx.complete(session.username)
                }
              }
            }
        } ~
          pathPrefix("site") {
            getFromResourceDirectory("")
          }
      }

  val bindingFuture = Http().bindAndHandle(routes, "localhost", 8080)

  println("Server started, press enter to stop. Visit http://localhost:8080 to see the demo.")
  StdIn.readLine()

  import system.dispatcher

  bindingFuture
    .flatMap(_.unbind())
    .onComplete { _ =>
      system.terminate()
      println("Server stopped")
    }
} 
Example 42
Source File: Launcher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.todo

import io.udash.logging.CrossLogging
import io.udash.todo.jetty.ApplicationServer

import scala.io.StdIn

object Launcher extends CrossLogging {
  def main(args: Array[String]): Unit = {
    val server = new ApplicationServer(8080, "frontend/target/UdashStatics/WebContent")
    server.start()
    logger.info(s"Application started...")

    // wait for user input and then stop the server
    logger.info(s"Click `Enter` to close application...")
    StdIn.readLine()
    server.stop()
  }
} 
Example 43
Source File: Launcher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.rest

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import io.udash.demos.rest.api.PhoneBookWebService
import io.udash.logging.CrossLogging

import scala.io.StdIn

object Launcher extends CrossLogging {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("my-system")
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher

    val service = new PhoneBookWebService
    val bindingFuture = Http().bindAndHandle(service.route, "localhost", 8080)

    logger.info(s"Server online at http://localhost:8080/\nPress Enter to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }
} 
Example 44
Source File: Launcher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.files

import io.udash.demos.files.jetty.ApplicationServer
import io.udash.logging.CrossLogging

import scala.io.StdIn

object Launcher extends CrossLogging {
  def main(args: Array[String]): Unit = {
    val server = new ApplicationServer(8080, "frontend/target/UdashStatics/WebContent")
    server.start()
    logger.info(s"Application started...")

    // wait for user input and then stop the server
    logger.info(s"Click `Enter` to close application...")
    StdIn.readLine()
    server.stop()
  }
} 
Example 45
Source File: ComposeFreeMonads.scala    From Freasy-Monad   with MIT License 5 votes vote down vote up
package examples.scalaz

import scalaz._
import scalaz.Id.Id
import freasymonad.scalaz.free
import scala.collection.mutable.ListBuffer
import scala.io.StdIn
import scala.language.{higherKinds, reflectiveCalls}

// example based off https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/freemonad.md#composing-free-monads-adts
object ComposeFreeMonads extends App {

  @free trait Interact {
    type InteractF[A] = Free[Adt, A]
    sealed trait Adt[A]
    def ask(prompt: String): InteractF[String]
    def tell(msg: String): InteractF[Unit]
  }

  @free trait DataSource {
    type DataSourceF[A] = Free[Adt, A]
    sealed trait Adt[A]
    def addCat(a: String): DataSourceF[Unit]
    def getAllCats: DataSourceF[List[String]]
    def addAndGetAllCats(a: String): DataSourceF[List[String]] =
     for {
       _ <- addCat(a)
       c <- getAllCats
     } yield c
  }

  type ScalazApp[A] = Coproduct[DataSource.Adt, Interact.Adt, A]

  // program1 and program2 are the same.
  // This library lets you choose which style you like.

  def program1(implicit I: Interact.Injects[ScalazApp], D : DataSource.Injects[ScalazApp]): Free[ScalazApp, Unit] = {
    import I._, D._
    for {
      cat  <- ask("What's the kitty's name?")
      cats <- addAndGetAllCats(cat)
      _    <- tell(cats.toString)
    } yield ()
  }

  val program2: Free[ScalazApp, Unit] = {
    import Interact.injectOps._, DataSource.injectOps._
    for {
      cat  <- ask[ScalazApp]("What's the kitty's name?")
      cats <- addAndGetAllCats[ScalazApp](cat)
      _    <- tell[ScalazApp](cats.toString)
    } yield ()
  }

  val consoleCats = new Interact.Interp[Id] {
    def ask(prompt: String): Id[String] = {
      println(prompt)
      StdIn.readLine()
    }
    def tell(msg: String): Id[Unit] = println(msg)
  }

  val inMemoryDatasource = new DataSource.Interp[Id] {
    private[this] val memDataSet = new ListBuffer[String]
    def addCat(a: String): Id[Unit] = memDataSet.append(a)
    def getAllCats: Id[List[String]] = memDataSet.toList
  }

  // scalaz lacks a convenient `or` atm
  // https://github.com/scalaz/scalaz/issues/1222
  implicit class NaturalTransformationOps[F[_], G[_]](val self: F ~> G) extends AnyVal {
    def or[H[_]](g: H ~> G): ({type λ[α] = Coproduct[F, H, α]})#λ ~> G =
      new (({type λ[α] = Coproduct[F, H, α]})#λ ~> G) {
        def apply[A](fa: Coproduct[F, H, A]): G[A] = fa.run.fold(self.apply, g.apply)
      }
  }

  val interpreter = inMemoryDatasource or consoleCats

  program1.foldMap(interpreter)
  program2.foldMap(interpreter)
} 
Example 46
Source File: ActorMaterializerLifecycleDemo.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.basic

import akka.actor.{ Actor, ActorSystem, Props }
import akka.stream.{ ActorMaterializer, Materializer }
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source

import scala.io.StdIn
import scala.util.{ Failure, Success }


class RunWithItself extends Actor {
  implicit val mat = ActorMaterializer()

  Source.maybe.runWith(Sink.onComplete {
    case Success(done) => println(s"$self Complated: $done")
    case Failure(e)    => println(s"$self Failed: ${e.getMessage}")
  })

  override def receive: Receive = {
    case "boom" => context.stop(self)
  }
}

class RunForever(implicit val mat: Materializer) extends Actor {
  Source.maybe.runWith(Sink.onComplete {
    case Success(done) => println(s"$self Complated: $done")
    case Failure(e)    => println(s"$self Failed: ${e.getMessage}")
  })

  override def receive: Receive = {
    case "boom" => context.stop(self)
  }
}

object ActorMaterializerLifecycleDemo extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  system.actorOf(Props[RunWithItself], "with-itself") ! "boom"
  val runForever = system.actorOf(Props(new RunForever), "run-forever")
  //  Thread.sleep(100)
  //  mat.shutdown()
  //  Thread.sleep(200)
  runForever ! "boom"

  StdIn.readLine()
  system.terminate()
} 
Example 47
Source File: LeagueServiceImpl.scala    From eventsourcing-intro   with Apache License 2.0 5 votes vote down vote up
package eu.reactivesystems.league.impl

import akka.Done
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import eu.reactivesystems.league.api.{Club, Game, LeagueService}

import scala.concurrent.Future
import scala.io.StdIn

object LeagueServiceImpl extends LeagueService {

  implicit val system = ActorSystem("league-actorsystem")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  override def addClub(leagueId: String, club: Club): Future[Done] =
    // get sharded instance
    // send message using ask
    // process result
    Future.successful(Done)

  override def addGame(leagueId: String, game: Game): Future[Done] =
    Future.successful(Done)

  override def changeGame(leagueId: String, game: Game): Future[Done] =
    Future.successful(Done)

  def main(args: Array[String]): Unit = {
    val port =
      system.settings.config.getInt("eu.reactivesystems.league.http.port")
    val bindingFuture = Http().bindAndHandle(routes, "localhost", port)

    println(
      s"Server online at http://localhost:$port/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }

} 
Example 48
Source File: Synthesizer.scala    From scalaz-reactive   with Apache License 2.0 5 votes vote down vote up
package scalaz.reactive.examples

import scalaz.reactive._
import scalaz.zio.{ App, IO }

import scala.io.StdIn


object Synthesizer extends App {

  type Octave = Int

  case class Pitch(val sign: String)
  object PA extends Pitch("a")
  object PB extends Pitch("b")
  object PC extends Pitch("c")
  object PD extends Pitch("d")
  object PE extends Pitch("e")
  object PF extends Pitch("f")
  object PG extends Pitch("g")

  case class Note(octave: Octave, pitch: Pitch)

  val table =
    Map(
      'a' -> PA,
      'b' -> PB,
      'b' -> PB,
      'c' -> PC,
      'd' -> PD,
      'e' -> PE,
      'f' -> PF,
      'g' -> PG
    )

  def build(eKey: Event[Char]) = {
//    val ePitch: Event[Pitch] = Event.joinMaybes(
//      eKey.map(table.get(_))
//    )

    val eOctChange: Event[Octave => Octave] = Event.joinMaybes(
      eKey
        .map { k =>
          k match {
            case '+' => Some((x: Octave) => x + 1)
            case '-' => Some((x: Octave) => x - 1)
            case _   => None
          }
        }
    )

    val bOctave: Behaviour[Octave] = Behaviour(
      Reactive(
        TimeFun.K(0),
        Event.accumE(0)(eOctChange).map((x: Octave) => TimeFun.K(x))
      )
    )

//    val bPitch: Behaviour[Pitch] = Behaviour(
//      Reactive(TimeFun.K(PA), ePitch.map(p => TimeFun.K(p)))
//    )

//    val bNote = (bOctave |@| bPitch) { Note.apply _ }

    bOctave

  }

  def run(args: List[String]): IO[Nothing, ExitStatus] =
    myAppLogic.attempt.map(_.fold(_ => 1, _ => 0)).map(ExitStatus.ExitNow(_))

  def eKey(): Event[Char] = {
    val nextChar: IO[Void, Char] = IO.sync {
      println(s"Waiting for input")
      StdIn.readChar()
    }

    Event(nextChar.flatMap { c =>
      Time.now.map((_, Reactive(c, eKey)))
    })
  }

  def myAppLogic: IO[Void, Unit] = {

    val toSink: Behaviour[Octave] = build(eKey())

    Sink.sinkB(
      toSink,
      (tn: TimeFun[Octave]) =>
        Time.now.map { t =>
          println(s"Octave is ${tn.apply(t)}")
        }
    )
  }

} 
Example 49
Source File: RTSPub.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
import cmwell.domain._
import cmwell.domain.FString
import cmwell.rts.{Rule, Publisher}
import k.grid.{GridConnection, Grid}
import scala.io.StdIn
import domain.testUtil.InfotonGenerator.genericSystemFields


object RTSPub extends App {
  // java -Done-jar.main.class=RTSPub -jar cmwell-rts-ng_2.10-1.2.1-SNAPSHOT-one-jar.jar
  val ip : String = "127.0.0.1"
  // start grid
  //Grid.roles = Set("publisher")
  Grid.setGridConnection(GridConnection(memberName = "rts", hostName = ip, seeds = Set("127.0.0.1:2551"), port = 0))
  Grid.joinClient
  //Grid.join(Set("127.0.0.1"),Set("subscriber"))
  Publisher.init
  // scalastyle:off
  println("Press enter publisher.")
  // scalastyle:on
  StdIn.readLine()
  // scalastyle:off
  println("-----------------------------------------")
  // scalastyle:on
  (1 to 9).foreach{ i =>
    val m : Map[String , Set[FieldValue]]= Map("name" -> Set(FString("gal"), FString("yoav")), "types" -> Set(FString("123"), FInt(123)))
    val ii = ObjectInfoton(genericSystemFields.copy(path = "/cmt/cm/command-test/objinfo_" + i), m)
    Publisher.publish(Vector(ii))
  }
  // scalastyle:off
  println("-----------------------------------------")
  // scalastyle:on
  StdIn.readLine()
  Grid.shutdown


} 
Example 50
Source File: RTSPub1.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
import domain.testUtil.InfotonGenerator.genericSystemFields
import cmwell.domain._
import cmwell.domain.FString
import cmwell.rts.Publisher
import k.grid.{GridConnection, Grid}

import scala.io.StdIn


object RTSPub1 extends App {

  // start grid

//  Grid.roles = Set("publisher")

  Grid.setGridConnection(GridConnection(memberName = "rts", hostName = "127.0.0.1", seeds = Set("127.0.0.1:2551"), port = 0))
  Grid.joinClient
  //Grid.join(Set("127.0.0.1"),Set("subscriber"))
  Publisher.init
  // scalastyle:off
  println("Press enter publisher.")
  // scalastyle:on
  StdIn.readLine()
  // scalastyle:off
  println("-----------------------------------------")
  // scalastyle:on
  (1 to 10).foreach{ i =>
    val m : Map[String , Set[FieldValue]]= Map("name" -> Set(FString("gal"), FString("yoav")), "types" -> Set(FString("123"), FInt(123)))
    val ii = ObjectInfoton(genericSystemFields.copy(path = "/cmt/news/command-test/objinfo_"+i), m)
    Publisher.publish(Vector(ii))
  }
  // scalastyle:off
  println("-----------------------------------------")
  // scalastyle:on
  StdIn.readLine()
  Grid.shutdown
} 
Example 51
Source File: RTSSub1.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
import cmwell.rts.{Rule, PathFilter, Subscriber}
import k.grid.{GridConnection, Grid}
import scala.io.StdIn


object RTSSub1 extends App {


//  Grid.roles = Set("subscriber")
  Grid.setGridConnection(GridConnection(memberName = "rts", hostName = "127.0.0.1", seeds = Set("127.0.0.1:2551"), port = 0))
  Grid.joinClient
  Subscriber.init
  Thread.sleep(5000)
  // scalastyle:off
  println("-----------------------------------------")
  // now lets subscribe
  println("Press enter subscriber.")
  // scalastyle:on
  StdIn.readLine()
//  Subscriber.subscribe("sub02", Rule("/cmt/cm/command-test", true))
  //Subscriber.subscribe("sub02", Rule())
  // scalastyle:off
  println("wait.")
  // scalastyle:on
  StdIn.readLine()
} 
Example 52
Source File: CustomerApp.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.{ActorSelection, ActorSystem, Address, RootActorPath}
import akka.event.Logging

import scala.annotation.tailrec
import scala.concurrent.Await
import scala.concurrent.duration.{Duration, FiniteDuration, MILLISECONDS => Millis}
import scala.io.StdIn

object CustomerApp {

  
  protected def createCustomer(count: Int, odds: Int, tolerance: Int): Unit = {
    val selection: ActorSelection  =
        system.actorSelection(
        RootActorPath(rareBooksAddress) /
        "user" / "rare-books")

    selection.resolveOne(resolveTimeout).onComplete {
      case scala.util.Success(rareBooks) =>
        for (_ <- 1 to count)
          system.actorOf(Customer.props(rareBooks, odds, tolerance))
      case scala.util.Failure(ex) =>
        log.error(ex, ex.getMessage)
    }
  }
} 
Example 53
Source File: RareBooksApp.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library


import akka.actor.{ ActorRef, ActorSystem }
import akka.event.Logging
import scala.annotation.tailrec
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.io.StdIn

object RareBooksApp {

  
  protected def createRareBooks(): ActorRef = {
    system.actorOf(RareBooks.props, "rare-books")
  }

  def run(): Unit = {
    log.warning(f"{} running%nWaiting for customer requests.", getClass.getSimpleName)
    commandLoop()
    Await.ready(system.whenTerminated, Duration.Inf)
  }

  @tailrec
  private def commandLoop(): Unit =
    Command(StdIn.readLine()) match {
      case Command.Customer(count, odds, tolerance) =>
        log.warning(s"Enter customer commands from the customer app prompt.")
        commandLoop()
      case Command.Quit =>
        system.terminate()
      case Command.Unknown(command) =>
        log.warning(s"Unknown command $command")
        commandLoop()
    }
} 
Example 54
Source File: AkkaHttpServerTemplate.scala    From akka-http-circe-json-template   with Apache License 2.0 5 votes vote down vote up
package com.vitorsvieira.http.server

import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.{ IncomingConnection, ServerBinding }
import akka.http.scaladsl.server.Route._
import akka.stream.scaladsl.{ Sink, Source }
import com.vitorsvieira.http.config.ServerSettingsTemplate
import com.vitorsvieira.http.routes.AkkaHttpRoutesTemplate

import scala.concurrent.Future
import scala.io.StdIn

object AkkaHttpServerTemplate extends App {

  import ServerSettingsTemplate._

  val server: Source[IncomingConnection, Future[ServerBinding]] =
    Http(actorSystem).bind(httpInterface, httpPort)

  log.info(s"\nAkka HTTP Server - Version ${actorSystem.settings.ConfigVersion} - running at http://$httpInterface:$httpPort/")

  val handler: Future[ServerBinding] =
    server
      .to(
        Sink.foreach {
          connection ⇒
            connection.handleWithAsyncHandler(asyncHandler(AkkaHttpRoutesTemplate.availableRoutes))
        }
      )
      .run()

  handler.failed.foreach { case ex: Exception ⇒ log.error(ex, "Failed to bind to {}:{}", httpInterface, httpPort) }

  StdIn.readLine(s"\nPress RETURN to stop...")

  handler
    .flatMap(binding ⇒ binding.unbind())
    .onComplete(_ ⇒ actorSystem.terminate())
} 
Example 55
Source File: MergeHubDemo.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.dynamichub

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ MergeHub, RunnableGraph, Sink, Source }
import com.typesafe.scalalogging.StrictLogging

import scala.io.StdIn

object MergeHubDemo extends App with StrictLogging {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  // A simple consumer that will print to the console for now
  val consumer = Sink.foreach[String](v => logger.info(s"consumer: $v"))

  // Attach a MergeHub Source to the consumer. This will materialize to a
  // corresponding Sink.
  val runnableGraph: RunnableGraph[Sink[String, NotUsed]] =
    MergeHub.source[String](perProducerBufferSize = 16).to(consumer)

  // By running/materializing the consumer we get back a Sink, and hence
  // now have access to feed elements into it. This Sink can be materialized
  // any number of times, and every element that enters the Sink will
  // be consumed by our consumer.
  val toConsumer: Sink[String, NotUsed] = runnableGraph.run()

  // Feeding two independent sources into the hub.
  Source.single("Hello!").runWith(toConsumer)
  Source.single("Hub!").runWith(toConsumer)

  StdIn.readLine()
  system.terminate()
} 
Example 56
Source File: SimplePublishSubscribe.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.dynamichub

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, KillSwitches, UniqueKillSwitch }
import akka.stream.scaladsl.{ BroadcastHub, Flow, Keep, MergeHub, Sink, Source }
import com.typesafe.scalalogging.StrictLogging

import scala.io.StdIn
import scala.concurrent.duration._

object SimplePublishSubscribe extends App with StrictLogging {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  import system.dispatcher

  val (sink, source) =
    MergeHub.source[String](perProducerBufferSize = 16).toMat(BroadcastHub.sink(bufferSize = 256))(Keep.both).run()

  source.runWith(Sink.ignore)

  val busFlow: Flow[String, String, UniqueKillSwitch] = Flow
    .fromSinkAndSource(sink, source)
    .joinMat(KillSwitches.singleBidi[String, String])(Keep.right)
    .backpressureTimeout(3.seconds)

  val switch: UniqueKillSwitch =
    Source.repeat("Hello world!").viaMat(busFlow)(Keep.right).to(Sink.foreach(v => logger.info(s"switch: $v"))).run()

  Thread.sleep(200)
  switch.shutdown()

  StdIn.readLine()
  system.terminate()
} 
Example 57
Source File: BufferProblem.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.buffer
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ GraphDSL, RunnableGraph, Sink, Source, ZipWith }
import akka.stream.{ ActorMaterializer, Attributes, ClosedShape }

import scala.concurrent.duration._
import scala.io.StdIn

object BufferProblem extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  case class Tick()

  val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b =>
    import akka.stream.scaladsl.GraphDSL.Implicits._

    // this is the asynchronous stage in this graph
    val zipper =
      b.add(ZipWith[Tick, Int, Int]((tick, count) => count).async.addAttributes(Attributes.inputBuffer(1, 1)))
    // 用默认缓冲区设置时将只打印 1
    //    val zipper = b.add(ZipWith[Tick, Int, Int]((tick, count) => count).async)

    Source.tick(initialDelay = 3.second, interval = 3.second, Tick()) ~> zipper.in0

    Source
      .tick(initialDelay = 1.second, interval = 1.second, "message!")
      .conflateWithSeed(seed = (_) => 1)((count, _) => count + 1) ~> zipper.in1

    zipper.out ~> Sink.foreach(println)
    ClosedShape
  })

  g.run()

  StdIn.readLine()
  system.terminate()
} 
Example 58
Source File: ExtrapolateExpand.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.buffer

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Flow, Source }

import scala.io.StdIn

object ExtrapolateExpand extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  //  val lastFlow = Flow[Double].extrapolate(Iterator.continually(_))
  //  Source((1 to 10).map(_.toDouble)).via(lastFlow).runWith(Sink.foreach(println))

  //  val initial = 2.0
  //  val seedFlow = Flow[Double].extrapolate(Iterator.continually(_), Some(initial))
  //  Source((1 to 10).map(_.toDouble)).via(seedFlow).runWith(Sink.foreach(println))

  //  val driftFlow = Flow[Double].map(_ -> 0).extrapolate[(Double, Int)] { case (i, _) => Iterator.from(1).map(i -> _) }
  //  Source((1 to 10).map(_.toDouble)).via(driftFlow).runForeach(println)

  val driftFlow = Flow[Double].expand(i => Iterator.from(0).map(i -> _))
  Source((1 to 10).map(_.toDouble)).via(driftFlow).runForeach(println)

  StdIn.readLine()
  system.terminate()
} 
Example 59
Source File: BufferExample.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package example.akkastream.buffer

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Sink, Source }

import scala.io.StdIn

object BufferExample extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  Source(1 to 3)
    .map { i =>
      println(s"A: $i"); i
    }
    .async
    .map { i =>
      println(s"B: $i"); i
    }
    .async
    .map { i =>
      println(s"C: $i"); i
    }
    .async
    .runWith(Sink.ignore)

  Thread.sleep(1000)
  println("------------------------------------")
  Source(1 to 3)
    .map { i =>
      println(s"A: $i"); i
    }
    .map { i =>
      println(s"B: $i"); i
    }
    .map { i =>
      println(s"C: $i"); i
    }
    .runWith(Sink.ignore)

  StdIn.readLine()
  system.terminate()
}