sk.baka.ikslibs
Class TransformUtils

java.lang.Object
  extended by sk.baka.ikslibs.TransformUtils

public final class TransformUtils
extends Object

Provides tools for javax.xml.transform package.

Author:
Martin Vysny

Nested Class Summary
static class TransformUtils.DomReader
          Reads a DOM document and sends it to the content handler.
 
Field Summary
static DocumentBuilder builder
          Produces document instances.
static Document doc
          The document instance, used as a node factory.
static TransformerFactory factory
          Factory that produces Transformer objects.
 
Constructor Summary
TransformUtils()
           
 
Method Summary
static void closeResult(Result result)
          Closes given result.
static void closeResultQuietly(Result result)
          Closes given result.
static void closeSource(Source source)
          Closes given source.
static void closeSourceQuietly(Source source)
          Closes given source.
static void copyStream(StreamSource source, StreamResult result, String encoding)
          Copies data from the source stream to the target stream.
static URIResolver entityResolverAsUriResolver(EntityResolver resolver)
          Wraps the SAX entity resolver as a transformer URI resolver.
static ErrorListener errorHandlerAsListener(ErrorHandler handler)
          Wraps the SAX error handler as a transformer error listener.
static javax.xml.stream.XMLEventReader eventReaderFromSource(STAXSource source)
          Returns STAX source as an XML event reader instance.
static String getEncoding(String encoding, Source source, Result result)
          Returns the most appropriate encoding.
static DocumentFragment newFragment()
          Creates new empty document fragment.
static Transformer newIdentity()
          Creates an identity - a transformer that produces document given as an input.
static Transformer newTransformer(URL url)
          For given URL returns appropriate Transformer object, that transforms XML document.
static XMLReader readerToSax(Reader reader, int chunkSize)
          Returns SAX reader that fires these events, in order: start document, multiple text events, end document.
static SAXSource readerToSaxSource(Reader reader, String systemId, int chunkSize)
          Constructs SAX reader that fires three events: start document, text, end document, and returns this reader enclosed in SAXSource.
static void serialize(Source source, StreamResult result, String encoding)
          Serializes given source into a result stream.
static DOMSource sourceToDom(Source source, boolean parse, String encoding)
           Converts source to the DOMSource.
static SAXSource sourceToSax(Source source, boolean parse, String encoding)
           Converts source to the SAXSource.
static STAXSource sourceToSTAX(Source source, boolean parse, String encoding)
           Converts source to the STAXSource.
static StreamSource sourceToStream(Source source)
           Converts source to the StreamSource.
static Reader streamSourceAsReader(StreamSource ss, String encoding)
           Converts stream source to a reader that reads the stream.
static InputSource streamSourceToInputSource(StreamSource ss)
          Converts stream source instance to an input source object.
static XMLReader stringToSax(String string, int chunkSize)
          Returns SAX reader that fires three events: start document, text, end document.
static SAXSource stringToSaxSource(String string, String systemId, int chunkSize)
          Constructs SAX reader that fires three events: start document, text, end document, and returns this reader enclosed in SAXSource.
static SAXParseException transformerExceptionToSax(TransformerException ex)
          Wraps transformer exception in SAX exception.
static Locator transformerLocatorToLocator(SourceLocator locator)
          Wraps the SAX locator as a transformer locator.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

doc

public static final Document doc
The document instance, used as a node factory.


factory

public static final TransformerFactory factory
Factory that produces Transformer objects. We cannot use the standard TransformerFactory.newInstance() because this may instantiate Saxon XSLT processor accidentally. We cannot use Saxon because of a nasty bug #548228.


builder

public static final DocumentBuilder builder
Produces document instances.

Constructor Detail

TransformUtils

public TransformUtils()
Method Detail

sourceToDom

public static DOMSource sourceToDom(Source source,
                                    boolean parse,
                                    String encoding)
                             throws TransformerException,
                                    IOException

Converts source to the DOMSource. Only DOMSource, StreamSource, SAXSource and STAXSource can be converted.

Warning: If the source parameter is DOMSource and it holds node different than document fragment, this node is deleted from its original position and inserted into new document fragment. If this node is a document node then all its children content nodes are moved into new document fragment.

Given source is polled for all data sufficient for a DOM tree construction. This method blocks until the result DOM tree is completely constructed.

Further reading from original source after the method end will most probably fail because of no data available (does not apply to a DOMSource and ObjectSource).

Parameters:
source - the source object to convert.
parse - if true and source is instance of StreamSource then try to parse the stream. Otherwise, result is a single Text node containing whole stream. Ignored when source is not StreamSource.
encoding - the encoding to use when reading from/writing to a stream. If null then it is detected from the source and/or result. If it cannot be detected then UTF-8 is used. For details please see getEncoding(String, Source, Result).
Returns:
Document fragment containing the content of the source, or null if source is not convertible.
Throws:
IOException - if i/o error occurs during source reading.
TransformerException - if transformer fails while processing source.

