9

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();

2 Answers 2

10

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;
Sign up to request clarification or add additional context in comments.

Comments

0

It's not normally possible, unless it can be down-casted to StreamSource or other implementations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.