net.sourceforge.spedit.core
Class XMLDocument

java.lang.Object
  |
  +--org.jdom.Document
        |
        +--net.sourceforge.spedit.core.XMLDocument
All Implemented Interfaces:
Cloneable, Document, Serializable, StyledDocument, TreeModel

public class XMLDocument
extends org.jdom.Document
implements StyledDocument, TreeModel

The XMLDocument class wraps a Swing Document around a JDOM XML document. There is an article on the website that describes how the design of this class was made, for further understanding you should read the source code.

When using the XMLDocument API you should take great care of the objects that you manipulate. Here are some points that should be clear:

See Also:
Serialized Form

Inner Class Summary
static class XMLDocument.DocumentEvent
          The DocumentEvent class represents a set of modifications that have been done on the document.
static class XMLDocument.ElementEdit
          This class stores a single change made on an element of the document.
static class XMLDocument.Position
          Implements the Swing position interface in order to keep track of changes that occur in an XMLDocument.
 
Field Summary
protected  GapContent content
           
protected  Vector documentListeners
           
protected  Position endPosition
           
protected  Font font
           
protected static int GAP_LENGTH
           
static String PARSER
           
protected  List positions
           
protected static int POSITIONS_THRESHOLD
           
protected  Hashtable properties
           
protected  Element[] roots
           
static org.jdom.input.SAXBuilder saxBuilder
           
protected  Position startPosition
           
protected  Vector treeModelListeners
           
protected  Vector undoableEditListeners
           
static org.jdom.input.JDOMFactory xmlFactory
           
static org.jdom.output.XMLOutputter xmlOutputter
           
 
Fields inherited from class org.jdom.Document
docType
 
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
 
Constructor Summary
XMLDocument()
          Creates a new blank XMLDocument.
XMLDocument(org.jdom.Element rootElement)
          Creates a new XMLDocument with the given rootElement as a root node.
XMLDocument(org.jdom.Element rootElement, org.jdom.DocType docType)
          Creates a new XMLDocument with the given rootElement as a root node, with the specified document type.
 
Method Summary
 void addDocumentListener(DocumentListener dl)
           
 Style addStyle(String nm, Style parent)
           
 void addTreeModelListener(TreeModelListener l)
          Adds a listener for the TreeModelEvent posted after the tree changes.
 void addUndoableEditListener(UndoableEditListener ul)
           
protected  org.jdom.Element convertElement(org.jdom.Element e)
          Converts the given element into a natural JDOM element.
 org.jdom.Document convertToJDOM()
          Generates a natural JDOM document.
 Position createBackwardPosition(int n)
           
 Position createForwardPosition(int n)
           
 Position createPosition(int n)
           
protected  void filter(org.jdom.Element element, XMLViewFactory factory)
          Filters the given element recursively.
 void filter(XMLViewFactory factory)
          Filters the given document, removing text nodes that contain no characters.
protected  void fireDocumentEvent(XMLDocument.DocumentEvent evt)
           
 Color getBackground(AttributeSet attr)
           
 Element getCharacterElement(int pos)
           
 Object getChild(Object parent, int index)
          Returns the child of parent at index index in the parent's child array.
 int getChildCount(Object parent)
          Returns the number of children of parent.
 Element getDefaultRootElement()
          Returns the default root element of the document.
 Element getElementAt(int offset)
          Search the Swing Element which is located at the specified position.
 Position getEndPosition()
           
 Font getFont(AttributeSet attr)
           
 Color getForeground(AttributeSet attr)
           
 int getIndexOfChild(Object parent, Object child)
          Returns the index of child in parent.
 int getLength()
           
 Style getLogicalStyle(int p)
           
 Element getParagraphElement(int offset)
          Returns the XMLElement that contains the specified offset.
 Object getProperty(Object key)
           
 Object getRoot()
          Returns the root of the tree.
 Element[] getRootElements()
          Returns an array of elements which only contains the default document root.
 Position getStartPosition()
           
 Style getStyle(String nm)
           
 String getText(int offset, int length)
           
 void getText(int offset, int length, Segment s)
          Fetches the text contained within the given portion of the document.
 GapContent getTextContent()
          Returns the Content object that represents the text contained in this document.
protected  void init()
          Initializes the XMLDocument.
 void insertElement(XMLElement element, int offset)
          Prepends the element at the given offset in the text.
 void insertString(int offset, String text, AttributeSet attrs)
          Prepends the given string at the given offset in the text.
protected  boolean isGarbage(XMLText elt)
          Tells wether or not the given element is a garbage element.
 boolean isLeaf(Object node)
          Returns true if node is a leaf.