sourceToSax

public static SAXSource sourceToSax(Source source,
                                    boolean parse,
                                    String encoding)
                             throws TransformerException,
                                    IOException

Converts source to the SAXSource. Only DOMSource, StreamSource, SAXSource and STAXSource can be converted.

This method will never block - the data from the underlying source is read when result's reader XMLReader.parse(InputSource) is invoked. Therefore, if the original source was not SAXSource instance it should NOT be modified or read, otherwise unexpected errors can occur - for example the parser may already have preread some data or events. If you want to 'forward' source streams, do so before the call to this method.

Parameters:
source - the source object to convert.
parse - if true and source is instance of StreamSource then try to parse the stream. Otherwise, result is a single Text node containing whole stream. Ignored when source is not StreamSource.
encoding - the encoding to use when reading from/writing to a stream. If null then it is detected from the source and/or result. If it cannot be detected then UTF-8 is used. For details please see getEncoding(String, Source, Result).
Returns:
XMLReader firing ContentHandler events only.
Throws:
IOException - if i/o error occurs during source reading.
TransformerException - if transformer fails while processing source.

sourceToSTAX

public static STAXSource sourceToSTAX(Source source,
                                      boolean parse,
                                      String encoding)
                               throws TransformerException,
                                      IOException

Converts source to the STAXSource. Only DOMSource, StreamSource and SAXSource can be converted.

Parameters:
source - the source object to convert.

This method will never block - the data from the underlying source is read as the result STAX stream reader is polled for events. Therefore, if the original source was not STAXSource instance it should NOT be modified or read, otherwise unexpected errors can occur - for example the parser may already have preread some data or events. If you want to 'forward' source streams, do so before the call to this method.

parse - if true and source is instance of StreamSource then try to parse the stream. Otherwise, result is a single Text node containing whole stream. Ignored when source is not StreamSource.
encoding - the encoding to use when reading from/writing to a stream. If null then it is detected from the source and/or result. If it cannot be detected then UTF-8 is used. For details please see getEncoding(String, Source, Result).
Returns:
XMLStreamReader.
Throws:
IOException - if i/o error occurs during source reading.
TransformerException - if transformer fails while processing source.

getEncoding

public static final String getEncoding(String encoding,
                                       Source source,
                                       Result result)
Returns the most appropriate encoding. If given encoding is null then it is detected from the source and/or result parameters.

Parameters:
encoding - the encoding. If not null then it is simply returned.
source - look for an encoding in this source. If null it is skipped.
result - look for an encoding in this result. If null it is skipped.
Returns:
encoding, never null. Returns UTF-8 if no encoding can be detected.

streamSourceToInputSource

public static InputSource streamSourceToInputSource(StreamSource ss)
Converts stream source instance to an input source object.

Parameters:
ss - stream source to convert
Returns:
InputSource instance representing original stream source.

streamSourceAsReader

public static Reader streamSourceAsReader(StreamSource ss,
                                          String encoding)
                                   throws UnsupportedEncodingException

Converts stream source to a reader that reads the stream.

Parameters:
ss - stream source to convert.
encoding - optional encoding, used if stream source does not have reader defined. If null then UTF-8 encoding is used.
Returns:
reader reading given stream.
Throws:
UnsupportedEncodingException - if encoding is not supported.

transformerExceptionToSax

public static SAXParseException transformerExceptionToSax(TransformerException ex)
Wraps transformer exception in SAX exception.

Parameters:
ex - exception to wrap.
Returns:
SAX exception.

transformerLocatorToLocator

public static Locator transformerLocatorToLocator(SourceLocator locator)
Wraps the SAX locator as a transformer locator.

Parameters:
locator - locator to wrap.
Returns:
SAX locator. Returns null only if given locator is null.

errorHandlerAsListener

public static ErrorListener errorHandlerAsListener(ErrorHandler handler)
Wraps the SAX error handler as a transformer error listener.

Parameters:
handler - handler to wrap.
Returns:
error listener. Returns null only if given handler is null.

entityResolverAsUriResolver

public static URIResolver entityResolverAsUriResolver(EntityResolver resolver)
Wraps the SAX entity resolver as a transformer URI resolver.

Parameters:
resolver - the resolver to wrap.
Returns:
URI resolver. Returns null only if given resolver is null.

readerToSax

public static XMLReader readerToSax(Reader reader,
                                    int chunkSize)
Returns SAX reader that fires these events, in order: start document, multiple text events, end document.

Parameters:
reader - string to convert.
chunkSize - split text into chunks with this size.
Returns:
SAX reader instance.

stringToSax

