Add examples for asInputStream and asOutputStream (#29830)
This commit is contained in:
parent
385e075fdc
commit
e290130386
4 changed files with 100 additions and 7 deletions
|
|
@ -5,16 +5,14 @@
|
|||
package docs.stream.operators.converters
|
||||
|
||||
// #import
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream }
|
||||
|
||||
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.stream.scaladsl.{ Flow, Keep, Sink, Source, StreamConverters }
|
||||
import akka.util.ByteString
|
||||
|
||||
import scala.util.Random
|
||||
// #import
|
||||
import akka.testkit.AkkaSpec
|
||||
import org.scalatest.concurrent.Futures
|
||||
|
|
@ -45,4 +43,31 @@ class ToFromJavaIOStreams extends AkkaSpec with Futures {
|
|||
|
||||
}
|
||||
|
||||
"demonstrate usage as java.io.InputStream" in {
|
||||
//#asJavaInputStream
|
||||
val toUpperCase: Flow[ByteString, ByteString, NotUsed] = Flow[ByteString].map(_.map(_.toChar.toUpper.toByte))
|
||||
val source: Source[ByteString, NotUsed] = Source.single(ByteString("some random input"))
|
||||
val sink: Sink[ByteString, InputStream] = StreamConverters.asInputStream()
|
||||
|
||||
val inputStream: InputStream = source.via(toUpperCase).runWith(sink)
|
||||
//#asJavaInputStream
|
||||
inputStream.read() should be('S')
|
||||
inputStream.close()
|
||||
}
|
||||
|
||||
"demonstrate usage as java.io.OutputStream" in {
|
||||
//#asJavaOutputStream
|
||||
val source: Source[ByteString, OutputStream] = StreamConverters.asOutputStream()
|
||||
val sink: Sink[ByteString, Future[ByteString]] = Sink.fold[ByteString, ByteString](ByteString.empty)(_ ++ _)
|
||||
|
||||
val (outputStream, result): (OutputStream, Future[ByteString]) =
|
||||
source.toMat(sink)(Keep.both).run()
|
||||
|
||||
//#asJavaOutputStream
|
||||
val bytesArray = Array.fill[Byte](3)(Random.nextInt(1024).asInstanceOf[Byte])
|
||||
outputStream.write(bytesArray)
|
||||
outputStream.close()
|
||||
result.futureValue should be(ByteString(bytesArray))
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue