package de.jpaw8.batch.functions;

import java.io.StringReader;
import java.util.function.Function;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Xml2Object<T> implements Function <String,T> {
    private final JAXBContext context;
    private final boolean threadSafe;       // if not (only sequential use), then the marshaller can be reused.
    private final Class<T> baseClass;
    private Unmarshaller m = null;

    /** Command line configurable constructor. */
    public Xml2Object(JAXBContext context, Class<T> baseClass, boolean threadSafe) {
        this.context = context;
        this.baseClass = baseClass;
        this.threadSafe = threadSafe;
    }

    private Unmarshaller createUnmarshaller() {
        Unmarshaller mm;
        try {
            mm = context.createUnmarshaller();
            mm.setProperty(Marshaller.JAXB_FRAGMENT, true);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
        return mm;
    }

    @Override
    public T apply(String t) {
        try {
            Unmarshaller mm = threadSafe ? createUnmarshaller() : m;
            StringReader r = new StringReader(t);
            Object o = mm.unmarshal(r);
            return baseClass.cast(o);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

@@ -446,16 +446,46 @@
 e reused
+, set threadSafe to false then
 .%0A    pr
@@ -520,32 +520,38 @@
 ss;%0A    private 
+final 
 Unmarshaller m =
@@ -552,15 +552,8 @@
 er m
- = null
 ;%0A%0A 
@@ -792,16 +792,70 @@
 adSafe;%0A
+        m = threadSafe ? null : createUnmarshaller();%0A
     %7D%0A%0A 
@@ -865,16 +865,22 @@
 private 
+final 
 Unmarsha

initialize unmarshaller for non-threadsafe invocation