com.webmethods.rtl.util.xml
Class XMLUtil

java.lang.Object
  extended by com.webmethods.rtl.util.xml.XMLUtil

public class XMLUtil
extends Object

XMLUtil provides convience functions XML Functions (DOM & XPath) Right now it uses xalan and xerces... this may change, but the api shouldn't


Nested Class Summary
static class XMLUtil.NodeListIterator
          NodeIterator which iterates over a dom NodeList.
static class XMLUtil.SingleNodeIterator
          Node iterator which iterates over a single node.
 
Field Summary
static String ATTR_BEG_QUERY
           
static String ATTR_END_QUERY
           
static String ATTR_MID_QUERY
           
static String CLOSE_TAG
           
protected static String DOCUMENT_DECL
           
static String END_TAG
           
static long LONG_ERROR_VALUE
          Error result of various long functions
static String MSG_NULL_DOCUMENT
          Empty string corresponding to the NULL document
static String OPEN_TAG
           
static String SERIALIZER_ENCODING
          Default serializer encoding -> UTF-8
static String SERIALIZER_MIME_TYPE
          Default serializer's MIME type -> text/xml
static String[] SERIALIZER_NON_ESCAPING_ELEMENTS
           
static int XML_DUMP_ALL
           
 
Constructor Summary
XMLUtil()
           
 
Method Summary
protected static void _dumpXML(Node node, Writer out, int depth, int totalDepth)
          output to a stream
protected static Document _loadDocument(InputSource inputSource)
          loads an xml document from the xslt input source
static Node createElement(Node parent, String name)
          Creates new element and appends it to passed parent
static Node createElement(Node parent, String name, String value)
          Creates new element with passed name and text value, and appends it to passed parent
static void dumpXML(Node node, Writer out, int depth)
          Outputs a Node to a stream
static Element duplicateElement(Element parent, Element src)
          Duplicates src Element as a regular Element, and adds it to the parent Element.
static String encodeToQName(String s)
          ASCII-only encoder
static void ensureChildElement(Node parent, String childName, Object childValue)
           
static void excludeElement(Node nodeExclude)
           
static void excludeElements(Document document, String xpathToExclude)
           
static void flushXSLCache()
          Flushes cache for all xsl templates
static void flushXSLCache(Source source)
          Flushes cache for a particular xsl template
static String getAllText(Node node)
          Gets all the text for the given node, including any child nodes
static String getAttributeDef(Element element, String attrName, String defaultValue)
          Gets the attribute value with the given attribute name from the given element.
static String getAttributeEx(Element element, String attribute)
          Helper function to get an attribute.
static long getAttrLong(Element element, String attrName)
          Return attribute value for the given DOM element as long.
static boolean getBooleanByXPath(Node aNode, String xPath, boolean defValue)
          Gets the boolean value for the node text of the first node that matches the given xpath criteria
static DocumentBuilderFactory getBuilderFactory()
          Returns reference to the DocumentBuilderFactory.
static EntityResolver getEntityResolver()
          Returns reference to the EntityResolver.
static ErrorHandler getErrorHandler()
          Returns reference to the sax ErrorHandler.
static Map getMapFromElement(Element element)
          Constructs a Map from element its attributes and its child elements.
static Map getMapFromElementAttributes(Element element)
          Constructs a Map from the attributes on the given element.
static Map getMapFromXMLAttributes(String xmlStream)
           
static String getNodeText(Node node)
          Get the text value for the given node.
static String getNodeTextByXPath(Node aNode, String xPath)
          Gets the node text for the first node that matches the given xpath criteria
static List getNodeTexts(NodeList nodeList)
          Gets a list of all the node texts for the nodes in the given NodeList
static String getSafeAttribute(Element element, String attribute)
          Helper function to get an attribute or return an empty string if the attribute doesn't exist
static Source getSAXSource(Reader inputReader)
           
static void init()
          Initializes XML utilities.
 void init(IComponentData data, String phase)
          Called automatically by the portal runtime to initialize the XMLUtil.
static boolean isEmpty(NodeList nodeList)
          Verifies whether specified node list is empty or null
static Document loadDocument(String xmlFile)
          loads an xml document by the supplied file name
static Document loadDocumentFromInputStream(InputStream inputStream)
          loads an xml document by the suplied input stream
static Document loadDocumentFromReader(Reader reader)
          loads an xml document by the suplied java.io.Reader
static Document loadDocumentFromXML(String xml)
          loads an xml document by the suplied xml
static void mergeNodeInDocument(String srcFilePath, String targetFilePath, String xpathQuery)
          Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node.