static XMLDocument loadFromFile(File file, XMLViewFactory fact)
          Loads the given file and tries to generate an XMLDocument instance from its content.
 void putProperty(Object key, Object value)
           
 void remove(int start, int end)
           
 void removeDocumentListener(DocumentListener dl)
           
 Object removeProperty(Object key)
           
 void removeStyle(String nm)
           
 void removeTreeModelListener(TreeModelListener l)
          Removes a listener previously added with addTreeModelListener().
 void removeUndoableEditListener(UndoableEditListener ul)
           
 void render(Runnable renderer)
           
 void saveToFile(File file)
          Saves the current XMLDocument into the given file.
 void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)
           
 void setLogicalStyle(int pos, Style s)
           
 void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)
           
 org.jdom.Document setRootElement(org.jdom.Element elem)
           
 String toString()
          Returns a string rtpresenting the XML contained in this document.
 void updatePositions(int offset, int length)
          Update all the position objects registered inside the document.
 void valueForPathChanged(TreePath path, Object newValue)
          Messaged when the user has altered the value for the item identified by path to newValue.
protected  void writeLock()
           
protected  void writeUnlock()
           
 
Methods inherited from class org.jdom.Document
addContent, addContent, clone, equals, getContent, getDocType, getMixedContent, getProcessingInstruction, getProcessingInstructions, getProcessingInstructions, getRootElement, getSerializedForm, hashCode, removeContent, removeContent, removeProcessingInstruction, removeProcessingInstructions, setContent, setDocType, setMixedContent, setProcessingInstructions
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

PARSER

public static final String PARSER

saxBuilder

public static final org.jdom.input.SAXBuilder saxBuilder

xmlOutputter

public static final org.jdom.output.XMLOutputter xmlOutputter

xmlFactory

public static final org.jdom.input.JDOMFactory xmlFactory

POSITIONS_THRESHOLD

protected static final int POSITIONS_THRESHOLD

GAP_LENGTH

protected static final int GAP_LENGTH

roots

protected Element[] roots

documentListeners

protected Vector documentListeners

undoableEditListeners

protected Vector undoableEditListeners

treeModelListeners

protected Vector treeModelListeners

properties

protected Hashtable properties

positions

protected List positions

content

protected GapContent content

startPosition

protected Position startPosition

endPosition

protected Position endPosition

font

protected Font font
Constructor Detail

XMLDocument

public XMLDocument()
Creates a new blank XMLDocument.

XMLDocument

public XMLDocument(org.jdom.Element rootElement)
Creates a new XMLDocument with the given rootElement as a root node.
Parameters:
rootElement - the root node of this XMLDocument.

XMLDocument

public XMLDocument(org.jdom.Element rootElement,
                   org.jdom.DocType docType)

Creates a new XMLDocument with the given rootElement as a root node, with the specified document type. This constructor is not really useful, you should not use it as no consistency check is made with the given doctype.

This constructor is provided for JDOMFactory consistency purposes.

Parameters:
rootElement - the root node of this XMLDocument.
docType - the root node of this XMLDocument.
Method Detail

init

protected void init()
Initializes the XMLDocument. It should not be called after document creation. This method is present to provide a common initialization facility for the various constructors, which is a technique cleaner that this(...) calls, as I allows super(...) constructor calls with more paramters.

loadFromFile

public static XMLDocument loadFromFile(File file,
                                       XMLViewFactory fact)

Loads the given file and tries to generate an XMLDocument instance from its content. This method returns a new XMLDocument in case of success, or of course null in case of failure.

If an exception occurs, it will be dumped on stderr.

Parameters:
file - Is the XML source file to be loaded
fact - Is the XMLViewFactory used to filter the element contents. It can be set to null.

saveToFile

public void saveToFile(File file)
                throws IOException

Saves the current XMLDocument into the given file. If an exception it will be thrown.


convertToJDOM

public org.jdom.Document convertToJDOM()

Generates a natural JDOM document. A natural JDOM document means a document that does not have the fancy elements, such as XMLText elements as children. Actually an XMLDocument can not really be used "as is" with the JDOM facilities, you first have to convert it using this method.

Note that if you plan to customize the XMLElement content you should extend the convertElement behaviour.

Returns:
A natural JDOM copy of this document. The new document will have completely different element references, so you don't have to worry about changes in the current document.
See Also:
convertElement(org.jdom.Element)

convertElement

protected org.jdom.Element convertElement(org.jdom.Element e)
Converts the given element into a natural JDOM element. This methods actually replaces XMLText elements by strings added to the new element using the addContent method of the org.jdom.Element.
Parameters:
e - The elements that will serve as a clone model for the return value.

