ucar.unidata.xml
Class XmlEncoder

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

public class XmlEncoder
extends XmlUtil

See the package.html file.

Version:
$Revision: 1.79 $Date: 2007/02/07 15:37:48 $
Author:
Metapps development team

Field Summary
static String ATTR_CLASS
          The name for the class attribute.
static String ATTR_ENCODING
          The name for the encode attribute
static String ATTR_ID
          The name for the id attribute.
static String ATTR_IDREF
          The name for the idref attribute.
static String ATTR_LENGTH
          The name for the length attribute.
static String ATTR_NAME
          The name for the name attribute.
static String ATTR_NULL
          The name for the null attribute.
static String ATTR_STRINGVALUE
          The name for the stringvalue attribute.
static String ATTR_VALUE
          The name for the value attribute.
static boolean debug
          Just a debug flag.
protected  ArrayList delegateClasses
          List of classes that we have corresponding XmlDelegates for.
protected  ArrayList delegates
          The List of XmlDelegates that know how to handle certain classes.
protected  Document document
          The Xml document we create.
static String METHOD_ADD
          Method name for List.add
static String METHOD_INIT
          The name of the init method that is called (if it exists) after an object is deserialized
static String METHOD_PUT
          Method name for Hashtable.put
static String NAME_STRING
          The name used in the xml for String objects.
static String TAG_ARRAY
          The tag name used for arrays.
static String TAG_CONSTRUCTOR
          The xml tag for constructors.
static String TAG_FACTORY
          The xml tag for factory objects.
static String TAG_FIELD
          The xml tag for object fields.
static String TAG_IGNORE
          The xml tag when we want to ignore something?
static String TAG_METHOD
          The xml tag for method calls.
static String TAG_NULL
          The xml tag for the null object.
static String TAG_OBJECT
          The xml tag for objects.
static String TAG_PARRAY
          The tag name used for primitive arrays.
static String TAG_PROPERTY
          The xml tag for properties.
static String TAG_SERIAL
          The xml tag for serialized objects.
static String VALUE_BASE64
          The value for the encode by base64
 
Fields inherited from class ucar.unidata.xml.XmlUtil
NULL_STRING, XML_HEADER
 
Constructor Summary
XmlEncoder()
          Create a new XmlEncoder.
 
Method Summary
protected  void addDefaultDelegates()
          Define the set of default delegates (e.g., for Rectangle, Font, etc.) for common objects that don't encode very well.
 void addDelegateForClass(Class theClass, XmlDelegate delegate)
          Add an XmlDelegate for the given class.
 void addHighPriorityDelegateForClass(Class theClass, XmlDelegate delegate)
          Add an XmlDelegate for the given class.
 void addSeedObject(Object seedObject)
          Add an existing object from the environement that is to be used in place of a newly created object.
 void clear()
          Clear the internal state this encoder keeps during the encoding/decoding process.
 Element createArrayElement(Object arrayObject)
          Create an Xml Element that represents the given object (which should be an array).
 ObjectClass createArrayObject(Element element)
          Create an array that contains a set of objects.
 Element createConstructorElement(List arguments)
          Construct a "constructor" tag that holds the set of argument objects.
 Element createConstructorElement(List arguments, List types)
          Construct a "constructor" tag that holds the set of argument objects with respective types.
 Element createElement(Object object)
          This acts as a wrapper around (Object, boolean) , passing in true for the checkPersistable flag.
 Element createElement(Object object, boolean checkDelegate)
          This acts as a wrapper around createElement(Object,Class,boolean,boolean), passing in true for the checkPersistable flag.
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.
protected  Element createElement(Object object, Class theClass, boolean checkPersistable, boolean checkDelegate)
          Create a xml representation of the object.
 Element createElementDontCheckDelegate(Object object)
          This acts as a wrapper around createElement(Object,boolean), passing in false for the checkDelegate flag.
 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.
 Element createElementForObject(Object object, Class theClass)
          Construct the Xml representation of the given object.
 Element createFactoryElement(Class factoryClass)
          Create a "factory" tag with the given factoryClass.
 Element createMethodElement(String methodName)
          Create a "method" xml element, one that represents a method call.
 Element createMethodElement(String methodName, Element contents)
          Create a "method" xml element, one that represents a method call.
 Element createMethodElement(String methodName, List argumentElements)
          Create a "method" xml element, one that represents a method call.
 Element createNullElement()
          Create a null element with no class.
 Element createNullElement(Class type)
          Create a null element with the given class (if non-null).
 Object createObject(Element element)
          Create an object defined by the given XML.
 Element createObjectConstructorElement(Object object, List arguments)
          Create an object tag that holds a constructor tag.
 Element createObjectConstructorElement(Object object, List arguments, List types)
          Create an object tag that holds a constructor tag.
 Object createObjectDontCheckDelegate(Element element)
          Create an object defined by the given XML.
 Element createObjectElement(Class objectClass)
          Create a "object" tag with the given objectClass.
 ObjectClass createObjectInner(Element element)
          Create the object defined by the given xml.
 ObjectClass createObjectInner(Element element, boolean checkDelegate)
          This method creates both the Object that the Element element represents and its Class.
 Element createPrimitiveArrayElement(Object primitiveArray)
          Create an Xml Element that represents the given array of primitives.
 ObjectClass createPrimitiveArrayObject(Element element)
          Create an array that contains a set of primitive objects.
 Element createPrimitiveElement(String primitiveName, Object value)
          Create the xml element for the given primitive value and name.
 ObjectClass createPrimitiveObject(Class primitiveClass, Element element)
          Create the primitive object defined by the given class and xml element.
 Object createPrimitiveObject(Class primitiveClass, String value)
          Create the primitive object defined by the given class and value.
 Element createPropertyElement(String propertyName, Element value)
          Create a "property" xml element, one that represents a bean property on an object.
 Element createReferenceElement(String id)
          Create an element that represents a reference to an already encoded object.
 Element createSerialElement(Class theClass, String serialRepresentation)
          Create a "serial" xml element, one that represents a serialized Object.
 ObjectClass createSerializedObject(Element parent)
          Deserialize the serialized object defined by the given parent xml element.
 Node createTextNode(String contents)
          A utility to create a text node
 void defineObjectId(Object theObject, String theId)
          Allow client code to predefine an object to id mapping.