static void mergeNodeInDocument(String srcFilePath, String targetFilePath, String srcXpathQuery, String targetXpathQuery)
          Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node.
static Node mergeNodes(Node srcNode, Node targetNode)
          Merge the contents of the srcNode into the targetNode replacing any duplicate nodes in the targetElement
static Document newDocument()
          Creates and returns a new DOM document
static Document newDocument(Node cloneNode)
          Creates and returns a new DOM document that is a clone of the given node.
static DocumentBuilder newDocumentBuilder()
          Creates and returns document builder
static String normalize(String s)
          Normalizes the given string.
static boolean notEmpty(NodeList nodeList)
          Checks that specified node list is not empty
static void removeChild(Element parent, String childName)
           
static void removeElement(Element element)
          Remove element from document
static void replaceNode(Node srcNode, Node targetNode)
          Replaces the targetNode with the srcNode
static void replaceNodeInDocument(String srcFilePath, String targetFilePath, String xpathQuery)
          Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node.
static Element selectElement(Node node, String xpath)
          returns a node from the suplied node that meets the xpath criteria.
static org.w3c.dom.traversal.NodeIterator selectNodeIterator(Node node, String xpath)
          returns a node iterator from the suplied node that meets the xpath criteria.
static NodeList selectNodeList(Node node, String xpath)
          returns a node list from the suplied node that meets the xpath criteria.
static Node selectSingleNode(Node node, String xpath)
          returns a node from the suplied node that meets the xpath criteria.
static void setNodeText(Node node, String text)
          Sets the text value for the given node.
 void shutdown()
          Called automatically by the portal runtime when the VM is closing down.
protected static Attr[] sortAttributes(NamedNodeMap attrs)
          Returns a sorted list of attributes.
static String toString(Document document)
          Serializes document and returns its content as a string
static String toString(Node node)
          Serializes document node and returns its content as a string
static String toString(Node node, boolean minimizeXMLSize)
          Serializes document node and returns its content as a string
static String toString(Node node, int depth)
          Writes a node to text up to the given depth
static void transformXSLtoDoc(Source source, Reader xslreader, Node out)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static void transformXSLtoDoc(Source source, Reader xslreader, Node out, HashMap params)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static void transformXSLtoDoc(Source source, String location, Node out)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static void transformXSLtoDoc(Source source, String location, Node out, HashMap params)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static String transformXSLtoStr(Source source, Reader xslreader)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static String transformXSLtoStr(Source source, Reader xslreader, HashMap params)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static String transformXSLtoStr(Source source, String location)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static String transformXSLtoStr(Source source, String location, HashMap params)
          Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String
static String wrapTextWithTag(String text, String tag)
          wraps a text with the tag for example: text
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ATTR_BEG_QUERY

public static final String ATTR_BEG_QUERY
See Also:
Constant Field Values

ATTR_MID_QUERY

public static final String ATTR_MID_QUERY
See Also:
Constant Field Values

ATTR_END_QUERY

public static final String ATTR_END_QUERY
See Also:
Constant Field Values

MSG_NULL_DOCUMENT

public static final String MSG_NULL_DOCUMENT
Empty string corresponding to the NULL document

See Also:
Constant Field Values

SERIALIZER_ENCODING

public static final String SERIALIZER_ENCODING
Default serializer encoding -> UTF-8

See Also:
Constant Field Values

SERIALIZER_MIME_TYPE

public static final String SERIALIZER_MIME_TYPE
Default serializer's MIME type -> text/xml

See Also:
Constant Field Values

XML_DUMP_ALL

public static final int XML_DUMP_ALL
See Also:
XMLUtil.dumpXML(org.w3c.dom.Node, java.io.Writer, int), Constant Field Values

SERIALIZER_NON_ESCAPING_ELEMENTS

public static final String[] SERIALIZER_NON_ESCAPING_ELEMENTS

LONG_ERROR_VALUE

public static final long LONG_ERROR_VALUE
Error result of various long functions

See Also:
Constant Field Values

OPEN_TAG

public static final String OPEN_TAG
See Also:
Constant Field Values

CLOSE_TAG

public static final String CLOSE_TAG
See Also:
Constant Field Values

END_TAG

public static final String END_TAG
See Also:
Constant Field Values

DOCUMENT_DECL

protected static final String DOCUMENT_DECL
See Also:
Constant Field Values
Constructor Detail

XMLUtil

public XMLUtil()
Method Detail

init

public void init(IComponentData data,
                 String phase)
          throws InitializationException
