Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert javax.xml.transform.Source into an InputStream?

Tags:

java

io

transform

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();
like image 212
Christopher Klewes Avatar asked Sep 14 '10 17:09

Christopher Klewes


People also ask

What is javax XML Transform source?

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).

What is Java StreamSource?

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.

What is StreamResult in Java?

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.


1 Answers

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;
like image 97
gpeche Avatar answered Oct 23 '22 06:10

gpeche