Class XMLHelper

java.lang.Object
net.simplace.core.service.XMLHelper

public final class XMLHelper extends Object
Helper methods for XML operations based on JDOM2: parsing, serialising, reading attributes and XPath queries.

Instance methods use one SAX builder (with DTDResolver) per thread and one shared pretty-printing outputter; use getInstance() to get the shared instance.

Author:
Andreas Enders
  • Method Details

    • getInstance

      public static XMLHelper getInstance()
      Returns the shared instance, creating it on first call.
      Returns:
      the shared instance
    • getRootIDAttribute

      public String getRootIDAttribute(String aXMLString)
      Reads the id attribute of the root element of an XML string. Parse errors are logged.
      Parameters:
      aXMLString - XML document as string
      Returns:
      the attribute value, or null if it does not exist or the string cannot be parsed
    • replace

      public static String replace(String aString, String aToBeReplacedString, String aReplaceWithString)
      Replaces all occurrences of a string (literally, not as regular expression).
      Parameters:
      aString - string to search in
      aToBeReplacedString - string to search for; must not be empty
      aReplaceWithString - replacement
      Returns:
      the resulting string
    • replaceAttribute

      public static String replaceAttribute(String aString, Map<String,Object> aReplacements, String aAttribute)
      Replaces attribute values in an XML string: every occurrence of attribute="key" is replaced by attribute="value" for each entry of the map.
      Parameters:
      aString - XML string
      aReplacements - map from old to new attribute values; the values must be strings
      aAttribute - name of the attribute
      Returns:
      the resulting string
    • getRootNameAttribute

      public String getRootNameAttribute(String aXMLString)
      Reads the name attribute of the root element of an XML string. Parse errors are logged.
      Parameters:
      aXMLString - XML document as string
      Returns:
      the attribute value, or null if it does not exist or the string cannot be parsed
    • outputToString

      public String outputToString(org.jdom2.Element aElement) throws IOException
      Serialises an element to a pretty-printed XML string.
      Parameters:
      aElement - element to serialise
      Returns:
      the XML string
      Throws:
      IOException - if serialising fails
    • outputToString

      public String outputToString(org.jdom2.Document aDocument) throws IOException
      Serialises a document to a pretty-printed XML string.
      Parameters:
      aDocument - document to serialise
      Returns:
      the XML string
      Throws:
      IOException - if serialising fails
    • getElementFromString

      public org.jdom2.Element getElementFromString(String aXMLContent) throws org.jdom2.JDOMException, IOException
      Parses an XML string and returns its root element.
      Parameters:
      aXMLContent - XML document as string
      Returns:
      the root element
      Throws:
      org.jdom2.JDOMException - if the string is not well-formed XML
      IOException - if reading fails
    • outputToStringWithDefault

      public String outputToStringWithDefault(org.jdom2.Element aElement, String aDefault)
      Serialises an element to a pretty-printed XML string. If the element is null or an error occurs, a default string is returned.
      Parameters:
      aElement - element to serialise
      aDefault - string to return on error
      Returns:
      the XML string, or aDefault
    • getCommaSeparatedList

      public String getCommaSeparatedList(org.jdom2.Element aElement, String aAttributeName)
      Reads an attribute from all child elements of an element and joins the values with commas.
      Parameters:
      aElement - parent element
      aAttributeName - name of the attribute to read from each child
      Returns:
      comma separated list of the values (missing attributes appear as null), an empty string if there are no children, or null if aElement is null
    • outputToStringWithDefault

      public String outputToStringWithDefault(org.jdom2.Document aDocument, String aDefault)
      Serialises a document to a pretty-printed XML string. If an error occurs (e.g. the document is null), a default string is returned.
      Parameters:
      aDocument - document to serialise
      aDefault - string to return on error
      Returns:
      the XML string, or aDefault
    • getRootAttribute

      public String getRootAttribute(String aXMLString, String aAttributeName)
      Reads an attribute of the root element of an XML string. Parse errors are logged.
      Parameters:
      aXMLString - XML document as string
      aAttributeName - name of the attribute
      Returns:
      the attribute value, or null if it does not exist or the string cannot be parsed
    • removeChildren

      public String removeChildren(String aXMLString, String aName)
      Removes all direct children of the root element with a certain name from an XML string.
      Parameters:
      aXMLString - XML document as string
      aName - name of the children to remove
      Returns:
      the resulting pretty-printed XML string, or the original string if it cannot be parsed
    • addElement

      public static final org.jdom2.Element addElement(org.jdom2.Element aElement, String aName, String aValue)
      Adds a new child element with text content, using the namespace of the parent.
      Parameters:
      aElement - parent element
      aName - name of the new element
      aValue - text content of the new element
      Returns:
      the new element
    • getOrCreateChild

      public static org.jdom2.Element getOrCreateChild(org.jdom2.Element aParentElement, String aChildName)
      Returns the child element of aParentElement with the given name. If it does not exist, it is created (in the namespace of the parent) and attached to aParentElement.
      Parameters:
      aParentElement - parent element
      aChildName - name of the child
      Returns:
      the existing or new child element
    • addTextToChildThatMayExist

      public static void addTextToChildThatMayExist(org.jdom2.Element aParentElement, String aChildName, String aValue)
      Appends text to the child of aParentElement with the name aChildName. If the child does not exist, it is created and attached.
      Parameters:
      aParentElement - parent element
      aChildName - name of the child
      aValue - text to append
    • getElementFromStream

      public org.jdom2.Element getElementFromStream(InputStream tFileIn) throws org.jdom2.JDOMException, IOException
      Parses an XML stream and returns its root element. The stream is not closed.
      Parameters:
      tFileIn - stream to parse
      Returns:
      the root element
      Throws:
      org.jdom2.JDOMException - if the content is not well-formed XML
      IOException - if reading fails
    • getDocumentFromStream

      public org.jdom2.Document getDocumentFromStream(InputStream tFileIn) throws org.jdom2.JDOMException, IOException
      Parses an XML stream and returns the document. The stream is not closed.
      Parameters:
      tFileIn - stream to parse
      Returns:
      the document
      Throws:
      org.jdom2.JDOMException - if the content is not well-formed XML
      IOException - if reading fails
    • getDocumentFromString

      public org.jdom2.Document getDocumentFromString(String aString) throws org.jdom2.JDOMException, IOException
      Parses an XML string and returns the document.
      Parameters:
      aString - XML document as string
      Returns:
      the document
      Throws:
      org.jdom2.JDOMException - if the string is not well-formed XML
      IOException - if reading fails
    • getElementFromReader

      public org.jdom2.Element getElementFromReader(Reader aReader) throws org.jdom2.JDOMException, IOException
      Parses XML from a reader and returns its root element. The reader is not closed.
      Parameters:
      aReader - reader to parse
      Returns:
      the root element
      Throws:
      org.jdom2.JDOMException - if the content is not well-formed XML
      IOException - if reading fails
    • getElementFromFile

      public org.jdom2.Element getElementFromFile(File aFile)
      Parses an XML file and returns its root element. Files ending with .gz are decompressed. If the file does not exist, a resource with the same file name (plain or GZIP compressed) is looked up on the class path. Errors are logged.
      Parameters:
      aFile - XML file to parse
      Returns:
      the root element, or null if an error occurred
    • getElementFromFile

      public org.jdom2.Element getElementFromFile(File aFile, String aEncoding)
      Parses an XML file with the given character encoding and returns its root element. Files ending with .gz are decompressed. If the file does not exist, a resource with the same file name (plain or GZIP compressed) is looked up on the class path. Errors are logged.
      Parameters:
      aFile - XML file to parse
      aEncoding - character encoding of the file, e.g. UTF-8
      Returns:
      the root element, or null if an error occurred
    • getAttributeValueOrEmptyString

      public static final String getAttributeValueOrEmptyString(org.jdom2.Element aElement, String aAtrributeValue)
      Returns the value of an attribute, or an empty string if it does not exist.
      Parameters:
      aElement - element to read from
      aAtrributeValue - name of the attribute
      Returns:
      the attribute value, or "" if it does not exist
    • getAttributeValueOrNull

      public static final String getAttributeValueOrNull(org.jdom2.Element aElement, String aAtrributeValue)
      Returns the value of an attribute, or null if it does not exist or is empty.
      Parameters:
      aElement - element to read from
      aAtrributeValue - name of the attribute
      Returns:
      the attribute value, or null if it does not exist or is empty
    • getBooleanAttributeValue

      public static final boolean getBooleanAttributeValue(org.jdom2.Element aElement, String aName, boolean aDefault)
      Returns the value of an attribute as boolean. Only the exact value true is interpreted as true.
      Parameters:
      aElement - element to read from
      aName - name of the attribute
      aDefault - value to return if the attribute does not exist
      Returns:
      the attribute value as boolean, or aDefault if it does not exist
    • getNumberAttributeValue

      public static <T extends Number> T getNumberAttributeValue(org.jdom2.Element aElement, String aAttr, Class<T> aNumberType, T aDefault)
      Returns the value of an attribute converted to a number type. A warning is logged if the value cannot be converted.
      Type Parameters:
      T - number type
      Parameters:
      aElement - element to read from
      aAttr - name of the attribute
      aNumberType - number type the value is converted to (subclass of Number)
      aDefault - value returned if the attribute does not exist, is empty or cannot be converted to aNumberType
      Returns:
      the attribute value as number, or aDefault
    • isXMLWellFormed

      public boolean isXMLWellFormed(String aXMLString)
      Checks whether a string is well-formed XML.
      Parameters:
      aXMLString - string to check
      Returns:
      true if the string can be parsed
    • transformElementToMap

      public static Map<String,Object> transformElementToMap(org.jdom2.Element aElement)
      Transforms the parameter children of an element into a map from their key attribute to their text. If a parameter has no text but a result child, the serialised result element is used as value. Expected structure:
      <root>
        <parameter key="key1">value1</parameter>
        <parameter key="key2">value2</parameter>
      </root>
      
      Parameters:
      aElement - the root element; may be null
      Returns:
      map from key to value; empty if aElement is null
      See Also:
    • createParameterElement

      public static org.jdom2.Element createParameterElement(String aParameter, Object aValue)
      Creates an element <parameter key="aParameter">aValue</parameter>.
      Parameters:
      aParameter - value of the key attribute
      aValue - text content; converted with toString()
      Returns:
      the new element
    • createTextElement

      public static org.jdom2.Element createTextElement(String aId, String aTitle, String aRequired, String aEnabled, String aDefault)
      Creates a form field element <text>.
      Parameters:
      aId - value of the id attribute
      aTitle - value of the title attribute; omitted if empty
      aRequired - value of the required attribute; omitted if empty
      aEnabled - value of the enabled attribute; omitted if empty
      aDefault - value of the default attribute; omitted if empty
      Returns:
      the new element
      See Also:
    • createChoiceElement

      public static org.jdom2.Element createChoiceElement(String aId, String aTitle, String aRequired, String aEnabled, String aType, String aLocalize, String aMultiselect, String aDefault, Map<String,String> aOptions)
      Creates a form field element <choice> with <option> children.
      Parameters:
      aId - value of the id attribute
      aTitle - value of the title attribute; omitted if empty
      aRequired - value of the required attribute; omitted if empty
      aEnabled - value of the enabled attribute; omitted if empty
      aType - value of the type attribute; omitted if empty
      aLocalize - value of the localize attribute; omitted if empty
      aMultiselect - value of the multiselect attribute
      aDefault - value of the default attribute; omitted if empty
      aOptions - options as map from display text to option id
      Returns:
      the new element
    • createDoubleElement

      public static org.jdom2.Element createDoubleElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault)
      Creates a form field element <double>.
      Parameters:
      aId - value of the id attribute
      aTitle - value of the title attribute; omitted if empty
      aRequired - value of the required attribute; omitted if empty
      aEnabled - value of the enabled attribute; omitted if empty
      aMin - value of the min attribute
      aMax - value of the max attribute
      aType - value of the type attribute; omitted if empty
      aDefault - value of the default attribute; omitted if empty
      Returns:
      the new element
    • createIntegerElement

      public static org.jdom2.Element createIntegerElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault)
      Creates a form field element <integer>.
      Parameters:
      aId - value of the id attribute
      aTitle - value of the title attribute; omitted if empty
      aRequired - value of the required attribute; omitted if empty
      aEnabled - value of the enabled attribute; omitted if empty
      aMin - value of the min attribute
      aMax - value of the max attribute
      aType - value of the type attribute; omitted if empty
      aDefault - value of the default attribute; omitted if empty
      Returns:
      the new element
    • createFieldElement

      public static org.jdom2.Element createFieldElement(String aName, String aTitle, String aId, String aRequired, String aEnabled, String aDefault)
      Creates a form field element with the common attributes.
      Parameters:
      aName - element name, i.e. the field type (e.g. text, integer)
      aTitle - value of the title attribute; omitted if empty
      aId - value of the id attribute
      aRequired - value of the required attribute; omitted if empty
      aEnabled - value of the enabled attribute; omitted if empty
      aDefault - value of the default attribute; omitted if empty
      Returns:
      the new element
    • evaluateXPath

      public static List<org.jdom2.Element> evaluateXPath(org.jdom2.Document aDoc, String aExpression)
      Evaluates an XPath expression on a document and returns the matching elements. The namespace of the root element is available in the expression. Errors are logged.
      Parameters:
      aDoc - document to query
      aExpression - XPath expression
      Returns:
      the matching elements, or null if an error occurred
    • evaluateXPath

      public static List<org.jdom2.Element> evaluateXPath(org.jdom2.Element aElement, String aExpression)
      Evaluates an XPath expression relative to an element and returns the matching elements. The namespace of the element is available in the expression. Errors are logged.
      Parameters:
      aElement - context element
      aExpression - XPath expression
      Returns:
      the matching elements, or null if an error occurred
    • selectSingleElement

      public static org.jdom2.Element selectSingleElement(Object aContext, String aExpression) throws org.jdom2.JDOMException
      Returns the first element selected by an XPath expression (replaces the deprecated org.jdom2.xpath.XPath.selectSingleNode). Expressions starting with // search the whole document of the context.
      Parameters:
      aContext - context node, e.g. an element or a document
      aExpression - XPath expression selecting elements
      Returns:
      the first selected element, or null if there is none
      Throws:
      org.jdom2.JDOMException - if the expression is invalid or cannot be evaluated
    • evaluateXPathSingleResult

      public static String evaluateXPathSingleResult(org.jdom2.Document aDoc, String aExpression)
      Evaluates an XPath expression on a document and returns the first result as string. For text nodes and elements the trimmed text is returned, for other results (e.g. attributes, numbers) their toString(). Errors are logged.
      Parameters:
      aDoc - document to query
      aExpression - XPath expression
      Returns:
      the first result as string, or null if there is no result or an error occurred
    • transformMapToElement

      public static org.jdom2.Element transformMapToElement(Map<String,Object> aParameterMap, String aNameOfRootElement)
      Transforms a map into an element with one parameter child per entry.
      Parameters:
      aParameterMap - map from key to value
      aNameOfRootElement - name of the element to create
      Returns:
      the new element
      See Also:
    • checkAttributeExists

      public static boolean checkAttributeExists(org.jdom2.Element aVarElement, String aString)
      Checks whether an element has an attribute.
      Parameters:
      aVarElement - element to check
      aString - name of the attribute
      Returns:
      true if the attribute exists
    • checkAttributeNotEmpty

      public static boolean checkAttributeNotEmpty(org.jdom2.Element aVarElement, String aString)
      Checks whether an element has an attribute with a non-blank value.
      Parameters:
      aVarElement - element to check
      aString - name of the attribute
      Returns:
      true if the attribute exists and is not empty or whitespace only
    • checkValueExists

      public static boolean checkValueExists(org.jdom2.Element aVarElement)
      Checks whether an element has non-blank text content.
      Parameters:
      aVarElement - element to check
      Returns:
      true if the trimmed text is not empty
    • toIntArray

      public static Integer[] toIntArray(List<org.jdom2.Element> aChildren)
      Parses the text of each element as integer. Elements that cannot be parsed are logged and skipped.
      Parameters:
      aChildren - elements to parse
      Returns:
      the parsed values
    • toDoubleArray

      public static Double[] toDoubleArray(List<org.jdom2.Element> aChildren)
      Parses the text of each element as double. Elements that cannot be parsed are logged and skipped.
      Parameters:
      aChildren - elements to parse
      Returns:
      the parsed values
    • toDoubleMatrix

      public static Double[][] toDoubleMatrix(List<org.jdom2.Element> aChildren)
      Parses a matrix: each element is a row, its value children are the columns. Values that cannot be parsed are logged and left null.
      Parameters:
      aChildren - row elements
      Returns:
      the matrix; rows may have different lengths
    • generateProjectXML

      public static org.jdom2.Document generateProjectXML(String aProjectDataFile, List<FWSimVariable<?>> aVars, Map<FWSimVariable<?>, String> aSensitivityVarsMap, org.jdom2.Element aOutputsElement) throws org.jdom2.JDOMException, IOException
      Generates a project XML document that reads the project data from a CSV file. If sensitivity variables are given, an EquidistantCalSimGenerator, a CSV output SensitivityOut (file ${_OUTPUTDIR_}/Cal_Out.csv) and the corresponding interface are added.
      Parameters:
      aProjectDataFile - path of the CSV file with the project data
      aVars - variables added as columns to the project resource header
      aSensitivityVarsMap - variables to vary, mapped to their values: for DOUBLE and INT variables min,max,count, for other types the value list; may be null
      aOutputsElement - existing outputs element to add the sensitivity output to; if null, a new one is created
      Returns:
      the project document
      Throws:
      org.jdom2.JDOMException - if the internal template cannot be parsed
      IOException - if the internal template cannot be read
    • toStringArray

      public static String[] toStringArray(List<org.jdom2.Element> aChildren)
      Returns the trimmed text of each element.
      Parameters:
      aChildren - elements to read
      Returns:
      the texts