public static XMLReader stringToSax(String string,
                                    int chunkSize)
Returns SAX reader that fires three events: start document, text, end document.

Parameters:
string - string to convert.
chunkSize - split text into chunks with this size.
Returns:
SAX reader instance.

stringToSaxSource

public static SAXSource stringToSaxSource(String string,
                                          String systemId,
                                          int chunkSize)
Constructs SAX reader that fires three events: start document, text, end document, and returns this reader enclosed in SAXSource.

Parameters:
string - string to convert.
systemId - identifier set to the SAXSource being returned.
chunkSize - split text into chunks with this size.
Returns:
SAX reader instance, enclosed in SAXSource. The source has an empty reader as its input source.

readerToSaxSource

public static SAXSource readerToSaxSource(Reader reader,
                                          String systemId,
                                          int chunkSize)
Constructs SAX reader that fires three events: start document, text, end document, and returns this reader enclosed in SAXSource.

Parameters:
reader - string to convert.
systemId - identifier set to the SAXSource being returned.
chunkSize - split text into chunks with this size.
Returns:
SAX reader instance, enclosed in SAXSource. The source has an empty reader as its input source.

serialize

public static void serialize(Source source,
                             StreamResult result,
                             String encoding)
                      throws IOException
Serializes given source into a result stream. Uses default settings for a serializer. Blocks until the serialization is not finished.

Parameters:
source - read document from this source. Cannot be ObjectSource. Must be readable.
result - write serialized document here. Must be writable. Not closed after the serialization.
encoding - the encoding to use when reading from/writing to a stream. If null then it is detected from the source and/or result. If it cannot be detected then UTF-8 is used. For details please see getEncoding(String, Source, Result). This parameter is used only if serializing into output stream.
Throws:
IOException - if io error occurs.

sourceToStream

public static StreamSource sourceToStream(Source source)

Converts source to the StreamSource. Only DOMSource, StreamSource, SAXSource and STAXSource can be converted.

The function will never block - a background daemon thread is constructed if needed, to transparently handle the conversion. For example, in case of SAXSource the XMLReader.parse(InputSource) is executed in the background thread.

The thread is terminated automatically when the reader is closed.

Parameters:
source - the source object to convert.
Returns:
stream source with the reader containing serialized document and input stream null.

newIdentity

public static Transformer newIdentity()
Creates an identity - a transformer that produces document given as an input.

Returns:
new identity transformer.

newFragment

public static DocumentFragment newFragment()
Creates new empty document fragment. You may use its document to create new nodes and fill the fragment with them.

Returns:
new empty instance of document fragment.

newTransformer

public static Transformer newTransformer(URL url)
                                  throws IOException,
                                         TransformerException
For given URL returns appropriate Transformer object, that transforms XML document. Only XSLT is supported.

Parameters:
url - location of the transformer.
Returns:
Transformer instance
Throws:
IOException - if I/O error occurs.
TransformerException - if XSLT contains errors.

closeSource

public static void closeSource(Source source)
                        throws IOException
Closes given source. Only StreamSource and STAXSource can be closed.

Parameters:
source - the source to close. Closes reader if not null, otherwise closes inputstream - does not close them both.
Throws:
IOException - if close fails.

closeSourceQuietly

public static void closeSourceQuietly(Source source)
Closes given source. Only StreamSource and STAXSource can be closed. IOException is logged and ignored.

Parameters:
source - the source to close. Closes reader if not null, otherwise closes inputstream - does not close them both.

closeResultQuietly

public static void closeResultQuietly(Result result)
Closes given result. Only StreamResult and STAXResult can be closed. IOException is logged and ignored.

Parameters:
result - the source to close. Closes writer if not null, otherwise closes outputstream - does not close them both.

closeResult

public static void closeResult(Result result)
                        throws IOException
Closes given result. Only StreamResult and STAXResult can be closed.

Parameters:
result - the source to close. Closes writer if not null, otherwise closes outputstream - does not close them both.
Throws:
IOException - if close fails.

eventReaderFromSource

public static javax.xml.stream.XMLEventReader eventReaderFromSource(STAXSource source)
                                                             throws javax.xml.stream.XMLStreamException
Returns STAX source as an XML event reader instance.

Parameters:
source - the source
Returns:
xml event reader, never null.
Throws:
javax.xml.stream.XMLStreamException

copyStream

public static void copyStream(StreamSource source,
                              StreamResult result,
                              String encoding)
                       throws IOException
Copies data from the source stream to the target stream.

Parameters:
source - the source, must be readable.
result - target, must be writable.
encoding - if copying from input stream to a writer (or vice versa), use this encoding. If null then UTF-8 encoding is used.
Throws:
IOException - if io error occurs.


Copyright © 2006 Martin Vysny - baka. All Rights Reserved.