Search code examples
javajaxbakka-stream

Empty file while trying to marshal jaxb object with akka streams


I'm trying to marshal jaxb object to xml String and then write it to file using akka Streams, but after executing created file is empty.

I already checked marshaling method but it works fine without streams. Help me please to understand where is an error.

Here is my test method:

  @Test
    public void singlePojoTest() {
        ActorSystem actor = ActorSystem.create();
        Materializer materializer = ActorMaterializer.create(actor);
        //Creating and initializing of JAXB POJO
        AuditFile.Header header = new AuditFile.Header();
        initHeader(header,calendar);
        // useMarshaller - is converting object to xml String
        Flow<Object,String,NotUsed> flow = Flow.of(Object.class).map(o -> useMarshaller(o));
        Source<String,NotUsed> source = Source.single((Object)header).via(flow);
        CompletionStage<IOResult> result = source.map(string -> ByteString.fromString(string)).runWith(FileIO.toPath(Paths.get("test.txt")),materializer);
        actor.terminate();
    }

I expecting that after executing of method - file with marshaled xml will be created.


Solution

  • You are calling actor.terminate(); immediately after initiating the stream without waiting for the stream to finish.

    You have to "block" your test thread and allow for the asynchronous stream processing to finish before you can terminate the actor system.

    Apply following before closing the actor system.

    result.toCompletableFuture().get();