How can I convert a javax.xml.transform.Source
into a InputStream? The Implementation of Source
is javax.xml.transform.dom.DOMSource
.
Source inputSource = messageContext.getRequest().getPayloadSource();
An object that implements this interface contains the information needed to build a transformation result tree. Source. An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).
public class StreamSource extends Object implements Source. Acts as an holder for a transformation Source in the form of a stream of XML markup. Note: Due to their internal use of either a Reader or InputStream instance, StreamSource instances may only be used once.
public class StreamResult extends Object implements Result. Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.
First try to downcast to javax.xml.transform.stream.StreamSource
. If that succeeds you have access to the underlying InputStream
or Reader
through getters. This would be the easiest way.
If downcasting fails, you can try using a javax.xml.transform.Transformer
to transform it into a javax.xml.transform.stream.StreamResult
that has been setup with a java.io.ByteArrayOutputStream
. Then you return a java.io.ByteArrayInputStream
. Something like:
Transformer t = // getTransformer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); t.transform(inputSource, result); return new ByteArrayInputStream(os.getByteArray());
Of course, if the StreamSource
can be a large document, this is not advisable. In that case, you could use a temporary file and java.io.FileOutputStream
/java.io.FileInputStram
. Another option would be to spawn a transformer thread and communicate through java.io.PipedOutputStream
/java.io.PipedInputStream
, but this is more complex:
PipedInputStream is = new PipedInputStream(); PipedOutputStream os = new PipedOutputStream(is); Result result = new StreamResult(os); // This creates and starts a thread that creates a transformer // and applies it to the method parameters. spawnTransformerThread(inputSource, result); return is;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With