Called automatically by the portal runtime to initialize the XMLUtil. A typical portal developer should never need to call this method.

Parameters:
data - the IComponentData contains the configuration data for the data manager.
phase - the name of the startup phase that is currently executing
Throws:
com.webmethods.portal.system.init.InitializationException
InitializationException
See Also:
IInitializable

shutdown

public void shutdown()
Called automatically by the portal runtime when the VM is closing down. A typical portal developer should never need to call this method.

See Also:
IInitializable

init

public static void init()
                 throws RtlException
Initializes XML utilities. Called automatically by the portal runtime to initialize the XMLUtil. A typical portal developer should never need to call this method.

Throws:
RtlException

getBuilderFactory

public static DocumentBuilderFactory getBuilderFactory()
Returns reference to the DocumentBuilderFactory. Uses lazy instantiation if not initialized yet.


getEntityResolver

public static EntityResolver getEntityResolver()
Returns reference to the EntityResolver. Uses lazy instantiation if not initialized yet.


getErrorHandler

public static ErrorHandler getErrorHandler()
Returns reference to the sax ErrorHandler. Uses lazy instantiation if not initialized yet.


newDocumentBuilder

public static DocumentBuilder newDocumentBuilder()
Creates and returns document builder


newDocument

public static Document newDocument()
Creates and returns a new DOM document


newDocument

public static Document newDocument(Node cloneNode)
Creates and returns a new DOM document that is a clone of the given node.

Parameters:
cloneNode - the node to use as the content of the new Document

createElement

public static Node createElement(Node parent,
                                 String name)
Creates new element and appends it to passed parent

Parameters:
parent - owner Node. May be either regular node, or document itself
name - name of the element to create

createElement

public static Node createElement(Node parent,
                                 String name,
                                 String value)
Creates new element with passed name and text value, and appends it to passed parent

Parameters:
parent - owner Node. May be either regular node, or document itself
name - name of the element to create
value - text value of created element

loadDocument

public static Document loadDocument(String xmlFile)
loads an xml document by the supplied file name

Parameters:
xmlFile - is the name of the file.

loadDocumentFromInputStream

public static Document loadDocumentFromInputStream(InputStream inputStream)
loads an xml document by the suplied input stream

Parameters:
inputStream - is an open inputStream to an xml document.

loadDocumentFromReader

public static Document loadDocumentFromReader(Reader reader)
loads an xml document by the suplied java.io.Reader

Parameters:
reader - is an open Reader to an xml document.

loadDocumentFromXML

public static Document loadDocumentFromXML(String xml)
loads an xml document by the suplied xml

Parameters:
xml - is a string with valid XML

_loadDocument

protected static Document _loadDocument(InputSource inputSource)
loads an xml document from the xslt input source

Parameters:
inputSource - is the xslt input source

selectSingleNode

public static Node selectSingleNode(Node node,
                                    String xpath)
returns a node from the suplied node that meets the xpath criteria.

Parameters:
node - is the tree starting point.
xpath - is a valid xpath statement.

selectElement

public static Element selectElement(Node node,
                                    String xpath)
returns a node from the suplied node that meets the xpath criteria.

Parameters:
node - is the tree starting point.
xpath - is a valid xpath statement.

selectNodeList

public static NodeList selectNodeList(Node node,
                                      String xpath)
returns a node list from the suplied node that meets the xpath criteria.

Parameters:
node - is the tree starting point.
xpath - is a valid xpath statement.

selectNodeIterator

public static org.w3c.dom.traversal.NodeIterator selectNodeIterator(Node node,
                                                                    String xpath)
returns a node iterator from the suplied node that meets the xpath criteria.

Parameters:
node - is the tree starting point.
xpath - is a valid xpath statement.

getSAXSource

public static Source getSAXSource(Reader inputReader)
                           throws RtlException
Throws:
RtlException

getMapFromXMLAttributes

public static Map getMapFromXMLAttributes(String xmlStream)
                                   throws RtlException
Throws:
RtlException

getMapFromElementAttributes

public static Map getMapFromElementAttributes(Element element)
Constructs a Map from the attributes on the given element. namespaces are ignored.

Parameters:
element - the element to get the attributes from
Returns:
a map of the element's attributes as name-value pairs. (Ignoring namespaces)

getMapFromElement

public static Map getMapFromElement(Element element)
Constructs a Map from element its attributes and its child elements. Child elements are constructed into nested Map instances, while attributes are passed as simple types

Parameters:
element -
Returns:

duplicateElement

public static Element duplicateElement(Element parent,
                                       Element src)
Duplicates src Element as a regular Element, and adds it to the parent Element.

