Add examples for asInputStream and asOutputStream (#29830)

This commit is contained in:
Nitika Agarwal 2020-11-30 15:09:14 +05:30 committed by GitHub
parent 385e075fdc
commit e290130386
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 100 additions and 7 deletions

View file

@ -6,9 +6,10 @@ package jdocs.stream.operators.converters;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.japi.Pair;
import akka.stream.IOResult;
import akka.stream.Materializer;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Keep;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.stream.javadsl.StreamConverters;
@ -21,12 +22,16 @@ import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static akka.util.ByteString.emptyByteString;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class ToFromJavaIOStreams extends AbstractJavaTest {
@ -80,4 +85,51 @@ public class ToFromJavaIOStreams extends AbstractJavaTest {
"SOME RANDOM INPUT",
new String(((ByteArrayOutputStream) outputStream).toByteArray(), charset));
}
@Test
public void demonstrateAsJavaInputStream() throws Exception {
// #asJavaInputStream
Charset charset = Charset.defaultCharset();
Flow<ByteString, ByteString, NotUsed> toUpperCase =
Flow.<ByteString>create()
.map(
bs -> {
String str = bs.decodeString(charset).toUpperCase();
return ByteString.fromString(str, charset);
});
final Sink<ByteString, InputStream> sink = StreamConverters.asInputStream();
final InputStream stream =
Source.single(ByteString.fromString("Some random input"))
.via(toUpperCase)
.runWith(sink, system);
// #asJavaInputStream
byte[] a = new byte[17];
stream.read(a);
assertArrayEquals("SOME RANDOM INPUT".getBytes(), a);
}
@Test
public void demonstrateAsJavaOutputStream() throws Exception {
// #asJavaOutputStream
final Source<ByteString, OutputStream> source = StreamConverters.asOutputStream();
final Sink<ByteString, CompletionStage<ByteString>> sink =
Sink.fold(emptyByteString(), (ByteString arg1, ByteString arg2) -> arg1.concat(arg2));
final Pair<OutputStream, CompletionStage<ByteString>> output =
source.toMat(sink, Keep.both()).run(system);
// #asJavaOutputStream
byte[] bytesArray = new byte[3];
output.first().write(bytesArray);
output.first().close();
final byte[] expected =
output.second().toCompletableFuture().get(5, TimeUnit.SECONDS).toArray();
assertArrayEquals(expected, bytesArray);
}
}