Class XmlEncoder

java.lang.Object
ucar.unidata.xml.XmlUtil
ucar.unidata.xml.XmlEncoder

public class XmlEncoder extends XmlUtil
See the package.html This class is in part responsible for (de)serializing bundles.
  • Field Details

  • Constructor Details

    • XmlEncoder

      public XmlEncoder()
      Create a new XmlEncoder.
  • Method Details

    • addDefaultDelegates

      protected void addDefaultDelegates()
      Define the set of default delegates (e.g., for Rectangle, Font, etc.) for common objects that don't encode very well.
    • toXml

      public String toXml(Object theObject)
      Convert the given object to xml, formatting the xml (with spaces and newlines).
      Parameters:
      theObject - The object to convert.
      Returns:
      The String xml that represents the object.
    • toXml

      public String toXml(Object theObject, boolean formatXml)
      Convert the given object to xml.
      Parameters:
      theObject - The object to convert.
      formatXml - Do we format the result xml with newlines and spaces to make it readable.
      Returns:
      The String xml that represents the object.
    • getExceptions

      public List getExceptions()
      Get the exceptions
      Returns:
      the list of exceptions
    • getErrorMessages

      public List getErrorMessages()
      The the error messages
      Returns:
      the list of error messages
    • toElement

      public Element toElement(Object theObject)
      Create the DOM Element that represents the given object.
      Parameters:
      theObject - The object to encode.
      Returns:
      The dom Element that represents the given Object.
    • decodeXml

      public static Object decodeXml(String xml) throws Exception
      Decode the XML
      Parameters:
      xml -
      Returns:
      the decoded XML
      Throws:
      Exception
    • encodeObject

      public static String encodeObject(Object object) throws Exception
      XML encode the object
      Parameters:
      object -
      Returns:
      encoded object as XML string
      Throws:
      Exception
    • toObject

      public Object toObject(String xml) throws Exception
      Create an object from the given xml. This will catch any exceptions and print them out in toto, returning null.
      Parameters:
      xml - The xml String that defines an object.
      Returns:
      The newly created object.
      Throws:
      Exception - When anything bad happens.
    • toObject

      public Object toObject(String xml, boolean catchAndLogError) throws Exception
      XML string to object
      Parameters:
      xml -
      catchAndLogError -
      Returns:
      the object
      Throws:
      Exception
    • toObject

      public Object toObject(Element node)
      Create an object from the given dom subtree.
      Parameters:
      node - The xml.
      Returns:
      the newly created object.
    • clear

      public void clear()
      Clear the internal state this encoder keeps during the encoding/decoding process.
    • init

      protected void init()
      This resets the state of this encoder.
    • methodOk

      public boolean methodOk(String methodName)
      Is the given method name one of the allowable methods to execute.
      Parameters:
      methodName - The mehtod name.
      Returns:
      Ok to invoke the method.
    • addDelegateForClass

      public void addDelegateForClass(Class theClass, XmlDelegate delegate)
      Add an XmlDelegate for the given class. The delegate is the object responsible for the persistence of all objects of the type of the given class or are a derived class.
      Parameters:
      theClass - The class to handle.
      delegate - The delegate that handles the class.
    • addHighPriorityDelegateForClass

      public void addHighPriorityDelegateForClass(Class theClass, XmlDelegate delegate)
      Add an XmlDelegate for the given class. The given delegate will get added to the beginning of the list so that it takes priority over ant existing delegates The delegate is the object responsible for the persistence of all objects of the type of the given class or are a derived class.
      Parameters:
      theClass - The class to handle.
      delegate - The delegate that handles the class.
    • getDelegate

      protected XmlDelegate getDelegate(Class theClass)
      Find the XmlDelegate that handles the given class.
      Parameters:
      theClass - The class.
      Returns:
      The delegate that handles the class.
    • getDocument

      public Document getDocument()
      Create (if needed) and return the xml Document for this encoder.
      Returns:
      The xml document to write to.
    • setDocument

      public void setDocument(Document document)
      Set the xml Document used by this encoder. This allows client code to override which Document is to be used.
      Parameters:
      document - The new xml document for this encoder to use.
    • getNextId

      protected String getNextId()
      Utility method to return a unique (during a particular encoding) String id.
      Returns:
      A unique (for this encoder) id.
    • getObjectFromId

      protected Object getObjectFromId(String id)
      Returns the object (maybe null) that has the given id.
      Parameters:
      id - The id to lookup.
      Returns:
      The object defined by the id or null if not found.
    • addSeedObject

      public void addSeedObject(Object seedObject)
      Add an existing object from the environement that is to be used in place of a newly created object. You can "seed" an encoder so that when a newly created object is ".equals" with the seedObject then we actually return and use the seedObject. This way we maintain Object pointer equality.
      Parameters:
      seedObject - The object that exists in the environment that we really want to use.
    • setObject

      protected void setObject(String id, Object theObject)
      Define a mapping between the given id and the object.
      Parameters:
      id - The id of the object.
      theObject - The object.
    • getObjectId

      protected String getObjectId(Object theObject)
      Return the encoding id defined for the given object.
      Parameters:
      theObject - The object to lookup an id for.
      Returns:
      The string id of the object or null.
    • getElementForObject

      protected Element getElementForObject(Object theObject)
      Return the DOM element that represents the given object.
      Parameters:
      theObject - The object.
      Returns:
      The dom Element that represented the object or null if not found.
    • defineObjectId

      public void defineObjectId(Object theObject, String theId)
      Allow client code to predefine an object to id mapping. This allows client code to predefine that certain objects (say, perhaps a fixed global singleton) are defined with the given id. The object itself won't get written out in the encoding but any other object that has a reference to theObject will write out an <object idref=theId> tag. When the encoded object is read back in it will point to the predefined object. e.g.:
        encoder.defineObjectId (someSingletonObject, "idOfSingletonObject");
        
      Will result in xml that looks like:
        <object class="SomeOtherObject">
        ...
        invalid input: '&lt' property name="referenceToSomeSingleton" idref="idOfSingletonObject"/>
        ...
        
      Now when we decode the above xml the object defined with "idOfSingletonObject" will be pre-loaded here.
      Parameters:
      theObject - The initial object.
      theId - The id.
    • setObjectId

      protected String setObjectId(Object theObject)
      Create a new id and define mappings between the id, object and DOM element.
      Parameters:
      theObject - The object to define an id for.
      Returns:
      The new id.
    • setObjectId

      public String setObjectId(Object theObject, Element element)
      Create a new id and define mappings between the id, object and DOM element.
      Parameters:
      theObject - The object to define a new id for.
      element - The Xml DOM node that defines theObject.
      Returns:
      The new id of the object.
    • initPrimitiveName

      protected void initPrimitiveName()
      Initialize the mapping between names for primitives and their classes.
    • isPrimitive

      public boolean isPrimitive(Class theClass)
      Is the given Class a primitive (e.g., an int, float, Integer, Double, etc.).
      Parameters:
      theClass - The class to check.
      Returns:
      Is theClass a primitive Class.
    • getPrimitiveName

      public String getPrimitiveName(Class primitiveClass)
      Return the name of the class to be used for the given class.
      Parameters:
      primitiveClass - The class.
      Returns:
      The class name to use for the class.
    • getPrimitiveClass

      public Class getPrimitiveClass(String name)
      For the given name (e.g., "int", "boolean") return the class (e.g., Integer.TYPE, Boolean.TYPE).
      Parameters:
      name - Primitive class name.
      Returns:
      The Class.
    • getPrimitiveCtor

      public Constructor getPrimitiveCtor(Class primitiveClass)
      Find the Constructor that creates objects of the given primitive class.
      Parameters:
      primitiveClass - The class of the primitive (e.g., Integer, int, etc.)
      Returns:
      The constructor to use.
    • registerClassName

      public void registerClassName(String theName, Class theClass)
      Define a mapping from some name (perhaps an old class path) to the new Class that actually is used to create an object. For example, say you have encoded and saved as xml some object with class: old.path.SomeObject. Now later you restructured your code (like good programmers do) so now the SomeObject class is really: new.path.SomeObject but you want to be able to read in the old xml. So you do:
        encoder.registerClassName ("old.path.SomeObject",  new.path.SomeObject.class);
        
      Parameters:
      theName - The old class name.
      theClass - The new Class to use.
    • registerNewClassName

      public void registerNewClassName(String oldName, String newName)
      Register new class name
      Parameters:
      oldName - the old name
      newName - the new name
    • addClassPatternReplacement

      public void addClassPatternReplacement(String pattern, String replace)
      This allows on to change package paths of classes that are in bundles with a new path
      Parameters:
      pattern - the pattern
      replace - the replace pattern
    • getClass

      public Class getClass(String className) throws ClassNotFoundException
      Find the Class that corresponds to the given className. Lookup in the classNameToClass table to see if we have a different Class. If not then just used Class.forName (className);
      Parameters:
      className - The name of the Class.
      Returns:
      The class found for the className.
      Throws:
      ClassNotFoundException - When we cannot find the class.
    • getClassName

      public String getClassName(Class theClass)
      Get the String name of the given class. We lookup to see if the given Class is for one of the primitive types. Else we lookup in the mapping defined with registerClassName. Finally we simply use theClass.getName ().
      Parameters:
      theClass - The Class.
      Returns:
      The name to use for the given Class.
    • newElement

      public Element newElement(String tagName)
      Create a new Element of the given tag name using the current document.
      Parameters:
      tagName - The tag name.
      Returns:
      The new Element.
    • createArrayElement

      public Element createArrayElement(Object arrayObject)
      Create an Xml Element that represents the given object (which should be an array). For example, a String array:
        String[]array ={"foo", "bar"};
        
      would result in: String[]array ={"foo", "bar"};
       <array class="string"  length="2" >
       <string><![CDATA[foo]]></string>
       <string><![CDATA[bar]]></string>
       </array>
        
      Primitive arrays are handled differently (for size reasons):
        int[]array ={5,4};
        
      Would result in:
       <parray class="int"  length="2" >5,4</parray>
        
      Parameters:
      arrayObject - The array object.
      Returns:
      The new Xml Element that represents the arrayObject.
    • createEnumElement

      public <E extends Enum<E>> Element createEnumElement(E e)
      Creates the element based on the enum.
      Type Parameters:
      E - the enum element type
      Parameters:
      e - the e
      Returns:
      the element
    • createPrimitiveArrayElement

      public Element createPrimitiveArrayElement(Object primitiveArray)
      Create an Xml Element that represents the given array of primitives.
      Parameters:
      primitiveArray - The array of primitives.
      Returns:
      The xml representation of the primitive array.
    • createTextNode

      public Node createTextNode(String contents)
      A utility to create a text node
      Parameters:
      contents - The text
      Returns:
      The text node
    • deserialize

      public static Object deserialize(byte[] bytes) throws Exception
      A utility to deserialize the given bytes
      Parameters:
      bytes - The bytes
      Returns:
      The deserialized object
      Throws:
      Exception - When something bad happens
    • serialize

      public static byte[] serialize(Serializable object) throws Exception
      A utility to serialize the given object
      Parameters:
      object - The object
      Returns:
      The serialized representation of the object
      Throws:
      Exception - When something bad happens
    • createMethodElement

      public Element createMethodElement(String methodName, List argumentElements)
      Create a "method" xml element, one that represents a method call. The argumentElements is a List of Xml Elements that represent the arguments to the method.
      Parameters:
      methodName - The name of the method.
      argumentElements - List of method arguments.
      Returns:
      The method xml Element.
    • createMethodElement

      public Element createMethodElement(String methodName, Element contents)
      Create a "method" xml element, one that represents a method call.
      Parameters:
      methodName - The name of the method.
      contents - Xml represention of the method arguments.
      Returns:
      The method xml Element.
    • createMethodElement

      public Element createMethodElement(String methodName)
      Create a "method" xml element, one that represents a method call. This method has no arguments.
      Parameters:
      methodName - The name of the method.
      Returns:
      The method xml Element.
    • createSerialElement

      public Element createSerialElement(Class theClass, String serialRepresentation)
      Create a "serial" xml element, one that represents a serialized Object.
      Parameters:
      theClass - The class of the original serialized object.
      serialRepresentation - Go figure.
      Returns:
      The xml element that represents the serialized object.
    • createPropertyElement

      public Element createPropertyElement(String propertyName, Element value)
      Create a "property" xml element, one that represents a bean property on an object.
      Parameters:
      propertyName - The bean name.
      value - The xml represention of the property value.
      Returns:
      The xml element that represents the property.
    • createReferenceElement

      public Element createReferenceElement(String id)
      Create an element that represents a reference to an already encoded object.
      Parameters:
      id - The id of the object.
      Returns:
      The xml element that represents holds the object reference.
    • createPrimitiveElement

      public Element createPrimitiveElement(String primitiveName, Object value)
      Create the xml element for the given primitive value and name.
      Parameters:
      primitiveName - The name of the primitive (e.g., string, int, etc.)
      value - The value.
      Returns:
      The xml representation of the primitive.
    • createNullElement

      public Element createNullElement(Class type)
      Create a null element with the given class (if non-null).
      Parameters:
      type - The class of the null object.
      Returns:
      The null element.
    • createNullElement

      public Element createNullElement()
      Create a null element with no class.
      Returns:
      The null element.
    • createObjectElement

      public Element createObjectElement(Class objectClass)
      Create a "object" tag with the given objectClass.
      Parameters:
      objectClass - The class of the object.
      Returns:
      The xml object tag.
    • createFactoryElement

      public Element createFactoryElement(Class factoryClass)
      Create a "factory" tag with the given factoryClass.
      Parameters:
      factoryClass - The class of the object that implements XmlObjectFactory.
      Returns:
      The xml factory tag.
    • createObjectConstructorElement

      public Element createObjectConstructorElement(Object object, List arguments)
      Create an object tag that holds a constructor tag.
      Parameters:
      object - The object to encode.
      arguments - The argument values to the constructor.
      Returns:
      The xml object tag containing a constructor tag.
    • createObjectConstructorElement

      public Element createObjectConstructorElement(Object object, List arguments, List types)
      Create an object tag that holds a constructor tag.
      Parameters:
      object - The object to encode.
      arguments - The argument values to the constructor.
      types - The types of the arguments
      Returns:
      The xml object tag containing a constructor tag.
    • createConstructorElement

      public Element createConstructorElement(List arguments)
      Construct a "constructor" tag that holds the set of argument objects.
      Parameters:
      arguments - The argument values.
      Returns:
      The xml constructor tag.
    • createConstructorElement

      public Element createConstructorElement(List arguments, List types)
      Construct a "constructor" tag that holds the set of argument objects with respective types.
      Parameters:
      arguments - The argument values.
      types - The types of the arguments.
      Returns:
      The xml constructor tag.
    • findPropertyMethods

      public static List findPropertyMethods(Class c)
      For the given class find the set of public set/get property methods.
      Parameters:
      c - The class to look at.
      Returns:
      The list of property Method-s.
    • findPropertyMethods

      public static List findPropertyMethods(Class c, boolean returnGetters)
      Find the property methods
      Parameters:
      c - the class
      returnGetters - return the getters
      Returns:
      list of property methods
    • createObject

      public Object createObject(Element element)
      Create an object defined by the given XML.
      Parameters:
      element - The xml representation of the object.
      Returns:
      The object.
    • createObjectDontCheckDelegate

      public Object createObjectDontCheckDelegate(Element element)
      Create an object defined by the given XML. Don't check if the object has a delegate.
      Parameters:
      element - The xml representation of the object.
      Returns:
      The object.
    • createArrayObject

      public ObjectClass createArrayObject(Element element)
      Create an array that contains a set of objects.
      Parameters:
      element - The xml representation of the array.
      Returns:
      The array object and its class.
    • createEnumObject

      public ObjectClass createEnumObject(Element element)
      Creates the enum.
      Parameters:
      element - the element
      Returns:
      the enum
    • getTextFromChild

      public String getTextFromChild(Element parent)
      A utility to find the text node child of the given parent
      Parameters:
      parent - The parent node
      Returns:
      The contents of the text node
    • createPrimitiveArrayObject

      public ObjectClass createPrimitiveArrayObject(Element element)
      Create an array that contains a set of primitive objects.
      Parameters:
      element - The xml representation of the primitive array.
      Returns:
      The primitive array object and its class.
    • createPrimitiveObject

      public ObjectClass createPrimitiveObject(Class primitiveClass, Element element)
      Create the primitive object defined by the given class and xml element.
      Parameters:
      primitiveClass - The class of the primitive.
      element - The xml representation of the primitive.
      Returns:
      The primitive object and its class.
    • createPrimitiveObject

      public Object createPrimitiveObject(Class primitiveClass, String value)
      Create the primitive object defined by the given class and value.
      Parameters:
      primitiveClass - The class of the primitive.
      value - The String representation of the value.
      Returns:
      The primitive object.
    • createSerializedObject

      public ObjectClass createSerializedObject(Element parent)
      Deserialize the serialized object defined by the given parent xml element.
      Parameters:
      parent - Contains the serialization xml.
      Returns:
      The new object and its class.
    • createObjectInner

      public ObjectClass createObjectInner(Element element)
      Create the object defined by the given xml.
      Parameters:
      element - Defines the object.
      Returns:
      The object with its class.
    • createObjectInner

      public ObjectClass createObjectInner(Element element, boolean checkDelegate)
      This method creates both the Object that the Element element represents and its Class. We keep track of the Class separately to handle primitive types (e.g., int, boolean, double).
      Parameters:
      element - The xml element that represents the encoded object.
      checkDelegate - Should we check if there is an XmlDelegate for this object.
      Returns:
      The pair (object, Class).
    • invokeMethod

      protected void invokeMethod(Object object, String methodName, Element element)
      Invoke the the method, identified by the given method name, on the given object. Use the children of the given parent xml node as the arguments to the method.
      Parameters:
      object - The object to set the field value of.
      methodName - The name of the method.
      element - The parent xml node that contains the argument object values.
    • invokeField

      protected void invokeField(Object object, String fieldName, Element parent)
      Set the field, identified by the given field name, on the given object, to the value defined by the first xml child of the given parent.
      Parameters:
      object - The object to set the field value of.
      fieldName - The name of the field.
      parent - The parent xml node that contains the object value.
    • createElement

      public Element createElement(Object object)
      This acts as a wrapper around (Object, boolean) , passing in true for the checkPersistable flag.
      Parameters:
      object - The object to create the xml element for.
      Returns:
      The xml representation of the object.
    • createElementDontCheckPersistable

      public Element createElementDontCheckPersistable(Object object)
      This acts as a wrapper around createElement(Object,Class,boolean,boolean), passing in false for the checkPersistable flag and true for the checkDelegate flag.
      Parameters:
      object - The object to create the xml element for.
      Returns:
      The xml representation of the object.
    • createElementDontCheckDelegate

      public Element createElementDontCheckDelegate(Object object)
      This acts as a wrapper around createElement(Object,boolean), passing in false for the checkDelegate flag.
      Parameters:
      object - The object to create the xml element for.
      Returns:
      The xml representation of the object.
    • createElement

      public Element createElement(Object object, boolean checkDelegate)
      This acts as a wrapper around createElement(Object,Class,boolean,boolean), passing in true for the checkPersistable flag.
      Parameters:
      object - The object to create the xml element for.
      checkDelegate - Should we check if the object has an XmlDelegate that handles it.
      Returns:
      The xml representation of the object.
    • createElement

      protected Element createElement(Object object, Class theClass)
      This acts as a wrapper around createElement(Object,Class,boolean,boolean), passing in true and true for the checkPersistable and checkDelegate flags.
      Parameters:
      object - The object to create the xml element for.
      theClass - Its class.
      Returns:
      The xml representation of the object.
    • createElement

      protected Element createElement(Object object, Class theClass, boolean checkPersistable, boolean checkDelegate)
      Create a xml representation of the object. The object may be anything, null, a primitive, an array or a regular object. We pass the class of the object in in case it is null. The flags tell whether to check if the object is a XmlPersistable or has a delegate (the default is to check).
      Parameters:
      object - The object to encode.
      theClass - The Class of the object.
      checkPersistable - Do we defer to the object if is is an XmlPersistable
      checkDelegate - Do we defer to the delegate if the object has an XmlDelegate
      Returns:
      The xml representation of the object.
    • createElementForObject

      public Element createElementForObject(Object object, Class theClass)
      Construct the Xml representation of the given object. This object is just a regular Object, not a primitive, array, etc.
      Parameters:
      object - The regular object.
      theClass - The class of the object. We have this here in case the object is null.
      Returns:
      The xml representation of the object.
    • getFieldElements

      public List getFieldElements(Object object, Hashtable propertyNames)
      Return a List of Xml Elements that represent the set of public fields in the given object.
      Parameters:
      object - The object to look for fields in.
      propertyNames - These represent properties that are already being persisted.
      Returns:
      A List of xml "field" elements.
    • getPropertyElements

      public List getPropertyElements(Object object, Hashtable propertyNames)
      Return a List of Xml Elements that represent the set of public properties in the given object. A property is denoted with public set/get methods of the same type.
      Parameters:
      object - The object to look for properties in.
      propertyNames - Put the property names in here so we can keep them unique.
      Returns:
      A List of xml "property" elements.
    • getSpecialCaseElements

      public List getSpecialCaseElements(Object object)
      Handle certain objects in a special way. For List-s return a set of "add" method Elements. For a Hashtable return a set of "put" method elements.
      Parameters:
      object - The object to check for special case handling.
      Returns:
      A list of xml Elements or null if the object is not special.
    • pr

      public static void pr(String msg)
      A utility method to print out an error message if we are in debug mode.
      Parameters:
      msg - The message.
    • test

      public boolean test(Object o, boolean printXml) throws Exception
      A simple test method.
      Parameters:
      o - The object to encode.
      printXml - Do we println the result xml.
      Returns:
      Did we pass the test.
      Throws:
      Exception - When something goes bad.
    • main

      public static void main(String[] args)
      Runs some tests.
      Parameters:
      args - The command line arguments.