Parameters:
parent - Element that will be made the parent of the new Element.
src - Element the source element (the element to be duplicated).

wrapTextWithTag

public static String wrapTextWithTag(String text,
                                     String tag)
wraps a text with the tag for example: text


getNodeText

public static String getNodeText(Node node)
Get the text value for the given node.

Parameters:
node - the node to examine
Returns:
the text value of the node, or null if not available

setNodeText

public static void setNodeText(Node node,
                               String text)
Sets the text value for the given node.

Parameters:
node - the node to examine
text - the text value of the node

getAttrLong

public static long getAttrLong(Element element,
                               String attrName)
Return attribute value for the given DOM element as long.

Parameters:
element - Document element to use
attrName - Attribute name to retrieve

getAttributeDef

public static String getAttributeDef(Element element,
                                     String attrName,
                                     String defaultValue)
Gets the attribute value with the given attribute name from the given element. If the attribute could not be found the passed in defaultValue is returned

Parameters:
element - the element to get the attribute value from
attrName - the attribute name to retrieve
defaultValue - the value to return if the attribute could not be found
Returns:
the value of the requested attribute if it could be located or the defaultValue otherwise

getAllText

public static String getAllText(Node node)
Gets all the text for the given node, including any child nodes


getNodeTextByXPath

public static String getNodeTextByXPath(Node aNode,
                                        String xPath)
Gets the node text for the first node that matches the given xpath criteria

Parameters:
aNode - is the tree starting point.
xPath - is a valid xpath statement.

getBooleanByXPath

public static boolean getBooleanByXPath(Node aNode,
                                        String xPath,
                                        boolean defValue)
Gets the boolean value for the node text of the first node that matches the given xpath criteria

Parameters:
aNode - is the tree starting point.
xPath - is a valid xpath statement.
defValue - the value to use if the node text is not a boolean string

getNodeTexts

public static List getNodeTexts(NodeList nodeList)
Gets a list of all the node texts for the nodes in the given NodeList

Parameters:
nodeList - the nodelist to get the node texts for

getSafeAttribute

public static String getSafeAttribute(Element element,
                                      String attribute)
Helper function to get an attribute or return an empty string if the attribute doesn't exist

Parameters:
element - the object to get the attribute from
attribute - the attribute name to retrieve
Returns:
value of the requested attribute, or an empty string if the attribute doesn't exist.

getAttributeEx

public static String getAttributeEx(Element element,
                                    String attribute)
Helper function to get an attribute. If it fails to get an attribute an assertion is thrown.

Parameters:
element - the object to get the attribute from
attribute - the attribute name to retrieve
Returns:
value of the requested attribute, or an empty string if the attribute doesn't exist.

transformXSLtoStr

public static String transformXSLtoStr(Source source,
                                       Reader xslreader)
                                throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
xslreader - reader to read XSLT from
Returns:
value is a String result of a transformation
Throws:
TransformerException

transformXSLtoStr

public static String transformXSLtoStr(Source source,
                                       Reader xslreader,
                                       HashMap params)
                                throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
xslreader - reader to read XSLT from
params - to be added to the processor
Returns:
value is a String result of a transformation
Throws:
TransformerException

transformXSLtoStr

public static String transformXSLtoStr(Source source,
                                       String location)
                                throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
location - is a full qualified path to XSLT file. Note, that passing XSLT as file location, rather than as stream, allows XSLT stylesheet caching.
Returns:
value is a String result of a transformation
Throws:
TransformerException

transformXSLtoStr

public static String transformXSLtoStr(Source source,
                                       String location,
                                       HashMap params)
                                throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
location - is a full qualified path to XSLT file. Note, that passing XSLT as file location, rather than as stream, allows XSLT stylesheet caching.
params - to be added to the processor
Returns:
value is a String result of a transformation
Throws:
TransformerException

transformXSLtoDoc

public static void transformXSLtoDoc(Source source,
                                     Reader xslreader,
                                     Node out)
                              throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
xslreader - reader to read XSLT from
out - output Node
Throws:
TransformerException

transformXSLtoDoc

public static void transformXSLtoDoc(Source source,
                                     Reader xslreader,
                                     Node out,
                                     HashMap params)
                              throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
xslreader - reader to read XSLT from
out - output Node
params - to be added to the processor
Throws:
TransformerException

transformXSLtoDoc

public static void transformXSLtoDoc(Source source,
                                     String location,
                                     Node out)
                              throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
location - is a full qualified path to XSLT file. Note, that passing XSLT as file location, rather than as stream, allows XSLT stylesheet caching.
out - output Node
Throws:
TransformerException

