Ejemplo n.º 1
0
    public void streamFile()
        throws IOException, FileNotFoundException, InterruptedException, ExecutionException {
      String url = "http://example.com";
      // #stream-to-file
      File file = File.createTempFile("stream-to-file-", ".txt");
      FileOutputStream outputStream = new FileOutputStream(file);

      // Make the request
      CompletionStage<StreamedResponse> futureResponse = ws.url(url).setMethod("GET").stream();

      CompletionStage<File> downloadedFile =
          futureResponse.thenCompose(
              res -> {
                Source<ByteString, ?> responseBody = res.getBody();

                // The sink that writes to the output stream
                Sink<ByteString, scala.concurrent.Future<scala.runtime.BoxedUnit>> outputWriter =
                    Sink.<ByteString>foreach(bytes -> outputStream.write(bytes.toArray()));

                // Converts the materialized Scala Future into a Java8 `CompletionStage`
                Sink<ByteString, CompletionStage<?>> convertedOutputWriter =
                    outputWriter.mapMaterializedValue(FutureConverters::toJava);

                // materialize and run the stream
                CompletionStage<File> result =
                    responseBody
                        .runWith(convertedOutputWriter, materializer)
                        .whenComplete(
                            (value, error) -> {
                              // Close the output stream whether there was an error or not
                              try {
                                outputStream.close();
                              } catch (IOException e) {
                              }
                            })
                        .thenApply(v -> file);
                return result;
              });
      // #stream-to-file
      downloadedFile.toCompletableFuture().get();
      file.delete();
    }
Ejemplo n.º 2
0
    public void streamSimpleRequest() {
      String url = "http://example.com";
      // #stream-count-bytes
      // Make the request
      CompletionStage<StreamedResponse> futureResponse = ws.url(url).setMethod("GET").stream();

      CompletionStage<Long> bytesReturned =
          futureResponse.thenCompose(
              res -> {
                Source<ByteString, ?> responseBody = res.getBody();

                // Count the number of bytes returned
                Sink<ByteString, scala.concurrent.Future<Long>> bytesSum =
                    Sink.fold(0L, (total, bytes) -> total + bytes.length());

                // Converts the materialized Scala Future into a Java8 `CompletionStage`
                Sink<ByteString, CompletionStage<Long>> convertedBytesSum =
                    bytesSum.mapMaterializedValue(FutureConverters::toJava);

                return responseBody.runWith(convertedBytesSum, materializer);
              });
      // #stream-count-bytes
    }