static Object deserialize(byte[] bytes)
          A utility to deserialize the given bytes
static List findPropertyMethods(Class c)
          For the given class find the set of public set/get property methods.
static List findPropertyMethods(Class c, boolean returnGetters)
          _more_
 Class getClass(String className)
          Find the Class that corresponds to the given className.
 String getClassName(Class theClass)
          Get the String name of the given class.
protected  XmlDelegate getDelegate(Class theClass)
          Find the XmlDelegate that handles the given class.
 Document getDocument()
          Create (if needed) and return the xml Document for this encoder.
protected  Element getElementForObject(Object theObject)
          Return the DOM element that represents the given object.
 List getFieldElements(Object object, Hashtable propertyNames)
          Return a List of Xml Elements that represent the set of public fields in the given object.
protected  String getNextId()
          Utility method to return a unique (during a particular encoding) String id.
protected  Object getObjectFromId(String id)
          Returns the object (maybe null) that has the given id.
protected  String getObjectId(Object theObject)
          Return the encoding id defined for the given object.
 Class getPrimitiveClass(String name)
          For the given name (e.g., "int", "boolean") return the class (e.g., Integer.TYPE, Boolean.TYPE).
 Constructor getPrimitiveCtor(Class primitiveClass)
          Find the Constructor that creates objects of the given primitive class.
 String getPrimitiveName(Class primitiveClass)
          Return the name of the class to be used for the given class.
 List getPropertyElements(Object object, Hashtable propertyNames)
          Return a List of Xml Elements that represent the set of public properties in the given object.
 List getSpecialCaseElements(Object object)
          Handle certain objects in a special way.
 String getTextFromChild(Element parent)
          A utility to find the text node child of the given parent
protected  void init()
          This resets the state of this encoder.
protected  void initPrimitiveName()
          Initialize the mapping between names for primitives and their classes.
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.
protected  void invokeMethod(Object object, String methodName, Element element)
          Invoke the the method, identified by the given method name, on the given object.
 boolean isPrimitive(Class theClass)
          Is the given Class a primitive (e.g., an int, float, Integer, Double, etc.).
static void main(String[] args)
          Runs some tests.
 boolean methodOk(String methodName)
          Is the given method name one of the allowable methods to execute.
 Element newElement(String tagName)
          Create a new Element of the given tag name using the current document.
static void pr(String msg)
          A utility method to print out an error message if we are in debug mode.
 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.
static byte[] serialize(Serializable object)
          A utility to serialize the given object
 void setDocument(Document document)
          Set the xml Document used by this encoder.
protected  void setObject(String id, Object theObject)
          Define a mapping between the given id and the object.
protected  String setObjectId(Object theObject)
          Create a new id and define mappings between the id, object and DOM element.
 String setObjectId(Object theObject, Element element)
          Create a new id and define mappings between the id, object and DOM element.
 boolean test(Object o, boolean printXml)
          A simple test method.
 Element toElement(Object theObject)
          Create the DOM Element that represents the given object.
 Object toObject(Element node)
          Create an object from the given dom subtree.
 Object toObject(String xml)
          Create an object from the given xml.
 String toXml(Object theObject)
          Convert the given object to xml, formatting the xml (with spaces and newlines).
 String toXml(Object theObject, boolean formatXml)
          Convert the given object to xml.
 