transformXSLtoDoc

public static void transformXSLtoDoc(Source source,
                                     String location,
                                     Node out,
                                     HashMap params)
                              throws TransformerException
Helper function that transforms input XML Node using specified XSLT stylesheet and returns result as a String

Parameters:
source - input Node to be transformed
location - is a full qualified path to XSLT file. Note, that passing XSLT as file location, rather than as stream, allows XSLT stylesheet caching.
out - output Node
params - to be added to the processor
Throws:
TransformerException

flushXSLCache

public static void flushXSLCache(Source source)
Flushes cache for a particular xsl template

Parameters:
source -

flushXSLCache

public static void flushXSLCache()
Flushes cache for all xsl templates


toString

public static String toString(Node node,
                              int depth)
Writes a node to text up to the given depth

Parameters:
node -
depth -
Returns:
See Also:
XMLUtil.toString(org.w3c.dom.Node, int), XMLUtil.dumpXML(org.w3c.dom.Node, java.io.Writer, int)

dumpXML

public static void dumpXML(Node node,
                           Writer out,
                           int depth)
                    throws IOException
Outputs a Node to a stream

Throws:
IOException

_dumpXML

protected static void _dumpXML(Node node,
                               Writer out,
                               int depth,
                               int totalDepth)
                        throws IOException
output to a stream

Throws:
IOException

sortAttributes

protected static Attr[] sortAttributes(NamedNodeMap attrs)
Returns a sorted list of attributes.


normalize

public static String normalize(String s)
Normalizes the given string.


toString

public static String toString(Node node)
Serializes document node and returns its content as a string


toString

public static String toString(Node node,
                              boolean minimizeXMLSize)
Serializes document node and returns its content as a string

Parameters:
node - the xml DOM node
minimizeXMLSize - if true then omit comments, identing, etc to minimize overall xml size

toString

public static String toString(Document document)
Serializes document and returns its content as a string


encodeToQName

public static String encodeToQName(String s)
ASCII-only encoder

Parameters:
s - the string the ecode
Returns:
String the encoded string

ensureChildElement

public static void ensureChildElement(Node parent,
                                      String childName,
                                      Object childValue)

removeChild

public static void removeChild(Element parent,
                               String childName)

excludeElements

public static void excludeElements(Document document,
                                   String xpathToExclude)

excludeElement

public static void excludeElement(Node nodeExclude)
Parameters:
nodeExclude -

removeElement

public static void removeElement(Element element)
Remove element from document

Parameters:
element -

mergeNodeInDocument

public static void mergeNodeInDocument(String srcFilePath,
                                       String targetFilePath,
                                       String srcXpathQuery,
                                       String targetXpathQuery)
                                throws IOException
Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node. Then write the target file out to disk.

Parameters:
srcFilePath -
targetFilePath -
srcXpathQuery - the xpath query to get the node in the src document
targetXpathQuery - the xpath query to get the node in the target document
Throws:
IOException

mergeNodeInDocument

public static void mergeNodeInDocument(String srcFilePath,
                                       String targetFilePath,
                                       String xpathQuery)
                                throws IOException
Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node. Then write the target file out to disk.

Parameters:
srcFilePath -
targetFilePath -
xpathQuery - the xpath query to get the node in both the src and target documents
Throws:
IOException

mergeNodes

public static Node mergeNodes(Node srcNode,
                              Node targetNode)
Merge the contents of the srcNode into the targetNode replacing any duplicate nodes in the targetElement

Parameters:
srcNode -
targetNode -
Returns:
the merged Node

replaceNodeInDocument

public static void replaceNodeInDocument(String srcFilePath,
                                         String targetFilePath,
                                         String xpathQuery)
                                  throws IOException
Lookup the node with the given xpath query in the source and target documents and merge the contents of the source node into the target node. Then write the target file out to disk.

Parameters:
srcFilePath -
targetFilePath -
xpathQuery -
Throws:
IOException

replaceNode

public static void replaceNode(Node srcNode,
                               Node targetNode)
Replaces the targetNode with the srcNode

Parameters:
srcNode -
targetNode -

isEmpty

public static boolean isEmpty(NodeList nodeList)
Verifies whether specified node list is empty or null

Parameters:
nodeList - Node list to check
Returns:
True, if list is empty and False - otherwise

notEmpty

public static boolean notEmpty(NodeList nodeList)
Checks that specified node list is not empty

Parameters:
nodeList - Node list to verify
Returns:
True - if list is not empty and False - otherwise