filter

public void filter(XMLViewFactory factory)

Filters the given document, removing text nodes that contain no characters. Those strings are always present inside an XML document that you have just loaded. This method should only be called when the document content has been (re)set.

In addition to that the filter looks in the given factory for information on how to filter element textual content, which can be for example stripping of leading and trailing spaces.

Parameters:
factory - The factory from which the information will be extracted.

filter

protected void filter(org.jdom.Element element,
                      XMLViewFactory factory)
Filters the given element recursively. Note that this method is desctructive, so you should not use it without being sure you do not remove valuable information.
Parameters:
element - the element to filter.
factory - the factory from which filtering information can be found.

isGarbage

protected boolean isGarbage(XMLText elt)
Tells wether or not the given element is a garbage element. A garbage element is typically an element that only contains blank characters.
Parameters:
elt - The XMLText element to analyze. This only applies to this kind of elements as they are the only susceptible to contain only text in the XMLDocument model.

insertElement

public void insertElement(XMLElement element,
                          int offset)
Prepends the element at the given offset in the text.
Parameters:
element - is the element that will be inserted.
offset - is the offset of the insertion point in the text.

getDefaultRootElement

public Element getDefaultRootElement()
Returns the default root element of the document. In the particular case of an XMLDocument, there is a always a single root.
Specified by:
getDefaultRootElement in interface Document

getRootElements

public Element[] getRootElements()
Returns an array of elements which only contains the default document root.
Specified by:
getRootElements in interface Document

setRootElement

public org.jdom.Document setRootElement(org.jdom.Element elem)
Overrides:
setRootElement in class org.jdom.Document

getParagraphElement

public Element getParagraphElement(int offset)
Returns the XMLElement that contains the specified offset. The name of this method is a little bit abusive, as the actual XMLElement may not a be a paragraph element, but this is provided to conform to the Swing document interface.
Specified by:
getParagraphElement in interface StyledDocument

getElementAt

public Element getElementAt(int offset)
Search the Swing Element which is located at the specified position. If the position is negative or superior to the document text length, then null is returned.
Parameters:
offset - The offset in the text, starting at 0, ending at document.getLength(), exclusive.
Returns:
The searched Element or null if the position is out of the document bounds.

addDocumentListener

public void addDocumentListener(DocumentListener dl)
Specified by:
addDocumentListener in interface Document

removeDocumentListener

public void removeDocumentListener(DocumentListener dl)
Specified by:
removeDocumentListener in interface Document

addUndoableEditListener

public void addUndoableEditListener(UndoableEditListener ul)
Specified by:
addUndoableEditListener in interface Document

removeUndoableEditListener

public void removeUndoableEditListener(UndoableEditListener ul)
Specified by:
removeUndoableEditListener in interface Document

getProperty

public Object getProperty(Object key)
Specified by:
getProperty in interface Document

putProperty

public void putProperty(Object key,
                        Object value)
Specified by:
putProperty in interface Document

removeProperty

public Object removeProperty(Object key)

remove

public void remove(int start,
                   int end)
Specified by:
remove in interface Document

insertString

public void insertString(int offset,
                         String text,
                         AttributeSet attrs)
Prepends the given string at the given offset in the text. The given attributes will be merged into the containing element attributes.
Specified by:
insertString in interface Document
Parameters:
offset - the offset at which text will be prepended.
text - the text to be inserted.
attrs - the attributes that will be merged (but will never override the attributes already defined in the parent). Important: these attributes must be XMLAttributes to work.

getText

public String getText(int offset,
                      int length)
               throws BadLocationException
Specified by:
getText in interface Document

getText

public void getText(int offset,
                    int length,
                    Segment s)
             throws BadLocationException
Fetches the text contained within the given portion of the document. If the partialReturn property on the txt parameter is false, the data returned in the Segment will be the entire length requested and may or may not be a copy depending upon how the data was stored. If the partialReturn property is true, only the amount of text that can be returned without creating a copy is returned. Using partial returns will give better performance for situations where large parts of the document are being scanned.
Specified by:
getText in interface Document

getLength

public int getLength()
Specified by:
getLength in interface Document

getStartPosition

public Position getStartPosition()
Specified by:
getStartPosition in interface Document

getEndPosition

public Position getEndPosition()
Specified by:
getEndPosition in interface Document

createPosition

public Position createPosition(int n)
Specified by:
createPosition in interface Document

createBackwardPosition

public Position createBackwardPosition(int n)

createForwardPosition

public Position createForwardPosition(int n)

