Docs: examples for io streams with StreamConverters (#28746)

This commit is contained in:
Ignasi Marimon-Clos 2020-03-27 09:56:59 +01:00 committed by GitHub
parent b40873dc10
commit f683241c40
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 191 additions and 17 deletions

View file

@ -0,0 +1,48 @@
/*
* Copyright (C) 2020 Lightbend Inc. <https://www.lightbend.com>
*/
package docs.stream.operators.converters
// #import
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import akka.NotUsed
import akka.stream.IOResult
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import akka.stream.scaladsl.StreamConverters
import akka.util.ByteString
// #import
import akka.testkit.AkkaSpec
import org.scalatest.concurrent.Futures
import scala.concurrent.Future
class ToFromJavaIOStreams extends AkkaSpec with Futures {
"demonstrate conversion from java.io.streams" in {
//#tofromJavaIOStream
val bytes = "Some random input".getBytes
val inputStream = new ByteArrayInputStream(bytes)
val outputStream = new ByteArrayOutputStream()
val source: Source[ByteString, Future[IOResult]] = StreamConverters.fromInputStream(() => inputStream)
val toUpperCase: Flow[ByteString, ByteString, NotUsed] = Flow[ByteString].map(_.map(_.toChar.toUpper.toByte))
val sink: Sink[ByteString, Future[IOResult]] = StreamConverters.fromOutputStream(() => outputStream)
val eventualResult = source.via(toUpperCase).runWith(sink)
//#tofromJavaIOStream
whenReady(eventualResult) { _ =>
outputStream.toByteArray.map(_.toChar).mkString should be("SOME RANDOM INPUT")
}
}
}