Methods inherited from class ucar.unidata.xml.XmlUtil
addChildren, appendCdata, appendCdataBytes, attr, attr, attrs, attrs, attrs, attrs, calculateRFC2104HMAC, closeTag, comment, create, create, create, create, decodeBase64, encodeBase64, encodeString, ensureAttributes, findAncestor, findChild, findChildRecurseUp, findChildren, findChildrenRecurseUp, findDescendant, findDescendantFromPath, findDescendants, findDescendantsFromPath, findElement, findElement, findRoot, findUrlRefNode, findUrlRefNode, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getAttributeFromTree, getAttributeFromTree, getAttributeFromTree, getAttributesFromTree, getAttributesFromTree, getChildText, getDocument, getDocument, getDocument, getElement, getElements, getElements, getElements, getFirstChild, getGrandChildren, getGrandChildText, getHeader, getListOfElements, getRoot, getRoot, getRoot, hasAttribute, makeCDataNode, makeDocument, mergeAttributes, openTag, openTag, quote, removeChildren, setAttribute, setAttributes, tag, tag, toString, toString, toString, toString, toStringNoChildren, toStringWithHeader, toStringWithHeader, toStringWithHeader
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

debug

public static boolean debug
Just a debug flag.


METHOD_INIT

public static final String METHOD_INIT
The name of the init method that is called (if it exists) after an object is deserialized

See Also:
Constant Field Values

METHOD_PUT

public static final String METHOD_PUT
Method name for Hashtable.put

See Also:
Constant Field Values

METHOD_ADD

public static final String METHOD_ADD
Method name for List.add

See Also:
Constant Field Values

NAME_STRING

public static final String NAME_STRING
The name used in the xml for String objects.

See Also:
Constant Field Values

TAG_ARRAY

public static final String TAG_ARRAY
The tag name used for arrays.

See Also:
Constant Field Values

TAG_PARRAY

public static final String TAG_PARRAY
The tag name used for primitive arrays.

See Also:
Constant Field Values

TAG_CONSTRUCTOR

public static final String TAG_CONSTRUCTOR
The xml tag for constructors.

See Also:
Constant Field Values

TAG_FACTORY

public static final String TAG_FACTORY
The xml tag for factory objects.

See Also:
Constant Field Values

TAG_FIELD

public static final String TAG_FIELD
The xml tag for object fields.

See Also:
Constant Field Values

TAG_IGNORE

public static final String TAG_IGNORE
The xml tag when we want to ignore something?

See Also:
Constant Field Values

TAG_METHOD

public static final String TAG_METHOD
The xml tag for method calls.

See Also:
Constant Field Values

TAG_NULL

public static final String TAG_NULL
The xml tag for the null object.

See Also:
Constant Field Values

TAG_OBJECT

public static final String TAG_OBJECT
The xml tag for objects.

See Also:
Constant Field Values

TAG_PROPERTY

public static final String TAG_PROPERTY
The xml tag for properties.

See Also:
Constant Field Values

TAG_SERIAL

public static final String TAG_SERIAL
The xml tag for serialized objects.

See Also:
Constant Field Values

ATTR_CLASS

public static final String ATTR_CLASS
The name for the class attribute.

See Also:
Constant Field Values

ATTR_ENCODING

public static final String ATTR_ENCODING
The name for the encode attribute

See Also:
Constant Field Values

VALUE_BASE64

public static final String VALUE_BASE64
The value for the encode by base64

See Also:
Constant Field Values

ATTR_ID

public static final String ATTR_ID
The name for the id attribute.

See Also:
Constant Field Values

ATTR_IDREF

public static final String ATTR_IDREF
The name for the idref attribute.

See Also:
Constant Field Values

ATTR_NAME

public static final String ATTR_NAME
The name for the name attribute.

See Also:
Constant Field Values

ATTR_NULL

public static final String ATTR_NULL
The name for the null attribute.

See Also:
Constant Field Values

ATTR_STRINGVALUE

public static final String ATTR_STRINGVALUE
The name for the stringvalue attribute.

See Also:
Constant Field Values

ATTR_LENGTH

public static final String ATTR_LENGTH
The name for the length attribute.

See Also:
Constant Field Values

ATTR_VALUE

public static final String ATTR_VALUE
The name for the value attribute.

See Also:
Constant Field Values

document

protected Document document
The Xml document we create.


delegateClasses

protected ArrayList delegateClasses
List of classes that we have corresponding XmlDelegates for.


delegates

protected ArrayList delegates
The List of XmlDelegates that know how to handle certain classes.

Constructor Detail

XmlEncoder

public XmlEncoder()
Create a new XmlEncoder.

Method Detail

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.

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.

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(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">
  ...
  < 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.

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.

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 eleme