getTextContent

public GapContent getTextContent()
Returns the Content object that represents the text contained in this document.

render

public void render(Runnable renderer)
Specified by:
render in interface Document

writeLock

protected void writeLock()

writeUnlock

protected void writeUnlock()

addStyle

public Style addStyle(String nm,
                      Style parent)
Specified by:
addStyle in interface StyledDocument

getStyle

public Style getStyle(String nm)
Specified by:
getStyle in interface StyledDocument

removeStyle

public void removeStyle(String nm)
Specified by:
removeStyle in interface StyledDocument

getCharacterElement

public Element getCharacterElement(int pos)
Specified by:
getCharacterElement in interface StyledDocument

getBackground

public Color getBackground(AttributeSet attr)
Specified by:
getBackground in interface StyledDocument

getFont

public Font getFont(AttributeSet attr)
Specified by:
getFont in interface StyledDocument

getForeground

public Color getForeground(AttributeSet attr)
Specified by:
getForeground in interface StyledDocument

getLogicalStyle

public Style getLogicalStyle(int p)
Specified by:
getLogicalStyle in interface StyledDocument

setCharacterAttributes

public void setCharacterAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Specified by:
setCharacterAttributes in interface StyledDocument

setLogicalStyle

public void setLogicalStyle(int pos,
                            Style s)
Specified by:
setLogicalStyle in interface StyledDocument

setParagraphAttributes

public void setParagraphAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Specified by:
setParagraphAttributes in interface StyledDocument

getRoot

public Object getRoot()
Returns the root of the tree. Returns null only if the tree has no nodes.
Specified by:
getRoot in interface TreeModel
Returns:
the root of the tree

getChild

public Object getChild(Object parent,
                       int index)
Returns the child of parent at index index in the parent's child array. parent must be a node previously obtained from this data source. This should not return null if index is a valid index for parent (that is index >= 0 && index < getChildCount(parent)). @param parent a node in the tree, obtained from this data source @return the child of parent at index index
Specified by:
getChild in interface TreeModel

getChildCount

public int getChildCount(Object parent)
Returns the number of children of parent. Returns 0 if the node is a leaf or if it has no children. parent must be a node previously obtained from this data source.
Specified by:
getChildCount in interface TreeModel
Parameters:
parent - a node in the tree, obtained from this data source
Returns:
the number of children of the node parent

isLeaf

public boolean isLeaf(Object node)
Returns true if node is a leaf. It is possible for this method to return false even if node has no children. A directory in a filesystem, for example, may contain no files; the node representing the directory is not a leaf, but it also has no children.
Specified by:
isLeaf in interface TreeModel
Parameters:
node - a node in the tree, obtained from this data source
Returns:
true if node is a leaf

valueForPathChanged

public void valueForPathChanged(TreePath path,
                                Object newValue)
Messaged when the user has altered the value for the item identified by path to newValue. If newValue signifies a truly new value the model should post a treeNodesChanged event.
Specified by:
valueForPathChanged in interface TreeModel
Parameters:
path - path to the node that the user has altered.
newValue - the new value from the TreeCellEditor.

getIndexOfChild

public int getIndexOfChild(Object parent,
                           Object child)
Returns the index of child in parent.
Specified by:
getIndexOfChild in interface TreeModel

addTreeModelListener

public void addTreeModelListener(TreeModelListener l)
Adds a listener for the TreeModelEvent posted after the tree changes.
Specified by:
addTreeModelListener in interface TreeModel
Parameters:
l - the listener to add
See Also:
removeTreeModelListener(javax.swing.event.TreeModelListener)

removeTreeModelListener

public void removeTreeModelListener(TreeModelListener l)
Removes a listener previously added with addTreeModelListener().
Specified by:
removeTreeModelListener in interface TreeModel
Parameters:
l - the listener to remove
See Also:
addTreeModelListener(javax.swing.event.TreeModelListener)

fireDocumentEvent

protected void fireDocumentEvent(XMLDocument.DocumentEvent evt)

toString

public String toString()
Returns a string rtpresenting the XML contained in this document. This string can be written to a file.
Overrides:
toString in class org.jdom.Document

updatePositions

public void updatePositions(int offset,
                            int length)
Update all the position objects registered inside the document. This method is specific to the XMLDocument. It is called by the fire method of DocumentEvent.ElementChange objects.
Parameters:
offset - is the offset where the changed has occured in the document. offset >=0
length - indicates the length of the change. If length>0 then the change is an insertion of length characters from offset.
In case length <= 0 then the change is interpreted as a deletion of lenght characters starting at offset.