Serve result from java.io.OutputStream

I’m using a PDF library which writes data into an OutputStream. How can I serve this outputstream as a Result?

I used stuff from play-iteratees for this, but it seems that it no longer exists for Scala 2.13. I guess there might be something in StreamConverters, but I can’t figure out how to use it.

As far I I’m able to figure out

StreamConverters.asOutputStream().mapMaterializedValue { os => myRenderMethod(os) }

should be a possible solution.

However, that gives:

Rendering of response failed because response entity stream materialization failed with 'java.util.concurrent.TimeoutException'

That is with iText. When using the same technique for rendering Excel files using Apache POI I get a different error, but the common thing is that neither works.

So I’ve resorted to simply using a ByteArrayOutputStream and just serving it with .toByteArray. Which works perfectly.

This is an example in Java, not Scala, but this is how you “convert” an OutputStream to an InputStream.

	public static InputStream foo(Consumer<OutputStream> outputStreamConsumer) throws IOException {
		final PipedInputStream pipedIn = new PipedInputStream();
		final PipedOutputStream pipedOut = new PipedOutputStream(pipedIn);
		new Thread(() -> {
			try {
				outputStreamConsumer.accept(pipedOut);
			} catch (Exception e) {
				// uh oh
			}
		}).start();
		return pipedIn;
	}

It obviously needs to be polished up but that’s the basic idea of how you do it. Once you have an InputStream, it should be easy to pipe it to Play.