You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@xerces.apache.org by le...@apache.org on 2001/08/10 03:18:18 UTC
cvs commit: xml-xerces/java/src/org/apache/xerces/dom CoreDOMImplementationImpl.java CoreDocumentImpl.java AttrImpl.java AttrNSImpl.java AttributeMap.java CDATASectionImpl.java CharacterDataImpl.java ChildNode.java CommentImpl.java DOMImplementationImpl.java DeferredAttrImpl.java DeferredAttrNSImpl.java DeferredDocumentImpl.java DeferredDocumentTypeImpl.java DeferredElementDefinitionImpl.java DeferredElementImpl.java DeferredElementNSImpl.java DeferredEntityImpl.java DeferredEntityReferenceImpl.java DocumentFragmentImpl.java DocumentImpl.java DocumentTypeImpl.java ElementDefinitionImpl.java ElementImpl.java ElementNSImpl.java EntityImpl.java EntityReferenceImpl.java NamedNodeMapImpl.java NodeImpl.java NotationImpl.java ParentNode.java ProcessingInstructionImpl.java TextImpl.java
lehors 01/08/09 18:18:17
Modified: java/src/org/apache/xerces/dom AttrImpl.java AttrNSImpl.java
AttributeMap.java CDATASectionImpl.java
CharacterDataImpl.java ChildNode.java
CommentImpl.java DOMImplementationImpl.java
DeferredAttrImpl.java DeferredAttrNSImpl.java
DeferredDocumentImpl.java
DeferredDocumentTypeImpl.java
DeferredElementDefinitionImpl.java
DeferredElementImpl.java DeferredElementNSImpl.java
DeferredEntityImpl.java
DeferredEntityReferenceImpl.java
DocumentFragmentImpl.java DocumentImpl.java
DocumentTypeImpl.java ElementDefinitionImpl.java
ElementImpl.java ElementNSImpl.java EntityImpl.java
EntityReferenceImpl.java NamedNodeMapImpl.java
NodeImpl.java NotationImpl.java ParentNode.java
ProcessingInstructionImpl.java TextImpl.java
Added: java/src/org/apache/xerces/dom
CoreDOMImplementationImpl.java
CoreDocumentImpl.java
Log:
This new implementation supports two different DOMImplementation classes.
CoreDOMImplementationImpl, along with CoreDocumentImpl, only supports DOM
Core. DOMImplementationImpl, along with DocumentImpl, inherits from the
Core classes and adds support for optional modules (MutationEvents, Ranges,
Traversal) as well as the Deferred DOM.
Not much code has actually changed, but quite a lot of code has been moved
around. In particular, all the event code has been moved to DocumentImpl.
Instead of firing events directly, other classes now simply notify the
document of mutations. This allows us to have a core document class which
does nothing in response to these notifications, and a more complete class
which fires mutation events as well as update ranges and iterators if there
are any.
The net result is that one can make a jar which only contains the core DOM,
that is half the size of the complete DOM. The code is also cleaner
although fully backward compatible. Existing applications using the
DOMImplemenationImpl and DocumentImpl classes will keep working just fine.
In addition, although the gain can't be huge (because I already optimized
the code quite a bit ;-), the Core DOM can only be smaller in memory and
faster. At the same time memory consumption and performance remain the same
for the complete DOM. I actually noticed some small difference in
performance (~2%) but it turns out to be either a loss or a gain depending
on the jvm, so...
When we implement the DOM Level 3 Registry mechanism one will be able to
dynamically select one implementation or the other, depending on the
features it needs.
As an extra bonus the deferred DOM is a clean layer on top of the other
classes again, and can therefore be left out if desired.
Revision Changes Path
1.36 +49 -265 xml-xerces/java/src/org/apache/xerces/dom/AttrImpl.java
Index: AttrImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/AttrImpl.java,v
retrieving revision 1.35
retrieving revision 1.36
diff -u -r1.35 -r1.36
--- AttrImpl.java 2001/07/24 00:42:26 1.35
+++ AttrImpl.java 2001/08/10 01:18:16 1.36
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999 The Apache Software Foundation. All rights
+ * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -67,10 +67,7 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
-import org.w3c.dom.events.MutationEvent;
-import org.apache.xerces.dom.events.MutationEventImpl;
-
/**
* Attribute represents an XML-style attribute of an
* Element. Typically, the allowable values are controlled by its
@@ -109,7 +106,7 @@
*
* <p>AttrImpl used to inherit from ParentNode. It now directly inherits from
* NodeImpl and provide its own implementation of the ParentNode's behavior.
- * The reason is that we now try and avoid to always creating a Text node to
+ * The reason is that we now try and avoid to always create a Text node to
* hold the value of an attribute. The DOM spec requires it, so we still have
* to do it in case getFirstChild() is called for instance. The reason
* attribute values are stored as a list of nodes is so that they can carry
@@ -130,10 +127,13 @@
* To avoid too much duplicated code, I got rid of ParentNode and renamed
* ChildAndParentNode, which I never really liked, to ParentNode for
* simplicity, this doesn't make much of a difference in memory usage because
- * there are only very objects that are only a Parent. This is only true now
- * because AttrImpl now inherits directly from NodeImpl and has its own
+ * there are only very few objects that are only a Parent. This is only true
+ * now because AttrImpl now inherits directly from NodeImpl and has its own
* implementation of the ParentNode's node behavior. So there is still some
* duplicated code there.
+ * <p>
+ * This class doesn't directly support mutation events, however, it notifies
+ * the document when mutations are performed so that the document class do so.
*
* <p><b>WARNING</b>: Some of the code here is partially duplicated in
* ParentNode, be careful to keep these two classes in sync!
@@ -178,7 +178,7 @@
* Attribute has no public constructor. Please use the factory
* method in the Document class.
*/
- protected AttrImpl(DocumentImpl ownerDocument, String name) {
+ protected AttrImpl(CoreDocumentImpl ownerDocument, String name) {
super(ownerDocument);
this.name = name;
/** False for default attributes. */
@@ -186,7 +186,7 @@
hasStringValue(true);
}
- // for AttrNS
+ // for AttrNSImpl
protected AttrImpl() {}
// create a real text node as child if we don't have one yet
@@ -209,7 +209,7 @@
* NON-DOM
* set the ownerDocument of this node and its children
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
if (needsSyncChildren()) {
synchronizeChildren();
}
@@ -317,26 +317,9 @@
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
-
- LCount lc=null;
- String oldvalue="";
- DocumentImpl ownerDocument = ownerDocument();
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // Only DOMAttrModified need be produced directly.
- // It needs the previous value. Note that this may be
- // a treewalk, so I've put it under the conditional.
- lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0 && ownerNode!=null)
- {
- oldvalue=getValue();
- }
-
- } // End mutation preprocessing
-
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
+ CoreDocumentImpl ownerDocument = ownerDocument();
+ String oldvalue = "";
+ if (ownerDocument.getMutationEvents()) {
// Can no longer just discard the kids; they may have
// event listeners waiting for them to disconnect.
if (needsSyncChildren()) {
@@ -344,7 +327,8 @@
}
if (value != null) {
if (hasStringValue()) {
- // temporarily sets an actual text node as our child so
+ oldvalue = (String) value;
+ // create an actual text node as our child so
// that we can use it in the event
if (textNode == null) {
textNode = (TextImpl)
@@ -359,11 +343,12 @@
textNode.ownerNode = this;
textNode.isOwned(true);
hasStringValue(false);
- internalRemoveChild(textNode, MUTATION_LOCAL);
+ internalRemoveChild(textNode, true);
}
else {
+ oldvalue = getValue();
while (value != null) {
- internalRemoveChild((Node) value, MUTATION_LOCAL);
+ internalRemoveChild((Node) value, true);
}
}
}
@@ -388,25 +373,20 @@
// Note that aggregate events are NOT dispatched here,
// since we need to combine the remove and insert.
isSpecified(true);
- if(MUTATIONEVENTS && ownerDocument.mutationEvents) {
+ if (ownerDocument.getMutationEvents()) {
// if there are any event handlers create a real node
internalInsertBefore(ownerDocument.createTextNode(newvalue),
- null, MUTATION_LOCAL);
+ null, true);
hasStringValue(false);
+ // notify document
+ ownerDocument.modifiedAttrValue(this, oldvalue);
} else {
// directly store the string
value = newvalue;
hasStringValue(true);
+ changed();
}
-
- changed(); // ***** Is this redundant?
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION POST-EVENTS:
- dispatchAggregateEvents(this,oldvalue,MutationEvent.MODIFICATION);
- }
-
} // setValue(String)
/**
@@ -649,7 +629,7 @@
public Node insertBefore(Node newChild, Node refChild)
throws DOMException {
// Tail-call; optimizer should be able to do good things with.
- return internalInsertBefore(newChild,refChild,MUTATION_ALL);
+ return internalInsertBefore(newChild, refChild, false);
} // insertBefore(Node,Node):Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
@@ -657,10 +637,10 @@
* insertBefore operation allows us to do so. It is not intended
* for use by application programs.
*/
- Node internalInsertBefore(Node newChild, Node refChild,int mutationMask)
+ Node internalInsertBefore(Node newChild, Node refChild, boolean replace)
throws DOMException {
- DocumentImpl ownerDocument = ownerDocument();
+ CoreDocumentImpl ownerDocument = ownerDocument();
boolean errorChecking = ownerDocument.errorChecking;
if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) {
@@ -747,18 +727,8 @@
makeChildNode(); // make sure we have a node and not a string
- EnclosingAttr enclosingAttr=null;
- if (MUTATIONEVENTS && ownerDocument.mutationEvents
- && (mutationMask&MUTATION_AGGREGATE)!=0) {
- // MUTATION PREPROCESSING
- // No direct pre-events, but if we're within the scope
- // of an Attr and DOMAttrModified was requested,
- // we need to preserve its previous value.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- enclosingAttr=getEnclosingAttr();
- }
- }
+ // notify document
+ ownerDocument.insertingNode(this, replace);
// Convert to internal type, to avoid repeated casting
ChildNode newInternal = (ChildNode)newChild;
@@ -815,61 +785,9 @@
}
changed();
-
- if (MUTATIONEVENTS && ownerDocument.mutationEvents) {
- // MUTATION POST-EVENTS:
- // "Local" events (non-aggregated)
- if ((mutationMask&MUTATION_LOCAL) != 0) {
- // New child is told it was inserted, and where
- LCount lc = LCount.lookup(MutationEventImpl.DOM_NODE_INSERTED);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_NODE_INSERTED,
- true,false,this,null,
- null,null,(short)0);
- newInternal.dispatchEvent(me);
- }
-
- // If within the Document, tell the subtree it's been added
- // to the Doc.
- lc=LCount.lookup(
- MutationEventImpl.DOM_NODE_INSERTED_INTO_DOCUMENT);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- NodeImpl eventAncestor=this;
- if (enclosingAttr!=null)
- eventAncestor=
- (NodeImpl)(enclosingAttr.node.getOwnerElement());
- if (eventAncestor!=null) { // Might have been orphan Attr
- NodeImpl p=eventAncestor;
- while (p!=null) {
- eventAncestor=p; // Last non-null ancestor
- // In this context, ancestry includes
- // walking back from Attr to Element
- if (p.getNodeType()==ATTRIBUTE_NODE) {
- p=(ElementImpl)((AttrImpl)p).getOwnerElement();
- }
- else {
- p=p.parentNode();
- }
- }
- if (eventAncestor.getNodeType()==Node.DOCUMENT_NODE) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl
- .DOM_NODE_INSERTED_INTO_DOCUMENT,
- false,false,null,null,
- null,null,(short)0);
- dispatchEventToSubtree(newInternal,me);
- }
- }
- }
- }
- // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified
- // (Common to most kinds of mutation)
- if ((mutationMask&MUTATION_AGGREGATE) != 0) {
- dispatchAggregateEvents(enclosingAttr);
- }
- }
+ // notify document
+ ownerDocument.insertedNode(this, newInternal, replace);
checkNormalizationAfterInsert(newInternal);
@@ -897,7 +815,7 @@
throw new DOMException(DOMException.NOT_FOUND_ERR,
"DOM008 Not found");
}
- return internalRemoveChild(oldChild,MUTATION_ALL);
+ return internalRemoveChild(oldChild, false);
} // removeChild(Node) :Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
@@ -905,10 +823,10 @@
* removeChild operation allows us to do so. It is not intended
* for use by application programs.
*/
- Node internalRemoveChild(Node oldChild,int mutationMask)
+ Node internalRemoveChild(Node oldChild, boolean replace)
throws DOMException {
- DocumentImpl ownerDocument = ownerDocument();
+ CoreDocumentImpl ownerDocument = ownerDocument();
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
throw new DOMException(
@@ -921,75 +839,18 @@
}
}
- // notify document
- ownerDocument.removedChildNode(oldChild);
-
ChildNode oldInternal = (ChildNode) oldChild;
- EnclosingAttr enclosingAttr=null;
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // If we're within the scope of an Attr and DOMAttrModified
- // was requested, we need to preserve its previous value for
- // that event.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttr=getEnclosingAttr();
- }
-
- if( (mutationMask&MUTATION_LOCAL) != 0)
- {
- // Child is told that it is about to be removed
- lc=LCount.lookup(MutationEventImpl.DOM_NODE_REMOVED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_NODE_REMOVED,
- true,false,this,null,
- null,null,(short)0);
- oldInternal.dispatchEvent(me);
- }
-
- // If within Document, child's subtree is informed that it's
- // losing that status
- lc=LCount.lookup(
- MutationEventImpl.DOM_NODE_REMOVED_FROM_DOCUMENT);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- NodeImpl eventAncestor=this;
- if(enclosingAttr!=null)
- eventAncestor=
- (NodeImpl) enclosingAttr.node.getOwnerElement();
- if(eventAncestor!=null) // Might have been orphan Attr
- {
- for(NodeImpl p=eventAncestor.parentNode();
- p!=null;
- p=p.parentNode())
- {
- eventAncestor=p; // Last non-null ancestor
- }
- if(eventAncestor.getNodeType()==Node.DOCUMENT_NODE)
- {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl
- .DOM_NODE_REMOVED_FROM_DOCUMENT,
- false,false,
- null,null,null,null,(short)0);
- dispatchEventToSubtree(oldInternal,me);
- }
- }
- }
- }
- } // End mutation preprocessing
+ // notify document
+ ownerDocument.removingNode(this, oldInternal, replace);
// Patch linked list around oldChild
// Note: lastChild == firstChild.previousSibling
if (oldInternal == value) { // oldInternal == firstChild
// removing first child
oldInternal.isFirstChild(false);
- value = oldInternal.nextSibling; // firstChild = oldInternal.nextSibling
+ // next line is: firstChild = oldInternal.nextSibling
+ value = oldInternal.nextSibling;
ChildNode firstChild = (ChildNode) value;
if (firstChild != null) {
firstChild.isFirstChild(true);
@@ -1020,14 +881,8 @@
changed();
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION POST-EVENTS:
- // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
- // if required. (Common to most kinds of mutation)
- if( (mutationMask&MUTATION_AGGREGATE) != 0)
- dispatchAggregateEvents(enclosingAttr);
- } // End mutation postprocessing
+ // notify document
+ ownerDocument.removedNode(this, replace);
checkNormalizationAfterRemove(oldPreviousSibling);
@@ -1067,30 +922,17 @@
// this as either desirable or undesirable, but hints that
// aggregations should be issued only once per user request.
- EnclosingAttr enclosingAttr=null;
- DocumentImpl ownerDocument = ownerDocument();
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // If we're within the scope of an Attr and DOMAttrModified
- // was requested, we need to preserve its previous value for
- // that event.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttr=getEnclosingAttr();
- }
- } // End mutation preprocessing
+ // notify document
+ CoreDocumentImpl ownerDocument = ownerDocument();
+ ownerDocument.replacingNode(this);
- internalInsertBefore(newChild, oldChild,MUTATION_LOCAL);
+ internalInsertBefore(newChild, oldChild, true);
if (newChild != oldChild) {
- internalRemoveChild(oldChild,MUTATION_LOCAL);
+ internalRemoveChild(oldChild, true);
}
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- dispatchAggregateEvents(enclosingAttr);
- }
+ // notify document
+ ownerDocument.replacedNode(this);
return oldChild;
}
@@ -1196,64 +1038,6 @@
}
/**
- * Synchronizes the node's children with the internal structure.
- * Fluffing the children at once solves a lot of work to keep
- * the two structures in sync. The problem gets worse when
- * editing the tree -- this makes it a lot easier.
- * Even though this is only used in deferred classes this method is
- * put here so that it can be shared by all deferred classes.
- */
- protected final void synchronizeChildren(int nodeIndex) {
-
- // we don't want to generate any event for this so turn them off
- DeferredDocumentImpl ownerDocument =
- (DeferredDocumentImpl) ownerDocument();
- boolean orig = ownerDocument.mutationEvents;
- ownerDocument.mutationEvents = false;
-
- // no need to sync in the future
- needsSyncChildren(false);
-
- // create children and link them as siblings or simply store the value
- // as a String if all we have is one piece of text
- int last = ownerDocument.getLastChild(nodeIndex);
- int prev = ownerDocument.getPrevSibling(last);
- if (prev == -1) {
- value = ownerDocument.getNodeValueString(last);
- hasStringValue(true);
- }
- else {
- ChildNode firstNode = null;
- ChildNode lastNode = null;
- for (int index = last; index != -1;
- index = ownerDocument.getPrevSibling(index)) {
-
- ChildNode node = (ChildNode)ownerDocument.getNodeObject(index);
- if (lastNode == null) {
- lastNode = node;
- }
- else {
- firstNode.previousSibling = node;
- }
- node.ownerNode = this;
- node.isOwned(true);
- node.nextSibling = firstNode;
- firstNode = node;
- }
- if (lastNode != null) {
- value = firstNode; // firstChild = firstNode
- firstNode.isFirstChild(true);
- lastChild(lastNode);
- }
- hasStringValue(false);
- }
-
- // set mutation events flag back to its original value
- ownerDocument.mutationEvents = orig;
-
- } // synchronizeChildren()
-
- /**
* Checks the normalized state of this node after inserting a child.
* If the inserted child causes this node to be unnormalized, then this
* node is flagged accordingly.
@@ -1337,10 +1121,10 @@
// perform default deseralization
ois.defaultReadObject();
-
- // hardset synchildren - so we don't try to sync- it does not make any sense
- // to try to synchildren when we just desealize object.
+ // hardset synchildren - so we don't try to sync -
+ // it does not make any sense to try to synchildren when we just
+ // deserialize object.
needsSyncChildren(false);
} // readObject(ObjectInputStream)
1.21 +13 -13 xml-xerces/java/src/org/apache/xerces/dom/AttrNSImpl.java
Index: AttrNSImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/AttrNSImpl.java,v
retrieving revision 1.20
retrieving revision 1.21
diff -u -r1.20 -r1.21
--- AttrNSImpl.java 2001/07/24 00:42:26 1.20
+++ AttrNSImpl.java 2001/08/10 01:18:16 1.21
@@ -1,4 +1,4 @@
-/* $Id: AttrNSImpl.java,v 1.20 2001/07/24 00:42:26 lehors Exp $ */
+/* $Id: AttrNSImpl.java,v 1.21 2001/08/10 01:18:16 lehors Exp $ */
/*
* The Apache Software License, Version 1.1
*
@@ -94,7 +94,7 @@
/**
* DOM2: Constructor for Namespace implementation.
*/
- protected AttrNSImpl(DocumentImpl ownerDocument,
+ protected AttrNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI,
String qualifiedName) {
@@ -144,7 +144,7 @@
}
// for DeferredAttrImpl
- protected AttrNSImpl(DocumentImpl ownerDocument,
+ protected AttrNSImpl(CoreDocumentImpl ownerDocument,
String value) {
super(ownerDocument, value);
}
@@ -158,9 +158,9 @@
*
* The namespace URI of this node, or null if it is unspecified.<p>
*
- * This is not a computed value that is the result of a namespace lookup based on
- * an examination of the namespace declarations in scope. It is merely the
- * namespace URI given at creation time.<p>
+ * This is not a computed value that is the result of a namespace lookup
+ * based on an examination of the namespace declarations in scope. It is
+ * merely the namespace URI given at creation time.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null.
@@ -171,9 +171,9 @@
if (needsSyncData()) {
synchronizeData();
}
- // REVIST: This code could/should be done at a lower-level, such that the namespaceURI
- // is set properly upon creation. However, there still seems to be some DOM spec
- // interpretation grey-area.
+ // REVIST: This code could/should be done at a lower-level, such that
+ // the namespaceURI is set properly upon creation. However, there still
+ // seems to be some DOM spec interpretation grey-area.
return namespaceURI;
}
@@ -199,9 +199,9 @@
/**
* Introduced in DOM Level 2. <p>
*
- * Note that setting this attribute changes the nodeName attribute, which holds the
- * qualified name, as well as the tagName and name attributes of the Element
- * and Attr interfaces, when applicable.<p>
+ * Note that setting this attribute changes the nodeName attribute, which
+ * holds the qualified name, as well as the tagName and name attributes of
+ * the Element and Attr interfaces, when applicable.<p>
*
* @throws INVALID_CHARACTER_ERR Raised if the specified
* prefix contains an invalid character.
@@ -220,7 +220,7 @@
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
- if (!DocumentImpl.isXMLName(prefix)) {
+ if (!CoreDocumentImpl.isXMLName(prefix)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
1.14 +30 -114 xml-xerces/java/src/org/apache/xerces/dom/AttributeMap.java
Index: AttributeMap.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/AttributeMap.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- AttributeMap.java 2001/07/24 00:42:26 1.13
+++ AttributeMap.java 2001/08/10 01:18:16 1.14
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 2000 The Apache Software Foundation. All rights
+ * Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -61,11 +61,8 @@
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
-import org.w3c.dom.events.MutationEvent;
-import org.apache.xerces.dom.events.MutationEventImpl;
-
/**
* AttributeMap inherits from NamedNodeMapImpl and extends it to deal with the
* specifics of storing attributes. These are:
@@ -74,12 +71,13 @@
* <li>managing default attributes
* <li>firing mutation events
* </ul>
+ * <p>
+ * This class doesn't directly support mutation events, however, it notifies
+ * the document when mutations are performed so that the document class do so.
*
*/
public class AttributeMap extends NamedNodeMapImpl {
- final static boolean DEBUG = false;
-
//
// Constructors
//
@@ -122,7 +120,7 @@
"DOM006 Hierarchy request error");
}
- NodeImpl argn = (NodeImpl)arg;
+ AttrImpl argn = (AttrImpl)arg;
if (argn.isOwned()) {
throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
@@ -134,9 +132,9 @@
argn.isOwned(true);
int i = findNamePoint(arg.getNodeName(),0);
- NodeImpl previous = null;
+ AttrImpl previous = null;
if (i >= 0) {
- previous = (NodeImpl) nodes.elementAt(i);
+ previous = (AttrImpl) nodes.elementAt(i);
nodes.setElementAt(arg,i);
previous.ownerNode = ownerNode.ownerDocument();
previous.isOwned(false);
@@ -150,16 +148,8 @@
nodes.insertElementAt(arg, i);
}
- if (NodeImpl.MUTATIONEVENTS &&
- ownerNode.ownerDocument().mutationEvents) {
- // MUTATION POST-EVENTS:
- ownerNode.dispatchAggregateEvents(
- (AttrImpl)arg,
- previous==null ? null : previous.getNodeValue(),
- previous==null ?
- MutationEvent.ADDITION : MutationEvent.MODIFICATION
- );
- }
+ // notify document
+ ownerNode.ownerDocument().setAttrNode(argn, previous);
// If the new attribute is not normalized,
// the owning element is inherently not normalized.
@@ -195,7 +185,7 @@
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"DOM006 Hierarchy request error");
}
- NodeImpl argn = (NodeImpl)arg;
+ AttrImpl argn = (AttrImpl)arg;
if (argn.isOwned()) {
throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
"DOM009 Attribute already in use");
@@ -206,9 +196,9 @@
argn.isOwned(true);
int i = findNamePoint(argn.getNamespaceURI(), argn.getLocalName());
- NodeImpl previous = null;
+ AttrImpl previous = null;
if (i >= 0) {
- previous = (NodeImpl) nodes.elementAt(i);
+ previous = (AttrImpl) nodes.elementAt(i);
nodes.setElementAt(arg,i);
previous.ownerNode = ownerNode.ownerDocument();
previous.isOwned(false);
@@ -219,7 +209,7 @@
// nodeName so we know where to insert.
i = findNamePoint(arg.getNodeName(),0);
if (i >=0) {
- previous = (NodeImpl) nodes.elementAt(i);
+ previous = (AttrImpl) nodes.elementAt(i);
nodes.insertElementAt(arg,i);
} else {
i = -1 - i; // Insert point (may be end of list)
@@ -231,19 +221,8 @@
}
// changed(true);
- // Only NamedNodeMaps containing attributes (those which are
- // bound to an element) need report MutationEvents
- if (NodeImpl.MUTATIONEVENTS
- && ownerNode.ownerDocument().mutationEvents)
- {
- // MUTATION POST-EVENTS:
- ownerNode.dispatchAggregateEvents(
- (AttrImpl)arg,
- previous==null ? null : previous.getNodeValue(),
- previous==null ?
- MutationEvent.ADDITION : MutationEvent.MODIFICATION
- );
- }
+ // notify document
+ ownerNode.ownerDocument().setAttrNode(argn, previous);
// If the new attribute is not normalized,
// the owning element is inherently not normalized.
@@ -300,22 +279,9 @@
}
}
- LCount lc=null;
- String oldvalue="";
- AttrImpl enclosingAttribute=null;
- if (NodeImpl.MUTATIONEVENTS
- && ownerNode.ownerDocument().mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttribute=(AttrImpl)(nodes.elementAt(i));
- oldvalue=enclosingAttribute.getNodeValue();
- }
- } // End mutation preprocessing
+ AttrImpl n = (AttrImpl)nodes.elementAt(i);
+ CoreDocumentImpl ownerDocument = ownerNode.ownerDocument();
- NodeImpl n = (NodeImpl)nodes.elementAt(i);
// If there's a default, add it instead
if (hasDefaults()) {
NamedNodeMapImpl defaults =
@@ -323,7 +289,7 @@
Node d;
if (defaults != null && (d = defaults.getNamedItem(name)) != null
&& findNamePoint(name, i+1) < 0) {
-
+
NodeImpl clone = (NodeImpl)d.cloneNode(true);
clone.ownerNode = ownerNode;
clone.isOwned(true);
@@ -338,37 +304,18 @@
// changed(true);
- // remove owning element
- n.ownerNode = ownerNode.ownerDocument();
+ // remove reference to owner
+ n.ownerNode = ownerDocument;
n.isOwned(false);
// make sure it won't be mistaken with defaults in case it's reused
n.isSpecified(true);
- // We can't use the standard dispatchAggregate, since it assumes
- // that the Attr is still attached to an owner. This code is
- // similar but dispatches to the previous owner, "element".
- if(NodeImpl.MUTATIONEVENTS && ownerNode.ownerDocument().mutationEvents)
- {
- // If we have to send DOMAttrModified (determined earlier),
- // do so.
- if(lc.captures+lc.bubbles+lc.defaults>0) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_ATTR_MODIFIED,
- true, false,
- null, n.getNodeValue(),
- null, name, MutationEvent.REMOVAL);
- ownerNode.dispatchEvent(me);
- }
-
- // We can hand off to process DOMSubtreeModified, though.
- // Note that only the Element needs to be informed; the
- // Attr's subtree has not been changed by this operation.
- ownerNode.dispatchAggregateEvents(null,null,(short)0);
- }
+ // notify document
+ ownerDocument.removedAttrNode(n, ownerNode, name);
return n;
- } // removeNamedItem(String):Node
+ } // internalRemoveNamedItem(String,boolean):Node
/**
* Introduced in DOM Level 2. <p>
@@ -422,22 +369,9 @@
}
}
- LCount lc=null;
- String oldvalue="";
- AttrImpl enclosingAttribute=null;
- if (NodeImpl.MUTATIONEVENTS
- && ownerNode.ownerDocument().mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttribute=(AttrImpl)(nodes.elementAt(i));
- oldvalue=enclosingAttribute.getNodeValue();
- }
- } // End mutation preprocessing
+ AttrImpl n = (AttrImpl)nodes.elementAt(i);
+ CoreDocumentImpl ownerDocument = ownerNode.ownerDocument();
- NodeImpl n = (NodeImpl)nodes.elementAt(i);
// If there's a default, add it instead
String nodeName = n.getNodeName();
if (hasDefaults()) {
@@ -466,36 +400,18 @@
// changed(true);
- // Need to remove references to an Attr's owner before the
- // MutationEvents fire.
- n.ownerNode = ownerNode.ownerDocument();
+ // remove reference to owner
+ n.ownerNode = ownerDocument;
n.isOwned(false);
// make sure it won't be mistaken with defaults in case it's reused
n.isSpecified(true);
- // We can't use the standard dispatchAggregate, since it assumes
- // that the Attr is still attached to an owner. This code is
- // similar but dispatches to the previous owner, "element".
- if(NodeImpl.MUTATIONEVENTS && ownerNode.ownerDocument().mutationEvents)
- {
- // If we have to send DOMAttrModified (determined earlier),
- // do so.
- if(lc.captures+lc.bubbles+lc.defaults>0) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_ATTR_MODIFIED,
- true, false, null, n.getNodeValue(),
- null, name, MutationEvent.REMOVAL);
- ownerNode.dispatchEvent(me);
- }
+ // notify document
+ ownerDocument.removedAttrNode(n, ownerNode, name);
- // We can hand off to process DOMSubtreeModified, though.
- // Note that only the Element needs to be informed; the
- // Attr's subtree has not been changed by this operation.
- ownerNode.dispatchAggregateEvents(null,null,(short)0);
- }
return n;
- } // removeNamedItem(String):Node
+ } // internalRemoveNamedItemNS(String,String,boolean):Node
//
// Public methods
1.4 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/CDATASectionImpl.java
Index: CDATASectionImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/CDATASectionImpl.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- CDATASectionImpl.java 2001/07/24 00:42:26 1.3
+++ CDATASectionImpl.java 2001/08/10 01:18:16 1.4
@@ -101,7 +101,7 @@
//
/** Factory constructor for creating a CDATA section. */
- public CDATASectionImpl(DocumentImpl ownerDoc, String data) {
+ public CDATASectionImpl(CoreDocumentImpl ownerDoc, String data) {
super(ownerDoc, data);
}
1.14 +50 -83 xml-xerces/java/src/org/apache/xerces/dom/CharacterDataImpl.java
Index: CharacterDataImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/CharacterDataImpl.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- CharacterDataImpl.java 2001/07/24 00:42:26 1.13
+++ CharacterDataImpl.java 2001/08/10 01:18:16 1.14
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999 The Apache Software Foundation. All rights
+ * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -61,23 +61,18 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
-import org.w3c.dom.events.MutationEvent;
-import org.apache.xerces.dom.events.MutationEventImpl;
-
-
/**
* CharacterData is an abstract Node that can carry character data as its
* Value. It provides shared behavior for Text, CData, and
* possibly other node types. All offsets are 0-based.
* <p>
- * This implementation includes support for DOM Level 2 Mutation Events.
- * If the static boolean NodeImpl.MUTATIONEVENTS is not set true, that support
- * is disabled and can be optimized out to reduce code size.
- *
- * Since this ProcessingInstructionImpl inherits from this class to reuse the
+ * Since ProcessingInstructionImpl inherits from this class to reuse the
* setNodeValue method, this class isn't declared as implementing the interface
* CharacterData. This is done by relevant subclasses (TexImpl, CommentImpl).
+ * <p>
+ * This class doesn't directly support mutation events, however, it notifies
+ * the document when mutations are performed so that the document class do so.
*
* @version
* @since PR-DOM-Level-1-19980818.
@@ -109,7 +104,7 @@
//
/** Factory constructor. */
- protected CharacterDataImpl(DocumentImpl ownerDocument, String data) {
+ protected CharacterDataImpl(CoreDocumentImpl ownerDocument, String data) {
super(ownerDocument);
this.data = data;
}
@@ -140,20 +135,7 @@
* from the high-level functions in CharacterData, and another
* type if the client simply calls setNodeValue(value).
*/
- void setNodeValueInternal(String value) {
- /** flag to indicate whether setNodeValue was called by the
- * client or from the DOM.
- */
- setValueCalled(true);
- setNodeValue(value);
- setValueCalled(false);
- }
-
- /**
- * Sets the content, possibly firing related events,
- * and updating ranges (via notification to the document)
- */
- public void setNodeValue(String value) {
+ protected void setNodeValueInternal(String value) {
if (isReadOnly())
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
@@ -163,50 +145,33 @@
if (needsSyncData()) {
synchronizeData();
}
-
- // Cache old value for DOMCharacterDataModified.
+
+ // keep old value for document notification
String oldvalue = this.data;
- EnclosingAttr enclosingAttr=null;
- if(MUTATIONEVENTS)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // If we're within the scope of an Attr and DOMAttrModified
- // was requested, we need to preserve its previous value for
- // that event.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttr=getEnclosingAttr();
- }
- } // End mutation preprocessing
-
+
+ CoreDocumentImpl ownerDocument = ownerDocument();
+
+ // notify document
+ ownerDocument.modifyingCharacterData(this);
+
this.data = value;
- if (!setValueCalled()) {
- // notify document
- ownerDocument().replacedText(this);
- }
-
- if(MUTATIONEVENTS)
- {
- // MUTATION POST-EVENTS:
- LCount lc =
- LCount.lookup(MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- MutationEvent me= new MutationEventImpl();
- me.initMutationEvent(
- MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED,
- true,false,null,oldvalue,value,null,(short)0);
- dispatchEvent(me);
- }
-
- // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
- // if required. (Common to most kinds of mutation)
- dispatchAggregateEvents(enclosingAttr);
- } // End mutation postprocessing
+
+ // notify document
+ ownerDocument.modifiedCharacterData(this, oldvalue, value);
+ }
- } // setNodeValue(String)
+ /**
+ * Sets the content, possibly firing related events,
+ * and updating ranges (via notification to the document)
+ */
+ public void setNodeValue(String value) {
+ setNodeValueInternal(value);
+
+ // notify document
+ ownerDocument().replacedText(this);
+ }
+
//
// CharacterData methods
//
@@ -257,7 +222,6 @@
synchronizeData();
}
- // Handles mutation event generation, if any
setNodeValue(this.data + data);
} // appendData(String)
@@ -293,11 +257,13 @@
}
int tailLength = Math.max(data.length() - count - offset, 0);
try {
- // Handles mutation event generation, if any
- setNodeValueInternal(data.substring(0, offset) +
- (tailLength > 0
- ? data.substring(offset + count, offset + count + tailLength)
- : "") );
+ String value = data.substring(0, offset) +
+ (tailLength > 0
+ ? data.substring(offset + count, offset + count + tailLength)
+ : "");
+
+ setNodeValueInternal(value);
+
// notify document
ownerDocument().deletedText(this, offset, count);
}
@@ -330,10 +296,11 @@
synchronizeData();
}
try {
- // Handles mutation event generation, if any
- setNodeValueInternal(
- new StringBuffer(this.data).insert(offset, data).toString()
- );
+ String value =
+ new StringBuffer(this.data).insert(offset, data).toString();
+
+ setNodeValueInternal(value);
+
// notify document
ownerDocument().insertedText(this, offset, data.length());
}
@@ -371,14 +338,14 @@
public void replaceData(int offset, int count, String data)
throws DOMException {
- // The read-only check is done by deleteData()
- // ***** This could be more efficient w/r/t Mutation Events,
- // specifically by aggregating DOMAttrModified and
- // DOMSubtreeModified. But mutation events are
- // underspecified; I don't feel compelled
- // to deal with it right now.
- deleteData(offset, count);
- insertData(offset, data);
+ // The read-only check is done by deleteData()
+ // ***** This could be more efficient w/r/t Mutation Events,
+ // specifically by aggregating DOMAttrModified and
+ // DOMSubtreeModified. But mutation events are
+ // underspecified; I don't feel compelled
+ // to deal with it right now.
+ deleteData(offset, count);
+ insertData(offset, data);
} // replaceData(int,int,String)
1.5 +2 -2 xml-xerces/java/src/org/apache/xerces/dom/ChildNode.java
Index: ChildNode.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ChildNode.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- ChildNode.java 2001/07/24 00:42:26 1.4
+++ ChildNode.java 2001/08/10 01:18:16 1.5
@@ -95,9 +95,9 @@
* <p>
* Every Node knows what Document it belongs to.
*/
- protected ChildNode(DocumentImpl ownerDocument) {
+ protected ChildNode(CoreDocumentImpl ownerDocument) {
super(ownerDocument);
- } // <init>(DocumentImpl,String,short,boolean,String)
+ } // <init>(CoreDocumentImpl)
/** Constructor for serialization. */
public ChildNode() {}
1.5 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/CommentImpl.java
Index: CommentImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/CommentImpl.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- CommentImpl.java 2001/07/24 00:42:26 1.4
+++ CommentImpl.java 2001/08/10 01:18:16 1.5
@@ -83,7 +83,7 @@
//
/** Factory constructor. */
- public CommentImpl(DocumentImpl ownerDoc, String data) {
+ public CommentImpl(CoreDocumentImpl ownerDoc, String data) {
super(ownerDoc, data);
}
1.15 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/DOMImplementationImpl.java
Index: DOMImplementationImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DOMImplementationImpl.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- DOMImplementationImpl.java 2001/07/24 00:42:26 1.14
+++ DOMImplementationImpl.java 2001/08/10 01:18:16 1.15
@@ -155,7 +155,7 @@
String publicID,
String systemID)
{
- if (!DocumentImpl.isXMLName(qualifiedName)) {
+ if (!CoreDocumentImpl.isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
1.12 +3 -1 xml-xerces/java/src/org/apache/xerces/dom/DeferredAttrImpl.java
Index: DeferredAttrImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredAttrImpl.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- DeferredAttrImpl.java 2001/07/24 00:42:26 1.11
+++ DeferredAttrImpl.java 2001/08/10 01:18:16 1.12
@@ -174,7 +174,9 @@
* editing the tree -- this makes it a lot easier.
*/
protected void synchronizeChildren() {
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
} // synchronizeChildren()
} // class DeferredAttrImpl
1.15 +4 -2 xml-xerces/java/src/org/apache/xerces/dom/DeferredAttrNSImpl.java
Index: DeferredAttrNSImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredAttrNSImpl.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- DeferredAttrNSImpl.java 2001/05/10 18:11:10 1.14
+++ DeferredAttrNSImpl.java 2001/08/10 01:18:16 1.15
@@ -61,7 +61,7 @@
* DeferredAttrImpl.java at the same time.
*/
-/* $Id: DeferredAttrNSImpl.java,v 1.14 2001/05/10 18:11:10 lehors Exp $ */
+/* $Id: DeferredAttrNSImpl.java,v 1.15 2001/08/10 01:18:16 lehors Exp $ */
package org.apache.xerces.dom;
@@ -178,7 +178,9 @@
* editing the tree -- this makes it a lot easier.
*/
protected void synchronizeChildren() {
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
} // synchronizeChildren()
} // class DeferredAttrImpl
1.26 +105 -1 xml-xerces/java/src/org/apache/xerces/dom/DeferredDocumentImpl.java
Index: DeferredDocumentImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredDocumentImpl.java,v
retrieving revision 1.25
retrieving revision 1.26
diff -u -r1.25 -r1.26
--- DeferredDocumentImpl.java 2001/07/24 00:42:26 1.25
+++ DeferredDocumentImpl.java 2001/08/10 01:18:16 1.26
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999 The Apache Software Foundation. All rights
+ * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -1448,6 +1448,110 @@
mutationEvents = orig;
} // synchronizeChildren()
+
+ /**
+ * Synchronizes the node's children with the internal structure.
+ * Fluffing the children at once solves a lot of work to keep
+ * the two structures in sync. The problem gets worse when
+ * editing the tree -- this makes it a lot easier.
+ * This is not directly used in this class but this method is
+ * here so that it can be shared by all deferred subclasses of AttrImpl.
+ */
+ protected final void synchronizeChildren(AttrImpl a, int nodeIndex) {
+
+ // we don't want to generate any event for this so turn them off
+ boolean orig = getMutationEvents();
+ setMutationEvents(false);
+
+ // no need to sync in the future
+ a.needsSyncChildren(false);
+
+ // create children and link them as siblings or simply store the value
+ // as a String if all we have is one piece of text
+ int last = getLastChild(nodeIndex);
+ int prev = getPrevSibling(last);
+ if (prev == -1) {
+ a.value = getNodeValueString(last);
+ a.hasStringValue(true);
+ }
+ else {
+ ChildNode firstNode = null;
+ ChildNode lastNode = null;
+ for (int index = last; index != -1;
+ index = getPrevSibling(index)) {
+
+ ChildNode node = (ChildNode) getNodeObject(index);
+ if (lastNode == null) {
+ lastNode = node;
+ }
+ else {
+ firstNode.previousSibling = node;
+ }
+ node.ownerNode = this;
+ node.isOwned(true);
+ node.nextSibling = firstNode;
+ firstNode = node;
+ }
+ if (lastNode != null) {
+ a.value = firstNode; // firstChild = firstNode
+ firstNode.isFirstChild(true);
+ a.lastChild(lastNode);
+ }
+ a.hasStringValue(false);
+ }
+
+ // set mutation events flag back to its original value
+ setMutationEvents(orig);
+
+ } // synchronizeChildren(AttrImpl,int):void
+
+
+ /**
+ * Synchronizes the node's children with the internal structure.
+ * Fluffing the children at once solves a lot of work to keep
+ * the two structures in sync. The problem gets worse when
+ * editing the tree -- this makes it a lot easier.
+ * This is not directly used in this class but this method is
+ * here so that it can be shared by all deferred subclasses of ParentNode.
+ */
+ protected final void synchronizeChildren(ParentNode p, int nodeIndex) {
+
+ // we don't want to generate any event for this so turn them off
+ boolean orig = getMutationEvents();
+ setMutationEvents(false);
+
+ // no need to sync in the future
+ p.needsSyncChildren(false);
+
+ // create children and link them as siblings
+ ChildNode firstNode = null;
+ ChildNode lastNode = null;
+ for (int index = getLastChild(nodeIndex);
+ index != -1;
+ index = getPrevSibling(index)) {
+
+ ChildNode node = (ChildNode) getNodeObject(index);
+ if (lastNode == null) {
+ lastNode = node;
+ }
+ else {
+ firstNode.previousSibling = node;
+ }
+ node.ownerNode = this;
+ node.isOwned(true);
+ node.nextSibling = firstNode;
+ firstNode = node;
+ }
+ if (lastNode != null) {
+ p.firstChild = firstNode;
+ firstNode.isFirstChild(true);
+ p.lastChild(lastNode);
+ }
+
+ // set mutation events flag back to its original value
+ setMutationEvents(orig);
+
+ } // synchronizeChildren(ParentNode,int):void
// utility methods
1.12 +3 -3 xml-xerces/java/src/org/apache/xerces/dom/DeferredDocumentTypeImpl.java
Index: DeferredDocumentTypeImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredDocumentTypeImpl.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- DeferredDocumentTypeImpl.java 2001/07/24 00:42:26 1.11
+++ DeferredDocumentTypeImpl.java 2001/08/10 01:18:16 1.12
@@ -153,8 +153,8 @@
protected void synchronizeChildren() {
// we don't want to generate any event for this so turn them off
- boolean orig = ownerDocument().mutationEvents;
- ownerDocument().mutationEvents = false;
+ boolean orig = ownerDocument().getMutationEvents();
+ ownerDocument().setMutationEvents(false);
// no need to synchronize again
needsSyncChildren(false);
@@ -212,7 +212,7 @@
}
// set mutation events flag back to its original value
- ownerDocument().mutationEvents = orig;
+ ownerDocument().setMutationEvents(orig);
// set entities and notations read_only per DOM spec
setReadOnly(true, false);
1.8 +3 -3 xml-xerces/java/src/org/apache/xerces/dom/DeferredElementDefinitionImpl.java
Index: DeferredElementDefinitionImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredElementDefinitionImpl.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- DeferredElementDefinitionImpl.java 2001/07/24 00:42:26 1.7
+++ DeferredElementDefinitionImpl.java 2001/08/10 01:18:16 1.8
@@ -133,8 +133,8 @@
protected void synchronizeChildren() {
// we don't want to generate any event for this so turn them off
- boolean orig = ownerDocument.mutationEvents;
- ownerDocument.mutationEvents = false;
+ boolean orig = ownerDocument.getMutationEvents();
+ ownerDocument.setMutationEvents(false);
// attributes are now synced
needsSyncChildren(false);
@@ -154,7 +154,7 @@
}
// set mutation events flag back to its original value
- ownerDocument.mutationEvents = orig;
+ ownerDocument.setMutationEvents(orig);
} // synchronizeChildren()
1.11 +3 -1 xml-xerces/java/src/org/apache/xerces/dom/DeferredElementImpl.java
Index: DeferredElementImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredElementImpl.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- DeferredElementImpl.java 2001/07/24 00:42:26 1.10
+++ DeferredElementImpl.java 2001/08/10 01:18:16 1.11
@@ -173,7 +173,9 @@
} // synchronizeData()
protected final void synchronizeChildren() {
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
} // synchronizeChildren()
} // class DeferredElementImpl
1.10 +4 -2 xml-xerces/java/src/org/apache/xerces/dom/DeferredElementNSImpl.java
Index: DeferredElementNSImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredElementNSImpl.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- DeferredElementNSImpl.java 2001/05/10 18:11:08 1.9
+++ DeferredElementNSImpl.java 2001/08/10 01:18:16 1.10
@@ -56,7 +56,7 @@
*/
-/* $Id: DeferredElementNSImpl.java,v 1.9 2001/05/10 18:11:08 lehors Exp $ */
+/* $Id: DeferredElementNSImpl.java,v 1.10 2001/08/10 01:18:16 lehors Exp $ */
/*
* WARNING: because java doesn't support multi-inheritance some code is
@@ -180,7 +180,9 @@
* editing the tree -- this makes it a lot easier.
*/
protected final void synchronizeChildren() {
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
} // synchronizeChildren()
} // class DeferredElementImpl
1.10 +3 -1 xml-xerces/java/src/org/apache/xerces/dom/DeferredEntityImpl.java
Index: DeferredEntityImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredEntityImpl.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- DeferredEntityImpl.java 2001/07/24 00:42:26 1.9
+++ DeferredEntityImpl.java 2001/08/10 01:18:16 1.10
@@ -176,7 +176,9 @@
needsSyncChildren(false);
isReadOnly(false);
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
setReadOnly(true, true);
} // synchronizeChildren()
1.11 +6 -4 xml-xerces/java/src/org/apache/xerces/dom/DeferredEntityReferenceImpl.java
Index: DeferredEntityReferenceImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DeferredEntityReferenceImpl.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- DeferredEntityReferenceImpl.java 2001/07/24 00:42:26 1.10
+++ DeferredEntityReferenceImpl.java 2001/08/10 01:18:16 1.11
@@ -188,8 +188,8 @@
if (doctype != null) {
// we don't want to generate any event for this so turn them off
- boolean orig = ownerDocument.mutationEvents;
- ownerDocument.mutationEvents = false;
+ boolean orig = ownerDocument.getMutationEvents();
+ ownerDocument.setMutationEvents(false);
NamedNodeMap entities = doctype.getEntities();
if (entities != null) {
@@ -214,13 +214,15 @@
}
}
// set mutation events flag back to its original value
- ownerDocument.mutationEvents = orig;
+ ownerDocument.setMutationEvents(orig);
}
// if not found, create entity at this reference
if (!found) {
isReadOnly(false);
- synchronizeChildren(fNodeIndex);
+ DeferredDocumentImpl ownerDocument =
+ (DeferredDocumentImpl) ownerDocument();
+ ownerDocument.synchronizeChildren(this, fNodeIndex);
setReadOnly(true, true);
}
1.8 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/DocumentFragmentImpl.java
Index: DocumentFragmentImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DocumentFragmentImpl.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- DocumentFragmentImpl.java 2001/07/24 00:42:26 1.7
+++ DocumentFragmentImpl.java 2001/08/10 01:18:16 1.8
@@ -116,7 +116,7 @@
//
/** Factory constructor. */
- public DocumentFragmentImpl(DocumentImpl ownerDoc) {
+ public DocumentFragmentImpl(CoreDocumentImpl ownerDoc) {
super(ownerDoc);
}
1.59 +809 -1309 xml-xerces/java/src/org/apache/xerces/dom/DocumentImpl.java
Index: DocumentImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DocumentImpl.java,v
retrieving revision 1.58
retrieving revision 1.59
diff -u -r1.58 -r1.59
--- DocumentImpl.java 2001/07/24 00:42:26 1.58
+++ DocumentImpl.java 2001/08/10 01:18:16 1.59
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999 The Apache Software Foundation. All rights
+ * Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -62,16 +62,9 @@
import java.util.Vector;
import org.w3c.dom.Attr;
-import org.w3c.dom.CDATASection;
-import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
-import org.w3c.dom.Document;
-import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
-import org.w3c.dom.Element;
-import org.w3c.dom.Entity;
-import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -81,7 +74,10 @@
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
+import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
+import org.w3c.dom.events.EventTarget;
+import org.w3c.dom.events.MutationEvent;
import org.w3c.dom.ranges.DocumentRange;
import org.w3c.dom.ranges.Range;
import org.w3c.dom.traversal.DocumentTraversal;
@@ -125,8 +121,8 @@
* @since PR-DOM-Level-1-19980818.
*/
public class DocumentImpl
- extends ParentNode
- implements Document, DocumentTraversal, DocumentEvent, DocumentRange {
+ extends CoreDocumentImpl
+ implements DocumentTraversal, DocumentEvent, DocumentRange {
//
// Constants
@@ -139,28 +135,6 @@
// Data
//
- // document information
-
- /** Document type. */
- protected DocumentTypeImpl docType;
-
- /** Document element. */
- protected ElementImpl docElement;
-
-
- /**Experimental DOM Level 3 feature: Document encoding */
- protected String encoding;
-
- /**Experimental DOM Level 3 feature: Document version */
- protected String version;
-
- /**Experimental DOM Level 3 feature: Document standalone */
- protected boolean standalone;
-
-
- /** Identifiers. */
- protected Hashtable identifiers;
-
/** Iterators */
// REVISIT: Should this be transient? -Ac
protected Vector iterators;
@@ -169,97 +143,16 @@
// REVISIT: Should this be transient? -Ac
protected Vector ranges;
- /** Table for quick check of child insertion. */
- protected static int[] kidOK;
-
/** Table for user data attached to this document nodes. */
protected Hashtable userData;
/** Table for event listeners registered to this document nodes. */
protected Hashtable eventListeners;
- /**
- * Number of alterations made to this document since its creation.
- * Serves as a "dirty bit" so that live objects such as NodeList can
- * recognize when an alteration has been made and discard its cached
- * state information.
- * <p>
- * Any method that alters the tree structure MUST cause or be
- * accompanied by a call to changed(), to inform it that any outstanding
- * NodeLists may have to be updated.
- * <p>
- * (Required because NodeList is simultaneously "live" and integer-
- * indexed -- a bad decision in the DOM's design.)
- * <p>
- * Note that changes which do not affect the tree's structure -- changing
- * the node's name, for example -- do _not_ have to call changed().
- * <p>
- * Alternative implementation would be to use a cryptographic
- * Digest value rather than a count. This would have the advantage that
- * "harmless" changes (those producing equal() trees) would not force
- * NodeList to resynchronize. Disadvantage is that it's slightly more prone
- * to "false negatives", though that's the difference between "wildly
- * unlikely" and "absurdly unlikely". IF we start maintaining digests,
- * we should consider taking advantage of them.
- *
- * Note: This used to be done a node basis, so that we knew what
- * subtree changed. But since only DeepNodeList really use this today,
- * the gain appears to be really small compared to the cost of having
- * an int on every (parent) node plus having to walk up the tree all the
- * way to the root to mark the branch as changed everytime a node is
- * changed.
- * So we now have a single counter global to the document. It means that
- * some objects may flush their cache more often than necessary, but this
- * makes nodes smaller and only the document needs to be marked as changed.
- */
- protected int changes = 0;
-
- // experimental
-
- /** Allow grammar access. */
- protected boolean allowGrammarAccess;
-
- /** Bypass error checking. */
- protected boolean errorChecking = true;
-
/** Bypass mutation events firing. */
protected boolean mutationEvents = false;
//
- // Static initialization
- //
-
- static {
-
- kidOK = new int[13];
-
- kidOK[DOCUMENT_NODE] =
- 1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
- 1 << COMMENT_NODE | 1 << DOCUMENT_TYPE_NODE;
-
- kidOK[DOCUMENT_FRAGMENT_NODE] =
- kidOK[ENTITY_NODE] =
- kidOK[ENTITY_REFERENCE_NODE] =
- kidOK[ELEMENT_NODE] =
- 1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
- 1 << COMMENT_NODE | 1 << TEXT_NODE |
- 1 << CDATA_SECTION_NODE | 1 << ENTITY_REFERENCE_NODE ;
-
-
- kidOK[ATTRIBUTE_NODE] =
- 1 << TEXT_NODE | 1 << ENTITY_REFERENCE_NODE;
-
- kidOK[DOCUMENT_TYPE_NODE] =
- kidOK[PROCESSING_INSTRUCTION_NODE] =
- kidOK[COMMENT_NODE] =
- kidOK[TEXT_NODE] =
- kidOK[CDATA_SECTION_NODE] =
- kidOK[NOTATION_NODE] =
- 0;
-
- } // static
-
- //
// Constructors
//
@@ -268,18 +161,12 @@
* since it has to operate in terms of a particular implementation.
*/
public DocumentImpl() {
- this(false);
- // make sure the XMLCharacterProperties class is initilialized
- XMLCharacterProperties.initCharFlags();
+ super();
}
/** Constructor. */
public DocumentImpl(boolean grammarAccess) {
- super(null);
- ownerDocument = this;
- allowGrammarAccess = grammarAccess;
- // make sure the XMLCharacterProperties class is initilialized
- XMLCharacterProperties.initCharFlags();
+ super(grammarAccess);
}
/**
@@ -288,1109 +175,76 @@
*/
public DocumentImpl(DocumentType doctype)
{
- this(doctype, false);
- // make sure the XMLCharacterProperties class is initilialized
- XMLCharacterProperties.initCharFlags();
+ super(doctype);
}
/** For DOM2 support. */
- public DocumentImpl(DocumentType doctype, boolean grammarAccess) {
- this(grammarAccess);
- if (doctype != null) {
- DocumentTypeImpl doctypeImpl;
- try {
- doctypeImpl = (DocumentTypeImpl) doctype;
- } catch (ClassCastException e) {
- throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
- "DOM005 Wrong document");
- }
- doctypeImpl.ownerDocument = this;
- appendChild(doctype);
- }
- // make sure the XMLCharacterProperties class is initilialized
- XMLCharacterProperties.initCharFlags();
- }
-
- //
- // Node methods
- //
-
- // even though ownerDocument refers to this in this implementation
- // the DOM Level 2 spec says it must be null, so make it appear so
- final public Document getOwnerDocument() {
- return null;
- }
-
- /** Returns the node type. */
- public short getNodeType() {
- return Node.DOCUMENT_NODE;
- }
-
- /** Returns the node name. */
- public String getNodeName() {
- return "#document";
- }
-
- /**
- * Deep-clone a document, including fixing ownerDoc for the cloned
- * children. Note that this requires bypassing the WRONG_DOCUMENT_ERR
- * protection. I've chosen to implement it by calling importNode
- * which is DOM Level 2.
- *
- * @return org.w3c.dom.Node
- * @param deep boolean, iff true replicate children
- */
- public Node cloneNode(boolean deep) {
-
- // clone the node itself
- DocumentImpl newdoc = new DocumentImpl();
-
- // then the children by importing them
-
- if (needsSyncChildren()) {
- synchronizeChildren();
- }
-
- if (deep) {
- Hashtable reversedIdentifiers = null;
-
- if (identifiers != null) {
- // Build a reverse mapping from element to identifier.
- reversedIdentifiers = new Hashtable();
- Enumeration elementIds = identifiers.keys();
- while (elementIds.hasMoreElements()) {
- Object elementId = elementIds.nextElement();
- reversedIdentifiers.put(identifiers.get(elementId), elementId);
- }
- }
-
- // Copy children into new document.
- for (ChildNode kid = firstChild; kid != null; kid = kid.nextSibling) {
- newdoc.appendChild(newdoc.importNode(kid, true, reversedIdentifiers));
- }
- }
-
- // experimental
- newdoc.allowGrammarAccess = allowGrammarAccess;
- newdoc.errorChecking = errorChecking;
- newdoc.mutationEvents = mutationEvents;
-
- // return new document
- return newdoc;
-
- } // cloneNode(boolean):Node
-
- /**
- * Since a Document may contain at most one top-level Element child,
- * and at most one DocumentType declaraction, we need to subclass our
- * add-children methods to implement this constraint.
- * Since appendChild() is implemented as insertBefore(,null),
- * altering the latter fixes both.
- * <p>
- * While I'm doing so, I've taken advantage of the opportunity to
- * cache documentElement and docType so we don't have to
- * search for them.
- *
- * REVISIT: According to the spec it is not allowed to alter neither the
- * document element nor the document type in any way
- */
- public Node insertBefore(Node newChild, Node refChild)
- throws DOMException {
-
- // Only one such child permitted
- int type = newChild.getNodeType();
- if (errorChecking) {
- if((type == Node.ELEMENT_NODE && docElement != null) ||
- (type == Node.DOCUMENT_TYPE_NODE && docType != null)) {
- throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
- "DOM006 Hierarchy request error");
- }
- }
-
- super.insertBefore(newChild,refChild);
-
- // If insert succeeded, cache the kid appropriately
- if (type == Node.ELEMENT_NODE) {
- docElement = (ElementImpl)newChild;
- }
- else if (type == Node.DOCUMENT_TYPE_NODE) {
- docType=(DocumentTypeImpl)newChild;
- }
-
- return newChild;
-
- } // insertBefore(Node,Node):Node
-
- /**
- * Since insertBefore caches the docElement (and, currently, docType),
- * removeChild has to know how to undo the cache
- *
- * REVISIT: According to the spec it is not allowed to alter neither the
- * document element nor the document type in any way
- */
- public Node removeChild(Node oldChild)
- throws DOMException {
- super.removeChild(oldChild);
-
- // If remove succeeded, un-cache the kid appropriately
- int type = oldChild.getNodeType();
- if(type == Node.ELEMENT_NODE) {
- docElement = null;
- }
- else if (type == Node.DOCUMENT_TYPE_NODE) {
- docType=null;
- }
-
- return oldChild;
-
- } // removeChild(Node):Node
-
- /**
- * Since we cache the docElement (and, currently, docType),
- * replaceChild has to update the cache
- *
- * REVISIT: According to the spec it is not allowed to alter neither the
- * document element nor the document type in any way
- */
- public Node replaceChild(Node newChild, Node oldChild)
- throws DOMException {
-
- super.replaceChild(newChild, oldChild);
-
- int type = oldChild.getNodeType();
- if(type == Node.ELEMENT_NODE) {
- docElement = (ElementImpl)newChild;
- }
- else if (type == Node.DOCUMENT_TYPE_NODE) {
- docType = (DocumentTypeImpl)newChild;
- }
- return oldChild;
- } // replaceChild(Node,Node):Node
-
- //
- // Document methods
- //
-
- // factory methods
-
- /**
- * Factory method; creates an Attribute having this Document as its
- * OwnerDoc.
- *
- * @param name The name of the attribute. Note that the attribute's value
- * is _not_ established at the factory; remember to set it!
- *
- * @throws DOMException(INVALID_NAME_ERR) if the attribute name is not
- * acceptable.
- */
- public Attr createAttribute(String name)
- throws DOMException {
-
- if(errorChecking && !isXMLName(name)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
-
- return new AttrImpl(this, name);
-
- } // createAttribute(String):Attr
-
- /**
- * Factory method; creates a CDATASection having this Document as
- * its OwnerDoc.
- *
- * @param data The initial contents of the CDATA
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
- * not yet implemented.)
- */
- public CDATASection createCDATASection(String data)
- throws DOMException {
- return new CDATASectionImpl(this, data);
- }
-
- /**
- * Factory method; creates a Comment having this Document as its
- * OwnerDoc.
- *
- * @param data The initial contents of the Comment. */
- public Comment createComment(String data) {
- return new CommentImpl(this, data);
- }
-
- /**
- * Factory method; creates a DocumentFragment having this Document
- * as its OwnerDoc.
- */
- public DocumentFragment createDocumentFragment() {
- return new DocumentFragmentImpl(this);
- }
-
- /**
- * Factory method; creates an Element having this Document
- * as its OwnerDoc.
- *
- * @param tagName The name of the element type to instantiate. For
- * XML, this is case-sensitive. For HTML, the tagName parameter may
- * be provided in any case, but it must be mapped to the canonical
- * uppercase form by the DOM implementation.
- *
- * @throws DOMException(INVALID_NAME_ERR) if the tag name is not
- * acceptable.
- */
- public Element createElement(String tagName)
- throws DOMException {
-
- if (errorChecking && !isXMLName(tagName)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new ElementImpl(this, tagName);
-
- } // createElement(String):Element
-
- /**
- * Factory method; creates an EntityReference having this Document
- * as its OwnerDoc.
- *
- * @param name The name of the Entity we wish to refer to
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
- * nonstandard entities are not permitted. (HTML not yet
- * implemented.)
- */
- public EntityReference createEntityReference(String name)
- throws DOMException {
-
- if (errorChecking && !isXMLName(name)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new EntityReferenceImpl(this, name);
-
- } // createEntityReference(String):EntityReference
-
- /**
- * Factory method; creates a ProcessingInstruction having this Document
- * as its OwnerDoc.
- *
- * @param target The target "processor channel"
- * @param data Parameter string to be passed to the target.
- *
- * @throws DOMException(INVALID_NAME_ERR) if the target name is not
- * acceptable.
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
- * not yet implemented.)
- */
- public ProcessingInstruction createProcessingInstruction(String target, String data)
- throws DOMException {
-
- if(errorChecking && !isXMLName(target)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new ProcessingInstructionImpl(this, target, data);
-
- } // createProcessingInstruction(String,String):ProcessingInstruction
-
- /**
- * Factory method; creates a Text node having this Document as its
- * OwnerDoc.
- *
- * @param data The initial contents of the Text.
- */
- public Text createTextNode(String data) {
- return new TextImpl(this, data);
- }
-
- // other document methods
-
- /**
- * For XML, this provides access to the Document Type Definition.
- * For HTML documents, and XML documents which don't specify a DTD,
- * it will be null.
- */
- public DocumentType getDoctype() {
- if (needsSyncChildren()) {
- synchronizeChildren();
- }
- return docType;
- }
-
-
- /**
- * DOM Level 3 WD - Experimental.
- * The encoding of this document (part of XML Declaration)
- */
- public String getEncoding() {
- return encoding;
- }
-
- /**
- * DOM Level 3 WD - Experimental.
- * The version of this document (part of XML Declaration)
- */
- public String getVersion() {
- return version;
- }
-
- /**
- * DOM Level 3 WD - Experimental.
- * standalone that specifies whether this document is standalone (part of XML Declaration)
- */
- public boolean getStandalone() {
- return standalone;
- }
-
-
- /**
- * Convenience method, allowing direct access to the child node
- * which is considered the root of the actual document content. For
- * HTML, where it is legal to have more than one Element at the top
- * level of the document, we pick the one with the tagName
- * "HTML". For XML there should be only one top-level
- *
- * (HTML not yet supported.)
- */
- public Element getDocumentElement() {
- if (needsSyncChildren()) {
- synchronizeChildren();
- }
- return docElement;
- }
-
- /**
- * Return a <em>live</em> collection of all descendent Elements (not just
- * immediate children) having the specified tag name.
- *
- * @param tagname The type of Element we want to gather. "*" will be
- * taken as a wildcard, meaning "all elements in the document."
- *
- * @see DeepNodeListImpl
- */
- public NodeList getElementsByTagName(String tagname) {
- return new DeepNodeListImpl(this,tagname);
- }
-
- /**
- * Retrieve information describing the abilities of this particular
- * DOM implementation. Intended to support applications that may be
- * using DOMs retrieved from several different sources, potentially
- * with different underlying representations.
- */
- public DOMImplementation getImplementation() {
- // Currently implemented as a singleton, since it's hardcoded
- // information anyway.
- return DOMImplementationImpl.getDOMImplementation();
- }
-
- //
- // Public methods
- //
-
- // properties
-
- /**
- * Sets whether the DOM implementation performs error checking
- * upon operations. Turning off error checking only affects
- * the following DOM checks:
- * <ul>
- * <li>Checking strings to make sure that all characters are
- * legal XML characters
- * <li>Hierarchy checking such as allowed children, checks for
- * cycles, etc.
- * </ul>
- * <p>
- * Turning off error checking does <em>not</em> turn off the
- * following checks:
- * <ul>
- * <li>Read only checks
- * <li>Checks related to DOM events
- * </ul>
- */
-
- public void setErrorChecking(boolean check) {
- errorChecking = check;
- }
-
- /*
- * DOM Level 3 WD - Experimental.
- */
- public void setStrictErrorChecking(boolean check) {
- errorChecking = check;
- }
-
-
- /**
- * DOM Level 3 WD - Experimental.
- * An attribute specifying, as part of the XML declaration,
- * the encoding of this document. This is null when unspecified.
- */
- public void setEncoding(String value) {
- encoding = value;
- }
-
- /**
- * DOM Level 3 WD - Experimental.
- * version - An attribute specifying, as part of the XML declaration,
- * the version number of this document. This is null when unspecified
- */
- public void setVersion(String value) {
- version = value;
- }
-
- /**
- * DOM Level 3 WD - Experimental.
- * standalone - An attribute specifying, as part of the XML declaration,
- * whether this document is standalone
- */
- public void setStandalone(boolean value) {
- standalone = value;
- }
-
-
- /**
- * Returns true if the DOM implementation performs error checking.
- */
- public boolean getErrorChecking() {
- return errorChecking;
- }
-
- /*
- * DOM Level 3 WD - Experimental.
- */
- public boolean getStrictErrorChecking() {
- return errorChecking;
- }
-
-
- /**
- * Sets whether the DOM implementation generates mutation events
- * upon operations.
- */
- public void setMutationEvents(boolean set) {
- mutationEvents = set;
- }
-
- /**
- * Returns true if the DOM implementation generates mutation events.
- */
- public boolean getMutationEvents() {
- return mutationEvents;
- }
-
- // non-DOM factory methods
-
- /**
- * NON-DOM
- * Factory method; creates a DocumentType having this Document
- * as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
- * DTD information unspecified.)
- *
- * @param name The name of the Entity we wish to provide a value for.
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
- * DTDs are not permitted. (HTML not yet implemented.)
- */
- public DocumentType createDocumentType(String qualifiedName,
- String publicID,
- String systemID)
- throws DOMException {
-
- if (errorChecking && !isXMLName(qualifiedName)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new DocumentTypeImpl(this, qualifiedName, publicID, systemID);
-
- } // createDocumentType(String):DocumentType
-
- /**
- * NON-DOM
- * Factory method; creates an Entity having this Document
- * as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
- * DTD information unspecified.)
- *
- * @param name The name of the Entity we wish to provide a value for.
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
- * nonstandard entities are not permitted. (HTML not yet
- * implemented.)
- */
- public Entity createEntity(String name)
- throws DOMException {
-
- if (errorChecking && !isXMLName(name)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new EntityImpl(this, name);
-
- } // createEntity(String):Entity
-
- /**
- * NON-DOM
- * Factory method; creates a Notation having this Document
- * as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
- * DTD information unspecified.)
- *
- * @param name The name of the Notation we wish to describe
- *
- * @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
- * notations are not permitted. (HTML not yet
- * implemented.)
- */
- public Notation createNotation(String name)
- throws DOMException {
-
- if (errorChecking && !isXMLName(name)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new NotationImpl(this, name);
-
- } // createNotation(String):Notation
-
- /**
- * NON-DOM Factory method: creates an element definition. Element
- * definitions hold default attribute values.
- */
- public ElementDefinitionImpl createElementDefinition(String name)
- throws DOMException {
-
- if (errorChecking && !isXMLName(name)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new ElementDefinitionImpl(this, name);
-
- } // createElementDefinition(String):ElementDefinitionImpl
-
- // other non-DOM methods
-
- /**
- * Copies a node from another document to this document. The new nodes are
- * created using this document's factory methods and are populated with the
- * data from the source's accessor methods defined by the DOM interfaces.
- * Its behavior is otherwise similar to that of cloneNode.
- * <p>
- * According to the DOM specifications, document nodes cannot be imported
- * and a NOT_SUPPORTED_ERR exception is thrown if attempted.
- */
- public Node importNode(Node source, boolean deep)
- throws DOMException {
- return importNode(source, deep, null);
- } // importNode(Node,boolean):Node
-
- /**
- * Overloaded implementation of DOM's importNode method. This method
- * provides the core functionality for the public importNode and cloneNode
- * methods.
- *
- * The reversedIdentifiers parameter is provided for cloneNode to
- * preserve the document's identifiers. The Hashtable has Elements as the
- * keys and their identifiers as the values. When an element is being
- * imported, a check is done for an associated identifier. If one exists,
- * the identifier is registered with the new, imported element. If
- * reversedIdentifiers is null, the parameter is not applied.
- */
- private Node importNode(Node source, boolean deep, Hashtable reversedIdentifiers)
- throws DOMException {
- Node newnode=null;
-
- // Sigh. This doesn't work; too many nodes have private data that
- // would have to be manually tweaked. May be able to add local
- // shortcuts to each nodetype. Consider ?????
- // if(source instanceof NodeImpl &&
- // !(source instanceof DocumentImpl))
- // {
- // // Can't clone DocumentImpl since it invokes us...
- // newnode=(NodeImpl)source.cloneNode(false);
- // newnode.ownerDocument=this;
- // }
- // else
-
- DOMImplementation domImplementation =
- source.getOwnerDocument().getImplementation(); // get source implementation
- boolean domLevel20 =
- domImplementation.hasFeature("XML", "2.0" ); //DOM Level 2.0 implementation
-
-
- int type = source.getNodeType();
-
- switch (type) {
- case ELEMENT_NODE: {
- Element newElement;
-
- // Create element according to namespace support/qualification.
- if(domLevel20 == false || source.getLocalName() == null)
- newElement = createElement(source.getNodeName());
- else
- newElement = createElementNS(source.getNamespaceURI(), source.getNodeName());
-
- // Copy element's attributes, if any.
- NamedNodeMap sourceAttrs = source.getAttributes();
- if (sourceAttrs != null) {
- int length = sourceAttrs.getLength();
- for (int index = 0; index < length; index++) {
- Attr attr = (Attr)sourceAttrs.item(index);
-
- // Copy the attribute only if it is not a default.
- if (attr.getSpecified()) {
- Attr newAttr = (Attr)importNode(attr, true, reversedIdentifiers);
-
- // Attach attribute according to namespace support/qualification.
- if(domLevel20 == false || attr.getLocalName() == null)
- newElement.setAttributeNode(newAttr);
- else
- newElement.setAttributeNodeNS(newAttr);
- }
- }
- }
-
- // Register element identifier.
- if (reversedIdentifiers != null) {
- // Does element have an associated identifier?
- Object elementId = reversedIdentifiers.get(source);
- if (elementId != null) {
- if (identifiers == null)
- identifiers = new Hashtable();
-
- identifiers.put(elementId, newElement);
- }
- }
-
- newnode = newElement;
- break;
- }
-
- case ATTRIBUTE_NODE: {
-
- if( domLevel20 == true ){
- if (source.getLocalName() == null) {
- newnode = createAttribute(source.getNodeName());
- } else {
- newnode = createAttributeNS(source.getNamespaceURI(),
- source.getNodeName());
- }
- }
- else {
- newnode = createAttribute(source.getNodeName());
- }
- // if source is an AttrImpl from this very same implementation
- // avoid creating the child nodes if possible
- if (source instanceof AttrImpl) {
- AttrImpl attr = (AttrImpl) source;
- if (attr.hasStringValue()) {
- AttrImpl newattr = (AttrImpl) newnode;
- newattr.setValue(attr.getValue());
- deep = false;
- }
- else {
- deep = true;
- }
- }
- else {
- // According to the DOM spec the kids carry the value.
- // However, there are non compliant implementations out
- // there that fail to do so. To avoid ending up with no
- // value at all, in this case we simply copy the text value
- // directly.
- if (source.getFirstChild() == null) {
- newnode.setNodeValue(source.getNodeValue());
- deep = false;
- } else {
- deep = true;
- }
- }
- break;
- }
-
- case TEXT_NODE: {
- newnode = createTextNode(source.getNodeValue());
- break;
- }
-
- case CDATA_SECTION_NODE: {
- newnode = createCDATASection(source.getNodeValue());
- break;
- }
-
- case ENTITY_REFERENCE_NODE: {
- newnode = createEntityReference(source.getNodeName());
- // allow deep import temporarily
- ((EntityReferenceImpl)newnode).isReadOnly(false);
- break;
- }
-
- case ENTITY_NODE: {
- Entity srcentity = (Entity)source;
- EntityImpl newentity =
- (EntityImpl)createEntity(source.getNodeName());
- newentity.setPublicId(srcentity.getPublicId());
- newentity.setSystemId(srcentity.getSystemId());
- newentity.setNotationName(srcentity.getNotationName());
- // Kids carry additional value
- newentity.isReadOnly(false); // allow deep import temporarily
- newnode = newentity;
- break;
- }
-
- case PROCESSING_INSTRUCTION_NODE: {
- newnode = createProcessingInstruction(source.getNodeName(),
- source.getNodeValue());
- break;
- }
-
- case COMMENT_NODE: {
- newnode = createComment(source.getNodeValue());
- break;
- }
-
- // REVISIT: The DOM specifications say that DocumentType nodes cannot be
- // imported. Is this OK?
- case DOCUMENT_TYPE_NODE: {
- DocumentType srcdoctype = (DocumentType)source;
- DocumentTypeImpl newdoctype = (DocumentTypeImpl)
- createDocumentType(srcdoctype.getNodeName(),
- srcdoctype.getPublicId(),
- srcdoctype.getSystemId());
- // Values are on NamedNodeMaps
- NamedNodeMap smap = srcdoctype.getEntities();
- NamedNodeMap tmap = newdoctype.getEntities();
- if(smap != null) {
- for(int i = 0; i < smap.getLength(); i++) {
- tmap.setNamedItem(importNode(smap.item(i), true, reversedIdentifiers));
- }
- }
- smap = srcdoctype.getNotations();
- tmap = newdoctype.getNotations();
- if (smap != null) {
- for(int i = 0; i < smap.getLength(); i++) {
- tmap.setNamedItem(importNode(smap.item(i), true, reversedIdentifiers));
- }
- }
- // NOTE: At this time, the DOM definition of DocumentType
- // doesn't cover Elements and their Attributes. domimpl's
- // extentions in that area will not be preserved, even if
- // copying from domimpl to domimpl. We could special-case
- // that here. Arguably we should. Consider. ?????
- newnode = newdoctype;
- break;
- }
-
- case DOCUMENT_FRAGMENT_NODE: {
- newnode = createDocumentFragment();
- // No name, kids carry value
- break;
- }
-
- case NOTATION_NODE: {
- Notation srcnotation = (Notation)source;
- NotationImpl newnotation =
- (NotationImpl)createNotation(source.getNodeName());
- newnotation.setPublicId(srcnotation.getPublicId());
- newnotation.setSystemId(srcnotation.getSystemId());
- // Kids carry additional value
- newnode = newnotation;
- // No name, no value
- break;
- }
-
- case DOCUMENT_NODE : // Can't import document nodes
- default: { // Unknown node type
- throw new DOMException(
- DOMException.NOT_SUPPORTED_ERR,
- "Node type being imported is not supported");
- }
- }
-
- // If deep, replicate and attach the kids.
- if (deep) {
- for (Node srckid = source.getFirstChild();
- srckid != null;
- srckid = srckid.getNextSibling()) {
- newnode.appendChild(importNode(srckid, true, reversedIdentifiers));
- }
- }
- if (newnode.getNodeType() == Node.ENTITY_REFERENCE_NODE
- || newnode.getNodeType() == Node.ENTITY_NODE) {
- ((NodeImpl)newnode).setReadOnly(true, true);
- }
- return newnode;
-
- } // importNode(Node,boolean,Hashtable):Node
-
- /**
- * DOM Level 3 WD - Experimental
- * Change the node's ownerDocument, and its subtree, to this Document
- *
- * @param source The node to adopt.
- * @see DocumentImpl.importNode
- **/
- public Node adoptNode(Node source) {
- NodeImpl node;
- try {
- node = (NodeImpl) source;
- } catch (ClassCastException e) {
- // source node comes from a different DOMImplementation
- return null;
- }
- switch (node.getNodeType()) {
- case ATTRIBUTE_NODE: {
- AttrImpl attr = (AttrImpl) node;
- // remove node from wherever it is
- attr.getOwnerElement().removeAttributeNode(attr);
- // mark it as specified
- attr.isSpecified(true);
- // change ownership
- attr.setOwnerDocument(this);
- break;
- }
- case DOCUMENT_NODE:
- case DOCUMENT_TYPE_NODE: {
- throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
- "cannot adopt this type of node.");
- }
- case ENTITY_REFERENCE_NODE: {
- // remove node from wherever it is
- Node parent = node.getParentNode();
- if (parent != null) {
- parent.removeChild(source);
- }
- // discard its replacement value
- Node child;
- while ((child = node.getFirstChild()) != null) {
- node.removeChild(child);
- }
- // change ownership
- node.setOwnerDocument(this);
- // set its new replacement value if any
- if (docType == null) {
- break;
- }
- NamedNodeMap entities = docType.getEntities();
- Node entityNode = entities.getNamedItem(node.getNodeName());
- if (entityNode == null) {
- break;
- }
- EntityImpl entity = (EntityImpl) entityNode;
- for (child = entityNode.getFirstChild();
- child != null; child = child.getNextSibling()) {
- Node childClone = child.cloneNode(true);
- node.appendChild(childClone);
- }
- break;
- }
- case ELEMENT_NODE: {
- // remove node from wherever it is
- Node parent = node.getParentNode();
- if (parent != null) {
- parent.removeChild(source);
- }
- // change ownership
- node.setOwnerDocument(this);
- // reconcile default attributes
- ((ElementImpl)node).reconcileDefaultAttributes();
- break;
- }
- default: {
- // remove node from wherever it is
- Node parent = node.getParentNode();
- if (parent != null) {
- parent.removeChild(source);
- }
- // change ownership
- node.setOwnerDocument(this);
- }
- }
- return node;
- }
-
- // identifier maintenence
- /**
- * Introduced in DOM Level 2
- * Returns the Element whose ID is given by elementId. If no such element
- * exists, returns null. Behavior is not defined if more than one element has this ID.
- * <p>
- * Note: The DOM implementation must have information that says which
- * attributes are of type ID. Attributes with the name "ID" are not of type ID unless
- * so defined. Implementations that do not know whether attributes are of type ID
- * or not are expected to return null.
- * @see #getIdentifier
- */
- public Element getElementById(String elementId) {
- return getIdentifier(elementId);
- }
-
- /**
- * Registers an identifier name with a specified element node.
- * If the identifier is already registered, the new element
- * node replaces the previous node. If the specified element
- * node is null, removeIdentifier() is called.
- *
- * @see #getIdentifier
- * @see #removeIdentifier
- */
- public void putIdentifier(String idName, Element element) {
-
- if (element == null) {
- removeIdentifier(idName);
- return;
- }
-
- if (needsSyncData()) {
- synchronizeData();
- }
-
- if (identifiers == null) {
- identifiers = new Hashtable();
- }
-
- identifiers.put(idName, element);
-
- } // putIdentifier(String,Element)
-
- /**
- * Returns a previously registered element with the specified
- * identifier name, or null if no element is registered.
- *
- * @see #putIdentifier
- * @see #removeIdentifier
- */
- public Element getIdentifier(String idName) {
-
- if (needsSyncData()) {
- synchronizeData();
- }
-
- if (identifiers == null) {
- return null;
- }
-
- return (Element)identifiers.get(idName);
-
- } // getIdentifier(String):Element
-
- /**
- * Removes a previously registered element with the specified
- * identifier name.
- *
- * @see #putIdentifier
- * @see #getIdentifier
- */
- public void removeIdentifier(String idName) {
-
- if (needsSyncData()) {
- synchronizeData();
- }
-
- if (identifiers == null) {
- return;
- }
-
- identifiers.remove(idName);
-
- } // removeIdentifier(String)
+ public DocumentImpl(DocumentType doctype, boolean grammarAccess) {
+ super(doctype, grammarAccess);
+ }
- /** Returns an enumeration registered of identifier names. */
- public Enumeration getIdentifiers() {
+ //
+ // Node methods
+ //
- if (needsSyncData()) {
- synchronizeData();
- }
+ /**
+ * Deep-clone a document, including fixing ownerDoc for the cloned
+ * children. Note that this requires bypassing the WRONG_DOCUMENT_ERR
+ * protection. I've chosen to implement it by calling importNode
+ * which is DOM Level 2.
+ *
+ * @return org.w3c.dom.Node
+ * @param deep boolean, iff true replicate children
+ */
+ public Node cloneNode(boolean deep) {
- if (identifiers == null) {
- identifiers = new Hashtable();
- }
+ DocumentImpl newdoc = new DocumentImpl();
+ cloneNode(newdoc, deep);
- return identifiers.keys();
+ // experimental
+ newdoc.mutationEvents = mutationEvents;
- } // getIdentifiers():Enumeration
+ return newdoc;
- //
- // DOM2: Namespace methods
- //
+ } // cloneNode(boolean):Node
/**
- * Introduced in DOM Level 2. <p>
- * Creates an element of the given qualified name and namespace URI.
- * If the given namespaceURI is null or an empty string and the
- * qualifiedName has a prefix that is "xml", the created element
- * is bound to the predefined namespace
- * "http://www.w3.org/XML/1998/namespace" [Namespaces].
- * @param namespaceURI The namespace URI of the element to
- * create.
- * @param qualifiedName The qualified name of the element type to
- * instantiate.
- * @return Element A new Element object with the following attributes:
- * @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
- name contains an invalid character.
- * @throws DOMException NAMESPACE_ERR: Raised if the qualifiedName has a
- * prefix that is "xml" and the namespaceURI is
- * neither null nor an empty string nor
- * "http://www.w3.org/XML/1998/namespace", or
- * if the qualifiedName has a prefix different
- * from "xml" and the namespaceURI is null or an empty string.
- * @since WD-DOM-Level-2-19990923
+ * Retrieve information describing the abilities of this particular
+ * DOM implementation. Intended to support applications that may be
+ * using DOMs retrieved from several different sources, potentially
+ * with different underlying representations.
*/
- public Element createElementNS(String namespaceURI, String qualifiedName)
- throws DOMException
- {
- if (errorChecking && !isXMLName(qualifiedName)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
- }
- return new ElementNSImpl( this, namespaceURI, qualifiedName);
+ public DOMImplementation getImplementation() {
+ // Currently implemented as a singleton, since it's hardcoded
+ // information anyway.
+ return DOMImplementationImpl.getDOMImplementation();
}
/**
- * Introduced in DOM Level 2. <p>
- * Creates an attribute of the given qualified name and namespace URI.
- * If the given namespaceURI is null or an empty string and the
- * qualifiedName has a prefix that is "xml", the created element
- * is bound to the predefined namespace
- * "http://www.w3.org/XML/1998/namespace" [Namespaces].
- *
- * @param namespaceURI The namespace URI of the attribute to
- * create. When it is null or an empty string,
- * this method behaves like createAttribute.
- * @param qualifiedName The qualified name of the attribute to
- * instantiate.
- * @return Attr A new Attr object.
- * @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
- name contains an invalid character.
- * @since WD-DOM-Level-2-19990923
+ * Store user data related to a given node
+ * This is a place where we could use weak references! Indeed, the node
+ * here won't be GC'ed as long as some user data is attached to it, since
+ * the userData table will have a reference to the node.
*/
- public Attr createAttributeNS(String namespaceURI, String qualifiedName)
- throws DOMException
- {
- if (errorChecking && !isXMLName(qualifiedName)) {
- throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
- "DOM002 Illegal character");
+ protected void setUserData(NodeImpl n, Object data) {
+ if (userData == null) {
+ userData = new Hashtable();
+ }
+ if (data == null) {
+ userData.remove(n);
+ } else {
+ userData.put(n, data);
}
- return new AttrNSImpl( this, namespaceURI, qualifiedName);
}
/**
- * Introduced in DOM Level 2. <p>
- * Returns a NodeList of all the Elements with a given local name and
- * namespace URI in the order in which they would be encountered in a preorder
- * traversal of the Document tree.
- * @param namespaceURI The namespace URI of the elements to match
- * on. The special value "*" matches all
- * namespaces. When it is null or an empty
- * string, this method behaves like
- * getElementsByTagName.
- * @param localName The local name of the elements to match on.
- * The special value "*" matches all local names.
- * @return NodeList A new NodeList object containing all the matched Elements.
- * @since WD-DOM-Level-2-19990923
+ * Retreive user data related to a given node
*/
- public NodeList getElementsByTagNameNS(String namespaceURI, String localName)
- {
- return new DeepNodeListImpl(this, namespaceURI, localName);
+ protected Object getUserData(NodeImpl n) {
+ if (userData == null) {
+ return null;
+ }
+ return userData.get(n);
}
//
@@ -1413,7 +267,7 @@
short whatToShow,
NodeFilter filter)
{
- return createNodeIterator(root,whatToShow,filter,true);
+ return createNodeIterator(root, whatToShow, filter, true);
}
/**
@@ -1426,7 +280,8 @@
* @param root The root of the iterator.
* @param whatToShow The whatToShow mask.
* @param filter The NodeFilter installed. Null means no filter.
- * @param entityReferenceExpansion true to expand the contents of EntityReference nodes
+ * @param entityReferenceExpansion true to expand the contents of
+ * EntityReference nodes
* @since WD-DOM-Level-2-19990923
*/
public NodeIterator createNodeIterator(Node root,
@@ -1434,12 +289,11 @@
NodeFilter filter,
boolean entityReferenceExpansion)
{
- NodeIterator iterator = new NodeIteratorImpl(
- this,
- root,
- whatToShow,
- filter,
- entityReferenceExpansion);
+ NodeIterator iterator = new NodeIteratorImpl(this,
+ root,
+ whatToShow,
+ filter,
+ entityReferenceExpansion);
if (iterators == null) {
iterators = new Vector();
}
@@ -1461,7 +315,7 @@
short whatToShow,
NodeFilter filter)
{
- return createTreeWalker(root,whatToShow,filter,true);
+ return createTreeWalker(root, whatToShow, filter, true);
}
/**
* Create and return a TreeWalker.
@@ -1469,7 +323,8 @@
* @param root The root of the iterator.
* @param whatToShow The whatToShow mask.
* @param filter The NodeFilter installed. Null means no filter.
- * @param entityReferenceExpansion true to expand the contents of EntityReference nodes
+ * @param entityReferenceExpansion true to expand the contents of
+ * EntityReference nodes
* @since WD-DOM-Level-2-19990923
*/
public TreeWalker createTreeWalker(Node root,
@@ -1477,10 +332,9 @@
NodeFilter filter,
boolean entityReferenceExpansion)
{
- if (root==null) {
- throw new DOMException(
- DOMException.NOT_SUPPORTED_ERR,
- "DOM007 Not supported");
+ if (root == null) {
+ throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
+ "DOM007 Not supported");
}
return new TreeWalkerImpl(root, whatToShow, filter,
entityReferenceExpansion);
@@ -1539,7 +393,7 @@
* A method to be called when some text was changed in a text node,
* so that live objects can be notified.
*/
- void replacedText(Node node) {
+ void replacedText(NodeImpl node) {
// notify ranges
if (ranges != null) {
Enumeration enum = ranges.elements();
@@ -1553,7 +407,7 @@
* A method to be called when some text was deleted from a text node,
* so that live objects can be notified.
*/
- void deletedText(Node node, int offset, int count) {
+ void deletedText(NodeImpl node, int offset, int count) {
// notify ranges
if (ranges != null) {
Enumeration enum = ranges.elements();
@@ -1569,7 +423,7 @@
* A method to be called when some text was inserted into a text node,
* so that live objects can be notified.
*/
- void insertedText(Node node, int offset, int count) {
+ void insertedText(NodeImpl node, int offset, int count) {
// notify ranges
if (ranges != null) {
Enumeration enum = ranges.elements();
@@ -1597,30 +451,6 @@
}
}
- /**
- * A method to be called when a node is removed from the tree so that live
- * objects can be notified.
- */
- void removedChildNode(Node oldChild) {
-
- // notify iterators
- if (iterators != null) {
- Enumeration enum = iterators.elements();
- while (enum.hasMoreElements()) {
- ((NodeIteratorImpl)enum.nextElement()).removeNode(oldChild);
- }
- }
-
- // notify ranges
- if (ranges != null) {
- Enumeration enum = ranges.elements();
- while (enum.hasMoreElements()) {
- ((RangeImpl)enum.nextElement()).removeNode(oldChild);
- }
- }
- }
-
-
//
// DocumentEvent methods
//
@@ -1629,88 +459,46 @@
* Introduced in DOM Level 2. Optional. <p>
* Create and return Event objects.
*
- * @param type
- * The eventType parameter specifies the type of Event interface to be created.
- * If the Event interface specified is supported by the implementation this
- * method will return a new Event of the interface type requested. If the Event
- * is to be dispatched via the dispatchEvent method the appropriate event init
- * method must be called after creation in order to initialize the Event's values.
- * As an example, a user wishing to synthesize some kind of Event would call
- * createEvent with the parameter "Events". The initEvent method could then be
- * called on the newly created Event to set the specific type of Event to be
- * dispatched and set its context information.
+ * @param type The eventType parameter specifies the type of Event
+ * interface to be created. If the Event interface specified is supported
+ * by the implementation this method will return a new Event of the
+ * interface type requested. If the Event is to be dispatched via the
+ * dispatchEvent method the appropriate event init method must be called
+ * after creation in order to initialize the Event's values. As an
+ * example, a user wishing to synthesize some kind of Event would call
+ * createEvent with the parameter "Events". The initEvent method could then
+ * be called on the newly created Event to set the specific type of Event
+ * to be dispatched and set its context information.
* @return Newly created Event
- * @exception DOMException
- * NOT_SUPPORTED_ERR: Raised if the implementation does not support the
- * type of Event interface requested
+ * @exception DOMException NOT_SUPPORTED_ERR: Raised if the implementation
+ * does not support the type of Event interface requested
* @since WD-DOM-Level-2-19990923
*/
public Event createEvent(String type)
throws DOMException {
- if(type.equalsIgnoreCase("Events") || "Event".equals(type))
+ if (type.equalsIgnoreCase("Events") || "Event".equals(type))
return new EventImpl();
- if(type.equalsIgnoreCase("MutationEvents") || "MutationEvent".equals(type))
+ if (type.equalsIgnoreCase("MutationEvents") ||
+ "MutationEvent".equals(type))
return new MutationEventImpl();
else
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"DOM007 Not supported");
}
- //
- // Object methods
- //
-
- /** Clone. */
- public Object clone() throws CloneNotSupportedException {
- DocumentImpl newdoc = (DocumentImpl)super.clone();
- newdoc.docType = null;
- newdoc.docElement = null;
- return newdoc;
- }
-
- //
- // Public static methods
- //
-
- /**
- * Check the string against XML's definition of acceptable names for
- * elements and attributes and so on using the XMLCharacterProperties
- * utility class
- */
- public static boolean isXMLName(String s) {
-
- if (s == null) {
- return false;
- }
- return XMLCharacterProperties.validName(s);
-
- } // isXMLName(String):boolean
-
/**
- * Store user data related to a given node
- * This is a place where we could use weak references! Indeed, the node
- * here won't be GC'ed as long as some user data is attached to it, since
- * the userData table will have a reference to the node.
+ * Sets whether the DOM implementation generates mutation events
+ * upon operations.
*/
- protected void setUserData(NodeImpl n, Object data) {
- if (userData == null) {
- userData = new Hashtable();
- }
- if (data == null) {
- userData.remove(n);
- } else {
- userData.put(n, data);
- }
+ void setMutationEvents(boolean set) {
+ mutationEvents = set;
}
/**
- * Retreive user data related to a given node
+ * Returns true if the DOM implementation generates mutation events.
*/
- protected Object getUserData(NodeImpl n) {
- if (userData == null) {
- return null;
- }
- return userData.get(n);
+ boolean getMutationEvents() {
+ return mutationEvents;
}
/**
@@ -1746,33 +534,745 @@
return (Vector) eventListeners.get(n);
}
+ //
+ // EventTarget support (public and internal)
+ //
+
//
- // Protected methods
+ // Constants
//
+ /*
+ * NON-DOM INTERNAL: Class LEntry is just a struct used to represent
+ * event listeners registered with this node. Copies of this object
+ * are hung from the nodeListeners Vector.
+ * <p>
+ * I considered using two vectors -- one for capture,
+ * one for bubble -- but decided that since the list of listeners
+ * is probably short in most cases, it might not be worth spending
+ * the space. ***** REVISIT WHEN WE HAVE MORE EXPERIENCE.
+ */
+ class LEntry
+ {
+ String type;
+ EventListener listener;
+ boolean useCapture;
+
+ /** NON-DOM INTERNAL: Constructor for Listener list Entry
+ * @param type Event name (NOT event group!) to listen for.
+ * @param listener Who gets called when event is dispatched
+ * @param useCaptue True iff listener is registered on
+ * capturing phase rather than at-target or bubbling
+ */
+ LEntry(String type, EventListener listener, boolean useCapture)
+ {
+ this.type = type;
+ this.listener = listener;
+ this.useCapture = useCapture;
+ }
+ } // LEntry
+
+ /**
+ * Introduced in DOM Level 2. <p> Register an event listener with this
+ * Node. A listener may be independently registered as both Capturing and
+ * Bubbling, but may only be registered once per role; redundant
+ * registrations are ignored.
+ * @param node node to add listener to
+ * @param type Event name (NOT event group!) to listen for.
+ * @param listener Who gets called when event is dispatched
+ * @param useCapture True iff listener is registered on
+ * capturing phase rather than at-target or bubbling
+ */
+ protected void addEventListener(NodeImpl node, String type,
+ EventListener listener, boolean useCapture)
+ {
+ // We can't dispatch to blank type-name, and of course we need
+ // a listener to dispatch to
+ if (type == null || type.equals("") || listener == null)
+ return;
+
+ // Each listener may be registered only once per type per phase.
+ // Simplest way to code that is to zap the previous entry, if any.
+ removeEventListener(node, type, listener, useCapture);
+
+ Vector nodeListeners = getEventListeners(node);
+ if(nodeListeners == null) {
+ nodeListeners = new Vector();
+ setEventListeners(node, nodeListeners);
+ }
+ nodeListeners.addElement(new LEntry(type, listener, useCapture));
+
+ // Record active listener
+ LCount lc = LCount.lookup(type);
+ if (useCapture)
+ ++lc.captures;
+ else
+ ++lc.bubbles;
+
+ } // addEventListener(NodeImpl,String,EventListener,boolean) :void
+
+ /**
+ * Introduced in DOM Level 2. <p> Deregister an event listener previously
+ * registered with this Node. A listener must be independently removed
+ * from the Capturing and Bubbling roles. Redundant removals (of listeners
+ * not currently registered for this role) are ignored.
+ * @param node node to remove listener from
+ * @param type Event name (NOT event group!) to listen for.
+ * @param listener Who gets called when event is dispatched
+ * @param useCapture True iff listener is registered on
+ * capturing phase rather than at-target or bubbling
+ */
+ protected void removeEventListener(NodeImpl node, String type,
+ EventListener listener,
+ boolean useCapture)
+ {
+ // If this couldn't be a valid listener registration, ignore request
+ if (type == null || type.equals("") || listener == null)
+ return;
+ Vector nodeListeners = getEventListeners(node);
+ if (nodeListeners == null)
+ return;
+
+ // Note that addListener has previously ensured that
+ // each listener may be registered only once per type per phase.
+ // count-down is OK for deletions!
+ for (int i = nodeListeners.size() - 1; i >= 0; --i) {
+ LEntry le = (LEntry) nodeListeners.elementAt(i);
+ if (le.useCapture == useCapture && le.listener == listener &&
+ le.type.equals(type)) {
+ nodeListeners.removeElementAt(i);
+ // Storage management: Discard empty listener lists
+ if (nodeListeners.size() == 0)
+ setEventListeners(node, null);
+
+ // Remove active listener
+ LCount lc = LCount.lookup(type);
+ if (useCapture)
+ --lc.captures;
+ else
+ --lc.bubbles;
+
+ break; // Found it; no need to loop farther.
+ }
+ }
+ } // removeEventListener(NodeImpl,String,EventListener,boolean) :void
+
+ /**
+ * Introduced in DOM Level 2. <p>
+ * Distribution engine for DOM Level 2 Events.
+ * <p>
+ * Event propagation runs as follows:
+ * <ol>
+ * <li>Event is dispatched to a particular target node, which invokes
+ * this code. Note that the event's stopPropagation flag is
+ * cleared when dispatch begins; thereafter, if it has
+ * been set before processing of a node commences, we instead
+ * immediately advance to the DEFAULT phase.
+ * <li>The node's ancestors are established as destinations for events.
+ * For capture and bubble purposes, node ancestry is determined at
+ * the time dispatch starts. If an event handler alters the document
+ * tree, that does not change which nodes will be informed of the event.
+ * <li>CAPTURING_PHASE: Ancestors are scanned, root to target, for
+ * Capturing listeners. If found, they are invoked (see below).
+ * <li>AT_TARGET:
+ * Event is dispatched to NON-CAPTURING listeners on the
+ * target node. Note that capturing listeners on this node are _not_
+ * invoked.
+ * <li>BUBBLING_PHASE: Ancestors are scanned, target to root, for
+ * non-capturing listeners.
+ * <li>Default processing: Some DOMs have default behaviors bound to
+ * specific nodes. If this DOM does, and if the event's preventDefault
+ * flag has not been set, we now return to the target node and process
+ * its default handler for this event, if any.
+ * </ol>
+ * <p>
+ * Note that (de)registration of handlers during
+ * processing of an event does not take effect during
+ * this phase of this event; they will not be called until
+ * the next time this node is visited by dispatchEvent.
+ * <p>
+ * If an event handler itself causes events to be dispatched, they are
+ * processed synchronously, before processing resumes
+ * on the event which triggered them. Please be aware that this may
+ * result in events arriving at listeners "out of order" relative
+ * to the actual sequence of requests.
+ * <p>
+ * Note that our implementation resets the event's stop/prevent flags
+ * when dispatch begins.
+ * I believe the DOM's intent is that event objects be redispatchable,
+ * though it isn't stated in those terms.
+ * @param node node to dispatch to
+ * @param event the event object to be dispatched to
+ * registered EventListeners
+ * @return true if the event's <code>preventDefault()</code>
+ * method was invoked by an EventListener; otherwise false.
+ */
+ protected boolean dispatchEvent(NodeImpl node, Event event) {
+ if (event == null) return false;
+
+ // Can't use anyone else's implementation, since there's no public
+ // API for setting the event's processing-state fields.
+ EventImpl evt = (EventImpl)event;
+
+ // VALIDATE -- must have been initialized at least once, must have
+ // a non-null non-blank name.
+ if(!evt.initialized || evt.type == null || evt.type.equals(""))
+ throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
+ "DOM010 Unspecified event type");
+
+ // If nobody is listening for this event, discard immediately
+ LCount lc = LCount.lookup(evt.getType());
+ if (lc.captures + lc.bubbles + lc.defaults == 0)
+ return evt.preventDefault;
+
+ // INITIALIZE THE EVENT'S DISPATCH STATUS
+ // (Note that Event objects are reusable in our implementation;
+ // that doesn't seem to be explicitly guaranteed in the DOM, but
+ // I believe it is the intent.)
+ evt.target = node;
+ evt.stopPropagation = false;
+ evt.preventDefault = false;
+
+ // Capture pre-event parentage chain, not including target;
+ // use pre-event-dispatch ancestors even if event handlers mutate
+ // document and change the target's context.
+ // Note that this is parents ONLY; events do not
+ // cross the Attr/Element "blood/brain barrier".
+ // DOMAttrModified. which looks like an exception,
+ // is issued to the Element rather than the Attr
+ // and causes a _second_ DOMSubtreeModified in the Element's
+ // tree.
+ Vector pv = new Vector(10,10);
+ Node p = node;
+ Node n = p.getParentNode();
+ while (n != null) {
+ pv.addElement(n);
+ p = n;
+ n = n.getParentNode();
+ }
+
+ // CAPTURING_PHASE:
+ if (lc.captures > 0) {
+ evt.eventPhase = Event.CAPTURING_PHASE;
+ // Ancestors are scanned, root to target, for
+ // Capturing listeners.
+ for (int j = pv.size() - 1; j >= 0; --j) {
+ if (evt.stopPropagation)
+ break; // Someone set the flag. Phase ends.
+
+ // Handle all capturing listeners on this node
+ NodeImpl nn = (NodeImpl) pv.elementAt(j);
+ evt.currentTarget = nn;
+ Vector nodeListeners = getEventListeners(nn);
+ if (nodeListeners != null) {
+ Vector nl = (Vector) nodeListeners.clone();
+ // count-down more efficient
+ for (int i = nl.size() - 1; i >= 0; --i) {
+ LEntry le = (LEntry) nl.elementAt(i);
+ if (le.useCapture && le.type.equals(evt.type)) {
+ try {
+ le.listener.handleEvent(evt);
+ }
+ catch(Exception e) {
+ // All exceptions are ignored.
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Both AT_TARGET and BUBBLE use non-capturing listeners.
+ if (lc.bubbles > 0) {
+ // AT_TARGET PHASE: Event is dispatched to NON-CAPTURING listeners
+ // on the target node. Note that capturing listeners on the target
+ // node are _not_ invoked, even during the capture phase.
+ evt.eventPhase = Event.AT_TARGET;
+ evt.currentTarget = node;
+ Vector nodeListeners = getEventListeners(node);
+ if (!evt.stopPropagation && nodeListeners != null) {
+ Vector nl = (Vector) nodeListeners.clone();
+ // count-down is more efficient
+ for (int i = nl.size() - 1; i >= 0; --i) {
+ LEntry le = (LEntry)nl.elementAt(i);
+ if (le != null && !le.useCapture &&
+ le.type.equals(evt.type)) {
+ try {
+ le.listener.handleEvent(evt);
+ }
+ catch(Exception e) {
+ // All exceptions are ignored.
+ }
+ }
+ }
+ }
+ // BUBBLING_PHASE: Ancestors are scanned, target to root, for
+ // non-capturing listeners. If the event's preventBubbling flag
+ // has been set before processing of a node commences, we
+ // instead immediately advance to the default phase.
+ // Note that not all events bubble.
+ if (evt.bubbles) {
+ evt.eventPhase = Event.BUBBLING_PHASE;
+ for (int j = 0; j < pv.size(); ++j) {
+ if (evt.stopPropagation)
+ break; // Someone set the flag. Phase ends.
+
+ // Handle all bubbling listeners on this node
+ NodeImpl nn = (NodeImpl) pv.elementAt(j);
+ evt.currentTarget = nn;
+ nodeListeners = getEventListeners(nn);
+ if (nodeListeners != null) {
+ Vector nl = (Vector) nodeListeners.clone();
+ // count-down more efficient
+ for (int i = nl.size() - 1; i >= 0; --i) {
+ LEntry le = (LEntry) nl.elementAt(i);
+ if (!le.useCapture && le.type.equals(evt.type)) {
+ try {
+ le.listener.handleEvent(evt);
+ }
+ catch(Exception e) {
+ // All exceptions are ignored.
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // DEFAULT PHASE: Some DOMs have default behaviors bound to specific
+ // nodes. If this DOM does, and if the event's preventDefault flag has
+ // not been set, we now return to the target node and process its
+ // default handler for this event, if any.
+ // No specific phase value defined, since this is DOM-internal
+ if (lc.defaults > 0 && (!evt.cancelable || !evt.preventDefault)) {
+ // evt.eventPhase = Event.DEFAULT_PHASE;
+ // evt.currentTarget = node;
+ // DO_DEFAULT_OPERATION
+ }
+
+ return evt.preventDefault;
+ } // dispatchEvent(NodeImpl,Event) :boolean
+
+
+ /**
+ * NON-DOM INTERNAL: DOMNodeInsertedIntoDocument and ...RemovedFrom...
+ * are dispatched to an entire subtree. This is the distribution code
+ * therefor. They DO NOT bubble, thanks be, but may be captured.
+ * <p>
+ * ***** At the moment I'm being sloppy and using the normal
+ * capture dispatcher on every node. This could be optimized hugely
+ * by writing a capture engine that tracks our position in the tree to
+ * update the capture chain without repeated chases up to root.
+ * @param node node to dispatch to
+ * @param n node which was directly inserted or removed
+ * @param e event to be sent to that node and its subtree
+ */
+ protected void dispatchEventToSubtree(NodeImpl node, Node n, Event e) {
+ Vector nodeListeners = getEventListeners(node);
+ if (nodeListeners == null || n == null)
+ return;
+
+ // ***** Recursive implementation. This is excessively expensive,
+ // and should be replaced in conjunction with optimization
+ // mentioned above.
+ ((NodeImpl) n).dispatchEvent(e);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ NamedNodeMap a = n.getAttributes();
+ for (int i = a.getLength() - 1; i >= 0; --i)
+ dispatchEventToSubtree(node, a.item(i), e);
+ }
+ dispatchEventToSubtree(node, n.getFirstChild(), e);
+ dispatchEventToSubtree(node, n.getNextSibling(), e);
+ } // dispatchEventToSubtree(NodeImpl,Node,Event) :void
+
+ /**
+ * NON-DOM INTERNAL: Return object for getEnclosingAttr. Carries
+ * (two values, the Attr node affected (if any) and its previous
+ * string value. Simple struct, no methods.
+ */
+ class EnclosingAttr
+ {
+ AttrImpl node;
+ String oldvalue;
+ }
+
+ EnclosingAttr savedEnclosingAttr;
+
+ /**
+ * NON-DOM INTERNAL: Convenience wrapper for calling
+ * dispatchAggregateEvents when the context was established
+ * by <code>savedEnclosingAttr</code>.
+ * @param node node to dispatch to
+ * @param ea description of Attr affected by current operation
+ */
+ protected void dispatchAggregateEvents(NodeImpl node, EnclosingAttr ea) {
+ if (ea != null)
+ dispatchAggregateEvents(node, ea.node, ea.oldvalue,
+ MutationEvent.MODIFICATION);
+ else
+ dispatchAggregateEvents(node, null, null, (short) 0);
+
+ } // dispatchAggregateEvents(NodeImpl,EnclosingAttr) :void
+
+ /**
+ * NON-DOM INTERNAL: Generate the "aggregated" post-mutation events
+ * DOMAttrModified and DOMSubtreeModified.
+ * Both of these should be issued only once for each user-requested
+ * mutation operation, even if that involves multiple changes to
+ * the DOM.
+ * For example, if a DOM operation makes multiple changes to a single
+ * Attr before returning, it would be nice to generate only one
+ * DOMAttrModified, and multiple changes over larger scope but within
+ * a recognizable single subtree might want to generate only one
+ * DOMSubtreeModified, sent to their lowest common ancestor.
+ * <p>
+ * To manage this, use the "internal" versions of insert and remove
+ * with MUTATION_LOCAL, then make an explicit call to this routine
+ * at the higher level. Some examples now exist in our code.
+ *
+ * @param node The node to dispatch to
+ * @param enclosingAttr The Attr node (if any) whose value has been changed
+ * as a result of the DOM operation. Null if none such.
+ * @param oldValue The String value previously held by the
+ * enclosingAttr. Ignored if none such.
+ * @param change Type of modification to the attr. See
+ * MutationEvent.attrChange
+ */
+ protected void dispatchAggregateEvents(NodeImpl node,
+ AttrImpl enclosingAttr,
+ String oldvalue, short change) {
+ // We have to send DOMAttrModified.
+ NodeImpl owner = null;
+ if (enclosingAttr != null) {
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
+ owner = (NodeImpl) enclosingAttr.getOwnerElement();
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ if (owner != null) {
+ MutationEventImpl me = new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl.DOM_ATTR_MODIFIED,
+ true, false, enclosingAttr,
+ oldvalue,
+ enclosingAttr.getNodeValue(),
+ enclosingAttr.getNodeName(),
+ change);
+ owner.dispatchEvent(me);
+ }
+ }
+ }
+ // DOMSubtreeModified gets sent to the lowest common root of a
+ // set of changes.
+ // "This event is dispatched after all other events caused by the
+ // mutation have been fired."
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_SUBTREE_MODIFIED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ MutationEvent me = new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl.DOM_SUBTREE_MODIFIED,
+ true, false, null, null,
+ null, null, (short) 0);
+
+ // If we're within an Attr, DStM gets sent to the Attr
+ // and to its owningElement. Otherwise we dispatch it
+ // locally.
+ if (enclosingAttr != null) {
+ dispatchEvent(enclosingAttr, me);
+ if (owner != null)
+ dispatchEvent(owner, me);
+ }
+ else
+ dispatchEvent(node, me);
+ }
+ } // dispatchAggregateEvents(NodeImpl, AttrImpl,String) :void
+
+ /**
+ * NON-DOM INTERNAL: Pre-mutation context check, in
+ * preparation for later generating DOMAttrModified events.
+ * Determines whether this node is within an Attr
+ * @param node node to get enclosing attribute for
+ * @return either a description of that Attr, or null if none such.
+ */
+ protected void saveEnclosingAttr(NodeImpl node) {
+ savedEnclosingAttr = null;
+ // MUTATION PREPROCESSING AND PRE-EVENTS:
+ // If we're within the scope of an Attr and DOMAttrModified
+ // was requested, we need to preserve its previous value for
+ // that event.
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ NodeImpl eventAncestor = node;
+ while (true) {
+ if (eventAncestor == null)
+ return;
+ int type = eventAncestor.getNodeType();
+ if (type == Node.ATTRIBUTE_NODE) {
+ EnclosingAttr retval = new EnclosingAttr();
+ retval.node = (AttrImpl) eventAncestor;
+ retval.oldvalue = retval.node.getNodeValue();
+ savedEnclosingAttr = retval;
+ return;
+ }
+ else if (type == Node.ENTITY_REFERENCE_NODE)
+ eventAncestor = eventAncestor.parentNode();
+ else
+ return;
+ // Any other parent means we're not in an Attr
+ }
+ }
+ } // saveEnclosingAttr(NodeImpl) :void
+
+ /**
+ * A method to be called when a character data node has been modified
+ */
+ void modifyingCharacterData(NodeImpl node) {
+ if (mutationEvents) {
+ saveEnclosingAttr(node);
+ }
+ }
+
+ /**
+ * A method to be called when a character data node has been modified
+ */
+ void modifiedCharacterData(NodeImpl node, String oldvalue, String value) {
+ if (mutationEvents) {
+ // MUTATION POST-EVENTS:
+ LCount lc =
+ LCount.lookup(MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ MutationEvent me = new MutationEventImpl();
+ me.initMutationEvent(
+ MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED,
+ true, false, null,
+ oldvalue, value, null, (short) 0);
+ dispatchEvent(me);
+ }
+
+ // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
+ // if required. (Common to most kinds of mutation)
+ dispatchAggregateEvents(node, savedEnclosingAttr);
+ } // End mutation postprocessing
+ }
+
+ /**
+ * A method to be called when a node is about to be inserted in the tree.
+ */
+ void insertingNode(NodeImpl node, boolean replace) {
+ if (mutationEvents) {
+ if (!replace) {
+ saveEnclosingAttr(node);
+ }
+ }
+ }
+
+ /**
+ * A method to be called when a node has been inserted in the tree.
+ */
+ void insertedNode(NodeImpl node, NodeImpl newInternal, boolean replace) {
+ if (mutationEvents) {
+ // MUTATION POST-EVENTS:
+ // "Local" events (non-aggregated)
+ // New child is told it was inserted, and where
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_NODE_INSERTED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ MutationEventImpl me = new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl.DOM_NODE_INSERTED,
+ true, false, node,
+ null, null, null, (short) 0);
+ dispatchEvent(newInternal, me);
+ }
+
+ // If within the Document, tell the subtree it's been added
+ // to the Doc.
+ lc = LCount.lookup(
+ MutationEventImpl.DOM_NODE_INSERTED_INTO_DOCUMENT);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ NodeImpl eventAncestor = node;
+ if (savedEnclosingAttr != null)
+ eventAncestor = (NodeImpl)
+ savedEnclosingAttr.node.getOwnerElement();
+ if (eventAncestor != null) { // Might have been orphan Attr
+ NodeImpl p = eventAncestor;
+ while (p != null) {
+ eventAncestor = p; // Last non-null ancestor
+ // In this context, ancestry includes
+ // walking back from Attr to Element
+ if (p.getNodeType() == ATTRIBUTE_NODE) {
+ p = (NodeImpl) ((AttrImpl)p).getOwnerElement();
+ }
+ else {
+ p = p.parentNode();
+ }
+ }
+ if (eventAncestor.getNodeType() == Node.DOCUMENT_NODE){
+ MutationEventImpl me = new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl
+ .DOM_NODE_INSERTED_INTO_DOCUMENT,
+ false,false,null,null,
+ null,null,(short)0);
+ dispatchEventToSubtree(node, newInternal, me);
+ }
+ }
+ }
+ if (!replace) {
+ // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified
+ // (Common to most kinds of mutation)
+ dispatchAggregateEvents(node, savedEnclosingAttr);
+ }
+ }
+ }
+
+ /**
+ * A method to be called when a node is about to be removed from the tree.
+ */
+ void removingNode(NodeImpl node, NodeImpl oldChild, boolean replace) {
+
+ // notify iterators
+ if (iterators != null) {
+ Enumeration enum = iterators.elements();
+ while (enum.hasMoreElements()) {
+ ((NodeIteratorImpl)enum.nextElement()).removeNode(oldChild);
+ }
+ }
+
+ // notify ranges
+ if (ranges != null) {
+ Enumeration enum = ranges.elements();
+ while (enum.hasMoreElements()) {
+ ((RangeImpl)enum.nextElement()).removeNode(oldChild);
+ }
+ }
+
+ // mutation events
+ if (mutationEvents) {
+ // MUTATION PREPROCESSING AND PRE-EVENTS:
+ // If we're within the scope of an Attr and DOMAttrModified
+ // was requested, we need to preserve its previous value for
+ // that event.
+ if (!replace) {
+ saveEnclosingAttr(node);
+ }
+ // Child is told that it is about to be removed
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_NODE_REMOVED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ MutationEventImpl me= new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl.DOM_NODE_REMOVED,
+ true, false, node, null,
+ null, null, (short) 0);
+ dispatchEvent(oldChild, me);
+ }
+
+ // If within Document, child's subtree is informed that it's
+ // losing that status
+ lc = LCount.lookup(
+ MutationEventImpl.DOM_NODE_REMOVED_FROM_DOCUMENT);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ NodeImpl eventAncestor = this;
+ if(savedEnclosingAttr != null)
+ eventAncestor = (NodeImpl)
+ savedEnclosingAttr.node.getOwnerElement();
+ if (eventAncestor != null) { // Might have been orphan Attr
+ for (NodeImpl p = eventAncestor.parentNode();
+ p != null; p = p.parentNode()) {
+ eventAncestor = p; // Last non-null ancestor
+ }
+ if (eventAncestor.getNodeType() == Node.DOCUMENT_NODE){
+ MutationEventImpl me = new MutationEventImpl();
+ me.initMutationEvent(
+ MutationEventImpl.DOM_NODE_REMOVED_FROM_DOCUMENT,
+ false, false, null,
+ null, null, null, (short) 0);
+ dispatchEventToSubtree(node, oldChild, me);
+ }
+ }
+ }
+ } // End mutation preprocessing
+ }
+
+ /**
+ * A method to be called when a node has been removed from the tree.
+ */
+ void removedNode(NodeImpl node, boolean replace) {
+ if (mutationEvents) {
+ // MUTATION POST-EVENTS:
+ // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
+ // if required. (Common to most kinds of mutation)
+ if (!replace) {
+ dispatchAggregateEvents(node, savedEnclosingAttr);
+ }
+ } // End mutation postprocessing
+ }
+
/**
- * Uses the kidOK lookup table to check whether the proposed
- * tree structure is legal.
+ * A method to be called when a node is about to be replaced in the tree.
*/
- protected boolean isKidOK(Node parent, Node child) {
- if (allowGrammarAccess && parent.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
- return child.getNodeType() == Node.ELEMENT_NODE;
+ void replacingNode(NodeImpl node) {
+ if (mutationEvents) {
+ saveEnclosingAttr(node);
}
- return 0 != (kidOK[parent.getNodeType()] & 1 << child.getNodeType());
}
/**
- * Denotes that this node has changed.
+ * A method to be called when a node has been replaced in the tree.
*/
- protected void changed() {
- changes++;
+ void replacedNode(NodeImpl node) {
+ if (mutationEvents) {
+ dispatchAggregateEvents(node, savedEnclosingAttr);
+ }
+ }
+
+ /**
+ * A method to be called when an attribute value has been modified
+ */
+ void modifiedAttrValue(AttrImpl attr, String oldvalue) {
+ if (mutationEvents) {
+ // MUTATION POST-EVENTS:
+ dispatchAggregateEvents(attr, attr, oldvalue,
+ MutationEvent.MODIFICATION);
+ }
+ }
+
+ /**
+ * A method to be called when an attribute node has been set
+ */
+ void setAttrNode(AttrImpl attr, AttrImpl previous) {
+ if (mutationEvents) {
+ // MUTATION POST-EVENTS:
+ if (previous == null) {
+ dispatchAggregateEvents(attr.ownerNode, attr, null,
+ MutationEvent.ADDITION);
+ }
+ else {
+ dispatchAggregateEvents(attr.ownerNode, attr,
+ previous.getNodeValue(),
+ MutationEvent.MODIFICATION);
+ }
+ }
}
/**
- * Returns the number of changes to this node.
+ * A method to be called when an attribute node has been removed
*/
- protected int changes() {
- return changes;
+ void removedAttrNode(AttrImpl attr, NodeImpl oldOwner, String name) {
+ // We can't use the standard dispatchAggregate, since it assumes
+ // that the Attr is still attached to an owner. This code is
+ // similar but dispatches to the previous owner, "element".
+ if (mutationEvents) {
+ // If we have to send DOMAttrModified (determined earlier),
+ // do so.
+ LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
+ if (lc.captures + lc.bubbles + lc.defaults > 0) {
+ MutationEventImpl me= new MutationEventImpl();
+ me.initMutationEvent(MutationEventImpl.DOM_ATTR_MODIFIED,
+ true, false, null,
+ attr.getNodeValue(), null, name,
+ MutationEvent.REMOVAL);
+ dispatchEvent(oldOwner, me);
+ }
+
+ // We can hand off to process DOMSubtreeModified, though.
+ // Note that only the Element needs to be informed; the
+ // Attr's subtree has not been changed by this operation.
+ dispatchAggregateEvents(oldOwner, null, null, (short) 0);
+ }
}
} // class DocumentImpl
1.18 +6 -5 xml-xerces/java/src/org/apache/xerces/dom/DocumentTypeImpl.java
Index: DocumentTypeImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/DocumentTypeImpl.java,v
retrieving revision 1.17
retrieving revision 1.18
diff -u -r1.17 -r1.18
--- DocumentTypeImpl.java 2001/07/24 00:42:26 1.17
+++ DocumentTypeImpl.java 2001/08/10 01:18:16 1.18
@@ -127,7 +127,7 @@
//
/** Factory method for creating a document type node. */
- public DocumentTypeImpl(DocumentImpl ownerDocument, String name) {
+ public DocumentTypeImpl(CoreDocumentImpl ownerDocument, String name) {
super(ownerDocument);
this.name = name;
@@ -138,16 +138,17 @@
// NON-DOM
elements = new NamedNodeMapImpl(this);
- } // <init>(DocumentImpl,String)
+ } // <init>(CoreDocumentImpl,String)
/** Factory method for creating a document type node. */
- public DocumentTypeImpl(DocumentImpl ownerDocument, String qualifiedName,
+ public DocumentTypeImpl(CoreDocumentImpl ownerDocument,
+ String qualifiedName,
String publicID, String systemID) {
this(ownerDocument, qualifiedName);
this.publicID = publicID;
this.systemID = systemID;
- } // <init>(DocumentImpl,String)
+ } // <init>(CoreDocumentImpl,String)
//
// DOM2: methods.
@@ -242,7 +243,7 @@
* NON-DOM
* set the ownerDocument of this node and its children
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
super.setOwnerDocument(doc);
entities.setOwnerDocument(doc);
notations.setOwnerDocument(doc);
1.10 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/ElementDefinitionImpl.java
Index: ElementDefinitionImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ElementDefinitionImpl.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- ElementDefinitionImpl.java 2001/07/24 00:42:26 1.9
+++ ElementDefinitionImpl.java 2001/08/10 01:18:16 1.10
@@ -94,7 +94,7 @@
//
/** Factory constructor. */
- public ElementDefinitionImpl(DocumentImpl ownerDocument, String name) {
+ public ElementDefinitionImpl(CoreDocumentImpl ownerDocument, String name) {
super(ownerDocument);
this.name = name;
attributes = new NamedNodeMapImpl(ownerDocument);
1.37 +41 -37 xml-xerces/java/src/org/apache/xerces/dom/ElementImpl.java
Index: ElementImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ElementImpl.java,v
retrieving revision 1.36
retrieving revision 1.37
diff -u -r1.36 -r1.37
--- ElementImpl.java 2001/07/24 00:42:26 1.36
+++ ElementImpl.java 2001/08/10 01:18:16 1.37
@@ -114,7 +114,7 @@
//
/** Factory constructor. */
- public ElementImpl(DocumentImpl ownerDoc, String name) {
+ public ElementImpl(CoreDocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
needsSyncData(true); // synchronizeData will initialize attributes
@@ -187,7 +187,7 @@
* NON-DOM
* set the ownerDocument of this node, its children, and its attributes
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
super.setOwnerDocument(doc);
if (attributes != null) {
attributes.setOwnerDocument(doc);
@@ -541,22 +541,23 @@
/**
* Introduced in DOM Level 2. <p>
*
- * Adds a new attribute.
- * If the given namespaceURI is null or an empty string and
- * the qualifiedName has a prefix that is "xml", the new attribute is bound to the
- * predefined namespace "http://www.w3.org/XML/1998/namespace" [Namespaces].
- * If an attribute with the same local name and namespace URI is already present on
- * the element, its prefix is changed to be the prefix part of the qualifiedName, and
- * its value is changed to be the value parameter. This value is a simple string, it is not
- * parsed as it is being set. So any markup (such as syntax to be recognized as an
- * entity reference) is treated as literal text, and needs to be appropriately escaped by
- * the implementation when it is written out. In order to assign an attribute value that
- * contains entity references, the user must create an Attr node plus any Text and
- * EntityReference nodes, build the appropriate subtree, and use
- * setAttributeNodeNS or setAttributeNode to assign it as the value of an
- * attribute.
- * @param namespaceURI
- * The namespace URI of the attribute to create
+ * Adds a new attribute.
+ * If the given namespaceURI is null or an empty string and the
+ * qualifiedName has a prefix that is "xml", the new attribute is bound to
+ * the predefined namespace "http://www.w3.org/XML/1998/namespace"
+ * [Namespaces]. If an attribute with the same local name and namespace
+ * URI is already present on the element, its prefix is changed to be the
+ * prefix part of the qualifiedName, and its value is changed to be the
+ * value parameter. This value is a simple string, it is not parsed as it
+ * is being set. So any markup (such as syntax to be recognized as an
+ * entity reference) is treated as literal text, and needs to be
+ * appropriately escaped by the implementation when it is written out. In
+ * order to assign an attribute value that contains entity references, the
+ * user must create an Attr node plus any Text and EntityReference nodes,
+ * build the appropriate subtree, and use setAttributeNodeNS or
+ * setAttributeNode to assign it as the value of an attribute.
+ *
+ * @param namespaceURI The namespace URI of the attribute to create
* or alter.
* @param localName The local name of the attribute to create or
* alter.
@@ -568,14 +569,14 @@
* node is readonly.
*
* @throws NAMESPACE_ERR: Raised if the qualifiedName
- * has a prefix that is "xml" and the namespaceURI is
- * neither null nor an empty string nor
- * "http://www.w3.org/XML/1998/namespace", or if the
- * qualifiedName has a prefix that is "xmlns" but the
- * namespaceURI is neither null nor an empty string, or
- * if if the qualifiedName has a prefix different from
- * "xml" and "xmlns" and the namespaceURI is null or an
- * empty string.
+ * has a prefix that is "xml" and the namespaceURI
+ * is neither null nor an empty string nor
+ * "http://www.w3.org/XML/1998/namespace", or if
+ * the qualifiedName has a prefix that is "xmlns"
+ * but the namespaceURI is neither null nor an
+ * empty string, or if if the qualifiedName has a
+ * prefix different from "xml" and "xmlns" and the
+ * namespaceURI is null or an empty string.
* @since WD-DOM-Level-2-19990923
*/
public void setAttributeNS(String namespaceURI, String localName, String value) {
@@ -673,9 +674,10 @@
* @param Attr The Attr node to add to the attribute list. When
* the Node has no namespaceURI, this method behaves
* like setAttributeNode.
- * @return Attr If the newAttr attribute replaces an existing attribute with the same
- * local name and namespace URI, the previously existing Attr node is
- * returned, otherwise null is returned.
+ * @return Attr If the newAttr attribute replaces an existing attribute
+ * with the same local name and namespace URI, the *
+ * previously existing Attr node is returned, otherwise
+ * null is returned.
* @throws WRONG_DOCUMENT_ERR: Raised if newAttr
* was created from a different document than the one that
* created the element.
@@ -744,8 +746,8 @@
* Introduced in DOM Level 2. <p>
*
* Returns a NodeList of all the Elements with a given local name and
- * namespace URI in the order in which they would be encountered in a preorder
- * traversal of the Document tree, starting from this node.
+ * namespace URI in the order in which they would be encountered in a
+ * preorder traversal of the Document tree, starting from this node.
*
* @param namespaceURI The namespace URI of the elements to match
* on. The special value "*" matches all
@@ -754,10 +756,12 @@
* getElementsByTagName.
* @param localName The local name of the elements to match on.
* The special value "*" matches all local names.
- * @return NodeList A new NodeList object containing all the matched Elements.
+ * @return NodeList A new NodeList object containing all the matched
+ * Elements.
* @since WD-DOM-Level-2-19990923
*/
- public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
+ public NodeList getElementsByTagNameNS(String namespaceURI,
+ String localName) {
return new DeepNodeListImpl(this, namespaceURI, localName);
}
@@ -787,14 +791,14 @@
needsSyncData(false);
// we don't want to generate any event for this so turn them off
- boolean orig = ownerDocument.mutationEvents;
- ownerDocument.mutationEvents = false;
+ boolean orig = ownerDocument.getMutationEvents();
+ ownerDocument.setMutationEvents(false);
// attributes
setupDefaultAttributes();
// set mutation events flag back to its original value
- ownerDocument.mutationEvents = orig;
+ ownerDocument.setMutationEvents(orig);
} // synchronizeData()
@@ -830,6 +834,6 @@
}
return (NamedNodeMapImpl) eldef.getAttributes();
- } // setupAttributes(DocumentImpl)
+ } // getDefaultAttributes()
} // class ElementImpl
1.16 +4 -4 xml-xerces/java/src/org/apache/xerces/dom/ElementNSImpl.java
Index: ElementNSImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ElementNSImpl.java,v
retrieving revision 1.15
retrieving revision 1.16
diff -u -r1.15 -r1.16
--- ElementNSImpl.java 2001/07/24 00:42:26 1.15
+++ ElementNSImpl.java 2001/08/10 01:18:16 1.16
@@ -1,4 +1,4 @@
-/* $Id: ElementNSImpl.java,v 1.15 2001/07/24 00:42:26 lehors Exp $ */
+/* $Id: ElementNSImpl.java,v 1.16 2001/08/10 01:18:16 lehors Exp $ */
/*
* The Apache Software License, Version 1.1
*
@@ -93,7 +93,7 @@
/**
* DOM2: Constructor for Namespace implementation.
*/
- protected ElementNSImpl(DocumentImpl ownerDocument,
+ protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI,
String qualifiedName)
throws DOMException
@@ -132,7 +132,7 @@
}
// for DeferredElementImpl
- protected ElementNSImpl(DocumentImpl ownerDocument,
+ protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String value) {
super(ownerDocument, value);
}
@@ -210,7 +210,7 @@
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
- if (!DocumentImpl.isXMLName(prefix)) {
+ if (!CoreDocumentImpl.isXMLName(prefix)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
1.13 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/EntityImpl.java
Index: EntityImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/EntityImpl.java,v
retrieving revision 1.12
retrieving revision 1.13
diff -u -r1.12 -r1.13
--- EntityImpl.java 2001/07/24 00:42:26 1.12
+++ EntityImpl.java 2001/08/10 01:18:16 1.13
@@ -133,7 +133,7 @@
//
/** Factory constructor. */
- public EntityImpl(DocumentImpl ownerDoc, String name) {
+ public EntityImpl(CoreDocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
isReadOnly(true);
1.12 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/EntityReferenceImpl.java
Index: EntityReferenceImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/EntityReferenceImpl.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- EntityReferenceImpl.java 2001/07/24 00:42:26 1.11
+++ EntityReferenceImpl.java 2001/08/10 01:18:16 1.12
@@ -147,7 +147,7 @@
//
/** Factory constructor. */
- public EntityReferenceImpl(DocumentImpl ownerDoc, String name) {
+ public EntityReferenceImpl(CoreDocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
isReadOnly(true);
1.23 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/NamedNodeMapImpl.java
Index: NamedNodeMapImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/NamedNodeMapImpl.java,v
retrieving revision 1.22
retrieving revision 1.23
diff -u -r1.22 -r1.23
--- NamedNodeMapImpl.java 2001/07/24 00:42:26 1.22
+++ NamedNodeMapImpl.java 2001/08/10 01:18:16 1.23
@@ -415,7 +415,7 @@
* NON-DOM
* set the ownerDocument of this node, and the attributes it contains
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
if (nodes != null) {
for (int i = 0; i < nodes.size(); i++) {
((NodeImpl)item(i)).setOwnerDocument(doc);
1.42 +60 -580 xml-xerces/java/src/org/apache/xerces/dom/NodeImpl.java
Index: NodeImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/NodeImpl.java,v
retrieving revision 1.41
retrieving revision 1.42
diff -u -r1.41 -r1.42
--- NodeImpl.java 2001/07/24 00:42:26 1.41
+++ NodeImpl.java 2001/08/10 01:18:16 1.42
@@ -2,7 +2,7 @@
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999 The Apache Software Foundation. All rights
+ * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -68,16 +68,11 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.Event;
-import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
-import org.w3c.dom.events.MutationEvent;
-import org.apache.xerces.dom.events.EventImpl;
-import org.apache.xerces.dom.events.MutationEventImpl;
-
/**
- * Node provides the basic structure of a DOM tree. It is never used
+ * NodeImpl provides the basic structure of a DOM tree. It is never used
* directly, but instead is subclassed to add type and data
* information, and additional methods, appropriate to each node of
* the tree. Only its subclasses should be instantiated -- and those,
@@ -109,6 +104,10 @@
* though, so there is never more than one level of indirection.
* And when a node doesn't have an owner, ownerNode refers to its
* ownerDocument.
+ * <p>
+ * This class doesn't directly support mutation events, however, it still
+ * implements the EventTarget interface and forward all related calls to the
+ * document so that the document class do so.
*
* @author Arnaud Le Hors, IBM
* @author Joe Kesselman, IBM
@@ -149,9 +148,8 @@
protected final static short FIRSTCHILD = 0x1<<4;
protected final static short SPECIFIED = 0x1<<5;
protected final static short IGNORABLEWS = 0x1<<6;
- protected final static short SETVALUE = 0x1<<7;
- protected final static short HASSTRING = 0x1<<8;
- protected final static short UNNORMALIZED = 0x1<<9;
+ protected final static short HASSTRING = 0x1<<7;
+ protected final static short UNNORMALIZED = 0x1<<8;
//
// Constructors
@@ -163,10 +161,10 @@
* <p>
* Every Node knows what Document it belongs to.
*/
- protected NodeImpl(DocumentImpl ownerDocument) {
+ protected NodeImpl(CoreDocumentImpl ownerDocument) {
// as long as we do not have any owner, ownerNode is our ownerDocument
ownerNode = ownerDocument;
- } // <init>(DocumentImpl)
+ } // <init>(CoreDocumentImpl)
/** Constructor for serialization. */
public NodeImpl() {}
@@ -293,15 +291,15 @@
/**
* same as above but returns internal type and this one is not overridden
- * by DocumentImpl to return null
+ * by CoreDocumentImpl to return null
*/
- DocumentImpl ownerDocument() {
+ CoreDocumentImpl ownerDocument() {
// if we have an owner simply forward the request
// otherwise ownerNode is our ownerDocument
if (isOwned()) {
return ownerNode.ownerDocument();
} else {
- return (DocumentImpl) ownerNode;
+ return (CoreDocumentImpl) ownerNode;
}
}
@@ -309,7 +307,7 @@
* NON-DOM
* set the ownerDocument of this node
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
if (needsSyncData()) {
synchronizeData();
}
@@ -566,17 +564,17 @@
/**
* Introduced in DOM Level 2. <p>
- * Tests whether the DOM implementation implements a specific feature and that
- * feature is supported by this node.
- * @param feature The package name of the feature to test. This is the
- * same name as what can be passed to the method
- * hasFeature on DOMImplementation.
- * @param version This is the version number of the package name to
- * test. In Level 2, version 1, this is the string "2.0". If
- * the version is not specified, supporting any version of
- * the feature will cause the method to return true.
- * @return boolean Returns true if this node defines a subtree within which the
- * specified feature is supported, false otherwise.
+ * Tests whether the DOM implementation implements a specific feature and
+ * that feature is supported by this node.
+ * @param feature The package name of the feature to test. This is the same
+ * name as what can be passed to the method hasFeature on
+ * DOMImplementation.
+ * @param version This is the version number of the package name to
+ * test. In Level 2, version 1, this is the string "2.0". If the version is
+ * not specified, supporting any version of the feature will cause the
+ * method to return true.
+ * @return boolean Returns true if this node defines a subtree within which
+ * the specified feature is supported, false otherwise.
* @since WD-DOM-Level-2-19990923
*/
public boolean isSupported(String feature, String version)
@@ -588,13 +586,13 @@
/**
* Introduced in DOM Level 2. <p>
*
- * The namespace URI of this node, or null if it is unspecified. When this node
- * is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE, this is always
- * null and setting it has no effect. <p>
- *
- * This is not a computed value that is the result of a namespace lookup based on
- * an examination of the namespace declarations in scope. It is merely the
- * namespace URI given at creation time.<p>
+ * The namespace URI of this node, or null if it is unspecified. When this
+ * node is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE, this is
+ * always null and setting it has no effect. <p>
+ *
+ * This is not a computed value that is the result of a namespace lookup
+ * based on an examination of the namespace declarations in scope. It is
+ * merely the namespace URI given at creation time.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null.
@@ -610,9 +608,9 @@
/**
* Introduced in DOM Level 2. <p>
*
- * The namespace prefix of this node, or null if it is unspecified. When this
- * node is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE this is
- * always null and setting it has no effect.<p>
+ * The namespace prefix of this node, or null if it is unspecified. When
+ * this node is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE this
+ * is always null and setting it has no effect.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null. <p>
@@ -629,16 +627,16 @@
/**
* Introduced in DOM Level 2. <p>
*
- * The namespace prefix of this node, or null if it is unspecified. When this
- * node is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE this is
- * always null and setting it has no effect.<p>
- *
- * For nodes created with a DOM Level 1 method, such as createElement
- * from the Document interface, this is null.<p>
- *
- * Note that setting this attribute changes the nodeName attribute, which holds the
- * qualified name, as well as the tagName and name attributes of the Element
- * and Attr interfaces, when applicable.<p>
+ * The namespace prefix of this node, or null if it is unspecified. When
+ * this node is of any type other than ELEMENT_NODE and ATTRIBUTE_NODE
+ * this is always null and setting it has no effect.<p>
+ *
+ * For nodes created with a DOM Level 1 method, such as createElement from
+ * the Document interface, this is null.<p>
+ *
+ * Note that setting this attribute changes the nodeName attribute, which
+ * holds the qualified name, as well as the tagName and name attributes of
+ * the Element and Attr interfaces, when applicable.<p>
*
* @throws INVALID_CHARACTER_ERR Raised if the specified
* prefix contains an invalid character.
@@ -671,536 +669,26 @@
return null;
}
-
//
- // EventTarget support (public and internal)
+ // EventTarget support
//
- // Constants
- //
- /** Compile-time flag. If false, disables our code for
- the DOM Level 2 Events module, perhaps allowing it
- to be optimized out to save bytecodes.
- */
- protected final static boolean MUTATIONEVENTS=true;
-
- /** The MUTATION_ values are parameters to the NON-DOM
- internalInsertBefore() and internalRemoveChild() operations,
- allowing us to control which MutationEvents are generated.
- */
- protected final static int MUTATION_NONE=0x00;
- protected final static int MUTATION_LOCAL=0x01;
- protected final static int MUTATION_AGGREGATE=0x02;
- protected final static int MUTATION_ALL=0xffff;
-
- /* NON-DOM INTERNAL: Class LEntry is just a struct used to represent
- * event listeners registered with this node. Copies of this object
- * are hung from the nodeListeners Vector.
- * <p>
- * I considered using two vectors -- one for capture,
- * one for bubble -- but decided that since the list of listeners
- * is probably short in most cases, it might not be worth spending
- * the space. ***** REVISIT WHEN WE HAVE MORE EXPERIENCE.
- */
- class LEntry
- {
- String type;
- EventListener listener;
- boolean useCapture;
-
- /** NON-DOM INTERNAL: Constructor for Listener list Entry
- * @param type Event name (NOT event group!) to listen for.
- * @param listener Who gets called when event is dispatched
- * @param useCaptue True iff listener is registered on
- * capturing phase rather than at-target or bubbling
- */
- LEntry(String type,EventListener listener,boolean useCapture)
- {
- this.type=type;this.listener=listener;this.useCapture=useCapture;
- }
- }; // LEntry
-
- /** Introduced in DOM Level 2. <p>
- * Register an event listener with this Node. A listener may be independently
- * registered as both Capturing and Bubbling, but may only be
- * registered once per role; redundant registrations are ignored.
- * @param type Event name (NOT event group!) to listen for.
- * @param listener Who gets called when event is dispatched
- * @param useCapture True iff listener is registered on
- * capturing phase rather than at-target or bubbling
- */
- public void addEventListener(String type,EventListener listener,boolean useCapture)
- {
- // We can't dispatch to blank type-name, and of course we need
- // a listener to dispatch to
- if(type==null || type.equals("") || listener==null)
- return;
-
- // Each listener may be registered only once per type per phase.
- // Simplest way to code that is to zap the previous entry, if any.
- removeEventListener(type,listener,useCapture);
-
- Vector nodeListeners = ownerDocument().getEventListeners(this);
- if(nodeListeners==null) {
- nodeListeners=new Vector();
- ownerDocument().setEventListeners(this, nodeListeners);
- }
- nodeListeners.addElement(new LEntry(type,listener,useCapture));
-
- // Record active listener
- LCount lc=LCount.lookup(type);
- if(useCapture)
- ++lc.captures;
- else
- ++lc.bubbles;
-
- } // addEventListener(String,EventListener,boolean) :void
-
- /** Introduced in DOM Level 2. <p>
- * Deregister an event listener previously registered with this Node.
- * A listener must be independently removed from the
- * Capturing and Bubbling roles. Redundant removals (of
- * listeners not currently registered for this role) are ignored.
- * @param type Event name (NOT event group!) to listen for.
- * @param listener Who gets called when event is dispatched
- * @param useCapture True iff listener is registered on
- * capturing phase rather than at-target or bubbling
- */
- public void removeEventListener(String type,EventListener listener,boolean useCapture)
- {
- // If this couldn't be a valid listener registration, ignore request
- Vector nodeListeners = ownerDocument().getEventListeners(this);
- if(nodeListeners==null || type==null || type.equals("") || listener==null)
- return;
-
- // Note that addListener has previously ensured that
- // each listener may be registered only once per type per phase.
- for(int i=nodeListeners.size()-1;i>=0;--i) // count-down is OK for deletions!
- {
- LEntry le=(LEntry)(nodeListeners.elementAt(i));
- if(le.useCapture==useCapture && le.listener==listener &&
- le.type.equals(type))
- {
- nodeListeners.removeElementAt(i);
- // Storage management: Discard empty listener lists
- if(nodeListeners.size()==0)
- ownerDocument().setEventListeners(this, null);
-
- // Remove active listener
- LCount lc=LCount.lookup(type);
- if(useCapture)
- --lc.captures;
- else
- --lc.bubbles;
-
- break; // Found it; no need to loop farther.
- }
- }
- } // removeEventListener(String,EventListener,boolean) :void
-
- /** COMMENTED OUT **
- Now that event listeners are stored on the document with the node
- as the key, nodes can't be finalized if they have any event
- listener. This finalize method becomes useless... This is a place
- where we could definitely use weak references!! If we did, then
- this finalize method could be put back in (which is why I don't
- remove if completely). - ALH
- ** NON-DOM INTERNAL:
- A finalizer has added to NodeImpl in order to correct the event-usage
- counts of any remaining listeners before discarding the Node.
- This isn't absolutely required, and finalizers are of dubious
- reliability and have odd effects on some implementations of GC.
- But given the expense of event generation and distribution it
- seems a worthwhile safety net.
- ***** RECONSIDER at some future point.
-
- protected void finalize() throws Throwable
- {
- super.finalize();
- if(nodeListeners!=null)
- for(int i=nodeListeners.size()-1;i>=0;--i) // count-down is OK for deletions!
- {
- LEntry le=(LEntry)(nodeListeners.elementAt(i));
- LCount lc=LCount.lookup(le.type);
- if(le.useCapture)
- --lc.captures;
- else
- --lc.bubbles;
- }
- }
- */
-
- /**
- * Introduced in DOM Level 2. <p>
- * Distribution engine for DOM Level 2 Events.
- * <p>
- * Event propagation runs as follows:
- * <ol>
- * <li>Event is dispatched to a particular target node, which invokes
- * this code. Note that the event's stopPropagation flag is
- * cleared when dispatch begins; thereafter, if it has
- * been set before processing of a node commences, we instead
- * immediately advance to the DEFAULT phase.
- * <li>The node's ancestors are established as destinations for events.
- * For capture and bubble purposes, node ancestry is determined at
- * the time dispatch starts. If an event handler alters the document
- * tree, that does not change which nodes will be informed of the event.
- * <li>CAPTURING_PHASE: Ancestors are scanned, root to target, for
- * Capturing listeners. If found, they are invoked (see below).
- * <li>AT_TARGET:
- * Event is dispatched to NON-CAPTURING listeners on the
- * target node. Note that capturing listeners on this node are _not_
- * invoked.
- * <li>BUBBLING_PHASE: Ancestors are scanned, target to root, for
- * non-capturing listeners.
- * <li>Default processing: Some DOMs have default behaviors bound to specific
- * nodes. If this DOM does, and if the event's preventDefault flag has
- * not been set, we now return to the target node and process its
- * default handler for this event, if any.
- * </ol>
- * <p>
- * Note that (de)registration of handlers during
- * processing of an event does not take effect during
- * this phase of this event; they will not be called until
- * the next time this node is visited by dispatchEvent.
- * <p>
- * If an event handler itself causes events to be dispatched, they are
- * processed synchronously, before processing resumes
- * on the event which triggered them. Please be aware that this may
- * result in events arriving at listeners "out of order" relative
- * to the actual sequence of requests.
- * <p>
- * Note that our implementation resets the event's stop/prevent flags
- * when dispatch begins.
- * I believe the DOM's intent is that event objects be redispatchable,
- * though it isn't stated in those terms.
- * @param event the event object to be dispatched to
- * registered EventListeners
- * @return true if the event's <code>preventDefault()</code>
- * method was invoked by an EventListener; otherwise false.
- */
- public boolean dispatchEvent(Event event)
- {
- if(event==null) return false;
-
- // Can't use anyone else's implementation, since there's no public
- // API for setting the event's processing-state fields.
- EventImpl evt=(EventImpl)event;
-
- // VALIDATE -- must have been initialized at least once, must have
- // a non-null non-blank name.
- if(!evt.initialized || evt.type==null || evt.type.equals(""))
- throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
- "DOM010 Unspecified event type");
-
- // If nobody is listening for this event, discard immediately
- LCount lc=LCount.lookup(evt.getType());
- if(lc.captures+lc.bubbles+lc.defaults==0)
- return evt.preventDefault;
-
- // INITIALIZE THE EVENT'S DISPATCH STATUS
- // (Note that Event objects are reusable in our implementation;
- // that doesn't seem to be explicitly guaranteed in the DOM, but
- // I believe it is the intent.)
- evt.target=this;
- evt.stopPropagation=false;
- evt.preventDefault=false;
-
- // Capture pre-event parentage chain, not including target;
- // use pre-event-dispatch ancestors even if event handlers mutate
- // document and change the target's context.
- // Note that this is parents ONLY; events do not
- // cross the Attr/Element "blood/brain barrier".
- // DOMAttrModified. which looks like an exception,
- // is issued to the Element rather than the Attr
- // and causes a _second_ DOMSubtreeModified in the Element's
- // tree.
- Vector pv=new Vector(10,10);
- Node p=this,n=p.getParentNode();
- while(n!=null)
- {
- pv.addElement(n);
- p=n;
- n=n.getParentNode();
- }
-
- //CAPTURING_PHASE:
- if(lc.captures>0)
- {
- evt.eventPhase=Event.CAPTURING_PHASE;
- //Ancestors are scanned, root to target, for
- //Capturing listeners.
- for(int j=pv.size()-1;j>=0;--j)
- {
- if(evt.stopPropagation)
- break; // Someone set the flag. Phase ends.
-
- // Handle all capturing listeners on this node
- NodeImpl nn=(NodeImpl)pv.elementAt(j);
- evt.currentTarget=nn;
- Vector nodeListeners = ownerDocument().getEventListeners(nn);
- if(nodeListeners!=null)
- {
- Vector nl=(Vector)(nodeListeners.clone());
- for(int i=nl.size()-1;i>=0;--i) // count-down more efficient
- {
- LEntry le=(LEntry)(nl.elementAt(i));
- if(le.useCapture && le.type.equals(evt.type))
- try
- {
- le.listener.handleEvent(evt);
- }
- catch(Exception e)
- {
- // All exceptions are ignored.
- }
- }
- }
- }
- }
-
- //Both AT_TARGET and BUBBLE use non-capturing listeners.
- if(lc.bubbles>0)
- {
- //AT_TARGET PHASE: Event is dispatched to NON-CAPTURING listeners
- //on the target node. Note that capturing listeners on the target node
- //are _not_ invoked, even during the capture phase.
- evt.eventPhase=Event.AT_TARGET;
- evt.currentTarget=this;
- Vector nodeListeners = ownerDocument().getEventListeners(this);
- if(!evt.stopPropagation && nodeListeners!=null)
- {
- Vector nl=(Vector)nodeListeners.clone();
- for(int i=nl.size()-1;i>=0;--i) // count-down is more efficient
- {
- LEntry le=(LEntry)nl.elementAt(i);
- if(le!=null && !le.useCapture && le.type.equals(evt.type))
- try
- {
- le.listener.handleEvent(evt);
- }
- catch(Exception e)
- {
- // All exceptions are ignored.
- }
- }
- }
- //BUBBLING_PHASE: Ancestors are scanned, target to root, for
- //non-capturing listeners. If the event's preventBubbling flag has
- //been set before processing of a node commences, we instead
- //immediately advance to the default phase.
- //Note that not all events bubble.
- if(evt.bubbles)
- {
- evt.eventPhase=Event.BUBBLING_PHASE;
- for(int j=0;j<pv.size();++j)
- {
- if(evt.stopPropagation)
- break; // Someone set the flag. Phase ends.
-
- // Handle all bubbling listeners on this node
- NodeImpl nn=(NodeImpl)pv.elementAt(j);
- evt.currentTarget=nn;
- nodeListeners = ownerDocument().getEventListeners(nn);
- if(nodeListeners!=null)
- {
- Vector nl=(Vector)(nodeListeners.clone());
- for(int i=nl.size()-1;i>=0;--i) // count-down more efficient
- {
- LEntry le=(LEntry)(nl.elementAt(i));
- if(!le.useCapture && le.type.equals(evt.type))
- try
- {
- le.listener.handleEvent(evt);
- }
- catch(Exception e)
- {
- // All exceptions are ignored.
- }
- }
- }
- }
- }
- }
-
- //DEFAULT PHASE: Some DOMs have default behaviors bound to specific
- //nodes. If this DOM does, and if the event's preventDefault flag has
- //not been set, we now return to the target node and process its
- //default handler for this event, if any.
- // No specific phase value defined, since this is DOM-internal
- if(lc.defaults>0 && (!evt.cancelable || !evt.preventDefault))
- {
- // evt.eventPhase=Event.DEFAULT_PHASE;
- // evt.currentTarget=this;
- // DO_DEFAULT_OPERATION
- }
- return evt.preventDefault;
- } // dispatchEvent(Event) :boolean
-
+ public void addEventListener(String type, EventListener listener,
+ boolean useCapture) {
+ // simply forward to Document
+ ownerDocument().addEventListener(this, type, listener, useCapture);
+ }
- /** NON-DOM INTERNAL: DOMNodeInsertedIntoDocument and ...RemovedFrom...
- * are dispatched to an entire subtree. This is the distribution code
- * therefor. They DO NOT bubble, thanks be, but may be captured.
- * <p>
- * ***** At the moment I'm being sloppy and using the normal
- * capture dispatcher on every node. This could be optimized hugely
- * by writing a capture engine that tracks our position in the tree to
- * update the capture chain without repeated chases up to root.
- * @param n node which was directly inserted or removed
- * @param e event to be sent to that node and its subtree
- */
- void dispatchEventToSubtree(Node n,Event e)
- {
- if(MUTATIONEVENTS && ownerDocument().mutationEvents)
- {
- Vector nodeListeners = ownerDocument().getEventListeners(this);
- if(nodeListeners==null || n==null)
- return;
-
- // ***** Recursive implementation. This is excessively expensive,
- // and should be replaced in conjunction with optimization
- // mentioned above.
- ((NodeImpl)n).dispatchEvent(e);
- if(n.getNodeType()==Node.ELEMENT_NODE)
- {
- NamedNodeMap a=n.getAttributes();
- for(int i=a.getLength()-1;i>=0;--i)
- dispatchEventToSubtree(a.item(i),e);
- }
- dispatchEventToSubtree(n.getFirstChild(),e);
- dispatchEventToSubtree(n.getNextSibling(),e);
- }
- } // dispatchEventToSubtree(Node,Event) :void
-
- /** NON-DOM INTERNAL: Return object for getEnclosingAttr. Carries
- * (two values, the Attr node affected (if any) and its previous
- * string value. Simple struct, no methods.
- */
- class EnclosingAttr
- {
- AttrImpl node;
- String oldvalue;
- } //EnclosingAttr
-
- /** NON-DOM INTERNAL: Pre-mutation context check, in
- * preparation for later generating DOMAttrModified events.
- * Determines whether this node is within an Attr
- * @return either a description of that Attr, or Null
- * if none such.
- */
- EnclosingAttr getEnclosingAttr()
- {
- if(MUTATIONEVENTS && ownerDocument().mutationEvents)
- {
- NodeImpl eventAncestor=this;
- while(true)
- {
- if(eventAncestor==null)
- return null;
- int type=eventAncestor.getNodeType();
- if(type==Node.ATTRIBUTE_NODE)
- {
- EnclosingAttr retval=new EnclosingAttr();
- retval.node=(AttrImpl)eventAncestor;
- retval.oldvalue=retval.node.getNodeValue();
- return retval;
- }
- else if(type==Node.ENTITY_REFERENCE_NODE)
- eventAncestor=eventAncestor.parentNode();
- else
- return null;
- // Any other parent means we're not in an Attr
- }
- }
- return null; // Safety net, should never be reached
- } // getEnclosingAttr() :EnclosingAttr
-
-
- /** NON-DOM INTERNAL: Convenience wrapper for calling
- * dispatchAggregateEvents when the context was established
- * by <code>getEnclosingAttr</code>.
- * @param ea description of Attr affected by current operation
- */
- void dispatchAggregateEvents(EnclosingAttr ea)
- {
- if(ea!=null)
- dispatchAggregateEvents(ea.node, ea.oldvalue,
- MutationEvent.MODIFICATION);
- else
- dispatchAggregateEvents(null,null,(short)0);
-
- } // dispatchAggregateEvents(EnclosingAttr) :void
-
- /** NON-DOM INTERNAL: Generate the "aggregated" post-mutation events
- * DOMAttrModified and DOMSubtreeModified.
- * Both of these should be issued only once for each user-requested
- * mutation operation, even if that involves multiple changes to
- * the DOM.
- * For example, if a DOM operation makes multiple changes to a single
- * Attr before returning, it would be nice to generate only one
- * DOMAttrModified, and multiple changes over larger scope but within
- * a recognizable single subtree might want to generate only one
- * DOMSubtreeModified, sent to their lowest common ancestor.
- * <p>
- * To manage this, use the "internal" versions of insert and remove
- * with MUTATION_LOCAL, then make an explicit call to this routine
- * at the higher level. Some examples now exist in our code.
- *
- * @param enclosingAttr The Attr node (if any) whose value has
- * been changed as a result of the DOM operation. Null if none such.
- * @param oldValue The String value previously held by the
- * enclosingAttr. Ignored if none such.
- * @param change Type of modification to the attr. See
- * MutationEvent.attrChange
- */
- void dispatchAggregateEvents(AttrImpl enclosingAttr,
- String oldvalue, short change)
- {
- if(MUTATIONEVENTS && ownerDocument().mutationEvents) {
- // We have to send DOMAttrModified.
- NodeImpl owner = null;
- if (enclosingAttr != null) {
- LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- owner=((NodeImpl)(enclosingAttr.getOwnerElement()));
- if(lc.captures+lc.bubbles+lc.defaults>0) {
- if(owner!=null) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(
- MutationEventImpl.DOM_ATTR_MODIFIED,
- true, false, enclosingAttr,
- oldvalue,
- enclosingAttr.getNodeValue(),
- enclosingAttr.getNodeName(),
- change);
- owner.dispatchEvent(me);
- }
- }
- }
-
- // DOMSubtreeModified gets sent to the lowest common root of a
- // set of changes.
- // "This event is dispatched after all other events caused by the
- // mutation have been fired."
- LCount lc=LCount.lookup(MutationEventImpl.DOM_SUBTREE_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0) {
- MutationEvent me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_SUBTREE_MODIFIED,
- true,false,null,null,null,null,(short)0);
-
- // If we're within an Attr, DStM gets sent to the Attr
- // and to its owningElement. Otherwise we dispatch it
- // locally.
- if(enclosingAttr!=null) {
- enclosingAttr.dispatchEvent(me);
- if(owner!=null)
- owner.dispatchEvent(me);
- }
- else
- dispatchEvent(me);
- }
- }
- } //dispatchAggregateEvents(AttrImpl,String) :void
+ public void removeEventListener(String type, EventListener listener,
+ boolean useCapture) {
+ // simply forward to Document
+ ownerDocument().removeEventListener(this, type, listener, useCapture);
+ }
+ public boolean dispatchEvent(Event event) {
+ // simply forward to Document
+ return ownerDocument().dispatchEvent(this, event);
+ }
//
// Public methods
@@ -1363,14 +851,6 @@
final void isIgnorableWhitespace(boolean value) {
flags = (short) (value ? flags | IGNORABLEWS : flags & ~IGNORABLEWS);
- }
-
- final boolean setValueCalled() {
- return (flags & SETVALUE) != 0;
- }
-
- final void setValueCalled(boolean value) {
- flags = (short) (value ? flags | SETVALUE : flags & ~SETVALUE);
}
final boolean hasStringValue() {
1.10 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/NotationImpl.java
Index: NotationImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/NotationImpl.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- NotationImpl.java 2001/07/24 00:42:26 1.9
+++ NotationImpl.java 2001/08/10 01:18:16 1.10
@@ -111,7 +111,7 @@
//
/** Factory constructor. */
- public NotationImpl(DocumentImpl ownerDoc, String name) {
+ public NotationImpl(CoreDocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
}
1.27 +33 -220 xml-xerces/java/src/org/apache/xerces/dom/ParentNode.java
Index: ParentNode.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ParentNode.java,v
retrieving revision 1.26
retrieving revision 1.27
diff -u -r1.26 -r1.27
--- ParentNode.java 2001/07/24 00:42:26 1.26
+++ ParentNode.java 2001/08/10 01:18:16 1.27
@@ -1,9 +1,9 @@
-/* $Id: ParentNode.java,v 1.26 2001/07/24 00:42:26 lehors Exp $ */
+/* $Id: ParentNode.java,v 1.27 2001/08/10 01:18:16 lehors Exp $ */
/*
* The Apache Software License, Version 1.1
*
*
- * Copyright (c) 1999-2000 The Apache Software Foundation. All rights
+ * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -67,10 +67,8 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.apache.xerces.dom.events.MutationEventImpl;
-
/**
- * ParentNode inherits from ChildImpl and adds the capability of having child
+ * ParentNode inherits from ChildNode and adds the capability of having child
* nodes. Not every node in the DOM can have children, so only nodes that can
* should inherit from this class and pay the price for it.
* <P>
@@ -90,10 +88,13 @@
* called ChildAndParentNode that inherited from ChildNode. But due to the lack
* of multiple inheritance a lot of code had to be duplicated which led to a
* maintenance nightmare. At the same time only a few nodes (Document,
- * DocumentFragment, Entity, and Attribute) cannot be a child so the gain is
+ * DocumentFragment, Entity, and Attribute) cannot be a child so the gain in
* memory wasn't really worth it. The only type for which this would be the
* case is Attribute, but we deal with there in another special way, so this is
* not applicable.
+ * <p>
+ * This class doesn't directly support mutation events, however, it notifies
+ * the document when mutations are performed so that the document class do so.
*
* <p><b>WARNING</b>: Some of the code here is partially duplicated in
* AttrImpl, be careful to keep these two classes in sync!
@@ -109,7 +110,7 @@
static final long serialVersionUID = 2815829867152120872L;
/** Owner document. */
- protected DocumentImpl ownerDocument;
+ protected CoreDocumentImpl ownerDocument;
/** First child. */
protected ChildNode firstChild = null;
@@ -133,7 +134,7 @@
* No public constructor; only subclasses of ParentNode should be
* instantiated, and those normally via a Document's factory methods
*/
- protected ParentNode(DocumentImpl ownerDocument) {
+ protected ParentNode(CoreDocumentImpl ownerDocument) {
super(ownerDocument);
this.ownerDocument = ownerDocument;
}
@@ -204,9 +205,9 @@
/**
* same as above but returns internal type and this one is not overridden
- * by DocumentImpl to return null
+ * by CoreDocumentImpl to return null
*/
- DocumentImpl ownerDocument() {
+ CoreDocumentImpl ownerDocument() {
return ownerDocument;
}
@@ -214,7 +215,7 @@
* NON-DOM
* set the ownerDocument of this node and its children
*/
- void setOwnerDocument(DocumentImpl doc) {
+ void setOwnerDocument(CoreDocumentImpl doc) {
if (needsSyncChildren()) {
synchronizeChildren();
}
@@ -322,7 +323,7 @@
public Node insertBefore(Node newChild, Node refChild)
throws DOMException {
// Tail-call; optimizer should be able to do good things with.
- return internalInsertBefore(newChild,refChild,MUTATION_ALL);
+ return internalInsertBefore(newChild, refChild, false);
} // insertBefore(Node,Node):Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
@@ -330,7 +331,7 @@
* insertBefore operation allows us to do so. It is not intended
* for use by application programs.
*/
- Node internalInsertBefore(Node newChild, Node refChild,int mutationMask)
+ Node internalInsertBefore(Node newChild, Node refChild, boolean replace)
throws DOMException {
boolean errorChecking = ownerDocument.errorChecking;
@@ -417,18 +418,8 @@
}
}
- EnclosingAttr enclosingAttr=null;
- if (MUTATIONEVENTS && ownerDocument.mutationEvents
- && (mutationMask&MUTATION_AGGREGATE)!=0) {
- // MUTATION PREPROCESSING
- // No direct pre-events, but if we're within the scope
- // of an Attr and DOMAttrModified was requested,
- // we need to preserve its previous value.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- enclosingAttr=getEnclosingAttr();
- }
- }
+ // notify document
+ ownerDocument.insertingNode(this, replace);
// Convert to internal type, to avoid repeated casting
ChildNode newInternal = (ChildNode)newChild;
@@ -499,67 +490,15 @@
fCachedChildIndex = -1;
}
}
-
- if (MUTATIONEVENTS && ownerDocument.mutationEvents) {
- // MUTATION POST-EVENTS:
- // "Local" events (non-aggregated)
- if ((mutationMask&MUTATION_LOCAL) != 0) {
- // New child is told it was inserted, and where
- LCount lc = LCount.lookup(MutationEventImpl.DOM_NODE_INSERTED);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_NODE_INSERTED,
- true,false,this,null,
- null,null,(short)0);
- newInternal.dispatchEvent(me);
- }
- // If within the Document, tell the subtree it's been added
- // to the Doc.
- lc=LCount.lookup(
- MutationEventImpl.DOM_NODE_INSERTED_INTO_DOCUMENT);
- if (lc.captures+lc.bubbles+lc.defaults>0) {
- NodeImpl eventAncestor=this;
- if (enclosingAttr!=null)
- eventAncestor=
- (NodeImpl)(enclosingAttr.node.getOwnerElement());
- if (eventAncestor!=null) { // Might have been orphan Attr
- NodeImpl p=eventAncestor;
- while (p!=null) {
- eventAncestor=p; // Last non-null ancestor
- // In this context, ancestry includes
- // walking back from Attr to Element
- if(p.getNodeType()==ATTRIBUTE_NODE) {
- p=(ElementImpl)((AttrImpl)p).getOwnerElement();
- }
- else {
- p=p.parentNode();
- }
- }
- if(eventAncestor.getNodeType()==Node.DOCUMENT_NODE) {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl
- .DOM_NODE_INSERTED_INTO_DOCUMENT,
- false,false,null,null,
- null,null,(short)0);
- dispatchEventToSubtree(newInternal,me);
- }
- }
- }
- }
-
- // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified
- // (Common to most kinds of mutation)
- if ((mutationMask&MUTATION_AGGREGATE) != 0) {
- dispatchAggregateEvents(enclosingAttr);
- }
- }
+ // notify document
+ ownerDocument.insertedNode(this, newInternal, replace);
checkNormalizationAfterInsert(newInternal);
return newChild;
- } // internalInsertBefore(Node,Node,int):Node
+ } // internalInsertBefore(Node,Node,boolean):Node
/**
* Remove a child from this Node. The removed child's subtree
@@ -576,7 +515,7 @@
public Node removeChild(Node oldChild)
throws DOMException {
// Tail-call, should be optimizable
- return internalRemoveChild(oldChild,MUTATION_ALL);
+ return internalRemoveChild(oldChild, false);
} // removeChild(Node) :Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
@@ -584,10 +523,10 @@
* removeChild operation allows us to do so. It is not intended
* for use by application programs.
*/
- Node internalRemoveChild(Node oldChild,int mutationMask)
+ Node internalRemoveChild(Node oldChild, boolean replace)
throws DOMException {
- DocumentImpl ownerDocument = ownerDocument();
+ CoreDocumentImpl ownerDocument = ownerDocument();
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
throw new DOMException(
@@ -600,68 +539,10 @@
}
}
- // notify document
- ownerDocument.removedChildNode(oldChild);
-
ChildNode oldInternal = (ChildNode) oldChild;
- EnclosingAttr enclosingAttr=null;
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // If we're within the scope of an Attr and DOMAttrModified
- // was requested, we need to preserve its previous value for
- // that event.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttr=getEnclosingAttr();
- }
-
- if( (mutationMask&MUTATION_LOCAL) != 0)
- {
- // Child is told that it is about to be removed
- lc=LCount.lookup(MutationEventImpl.DOM_NODE_REMOVED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl.DOM_NODE_REMOVED,
- true,false,this,null,
- null,null,(short)0);
- oldInternal.dispatchEvent(me);
- }
-
- // If within Document, child's subtree is informed that it's
- // losing that status
- lc=LCount.lookup(
- MutationEventImpl.DOM_NODE_REMOVED_FROM_DOCUMENT);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- NodeImpl eventAncestor=this;
- if(enclosingAttr!=null)
- eventAncestor=
- (NodeImpl) enclosingAttr.node.getOwnerElement();
- if(eventAncestor!=null) // Might have been orphan Attr
- {
- for(NodeImpl p=eventAncestor.parentNode();
- p!=null;
- p=p.parentNode())
- {
- eventAncestor=p; // Last non-null ancestor
- }
- if(eventAncestor.getNodeType()==Node.DOCUMENT_NODE)
- {
- MutationEventImpl me= new MutationEventImpl();
- me.initMutationEvent(MutationEventImpl
- .DOM_NODE_REMOVED_FROM_DOCUMENT,
- false,false,
- null,null,null,null,(short)0);
- dispatchEventToSubtree(oldInternal,me);
- }
- }
- }
- }
- } // End mutation preprocessing
+ // notify document
+ ownerDocument.removingNode(this, oldInternal, replace);
// update cached length if we have any
if (fCachedLength != -1) {
@@ -713,20 +594,14 @@
changed();
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION POST-EVENTS:
- // Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
- // if required. (Common to most kinds of mutation)
- if( (mutationMask&MUTATION_AGGREGATE) != 0)
- dispatchAggregateEvents(enclosingAttr);
- } // End mutation postprocessing
+ // notify document
+ ownerDocument.removedNode(this, replace);
checkNormalizationAfterRemove(oldPreviousSibling);
return oldInternal;
- } // internalRemoveChild(Node,int):Node
+ } // internalRemoveChild(Node,boolean):Node
/**
* Make newChild occupy the location that oldChild used to
@@ -757,29 +632,16 @@
// this as either desirable or undesirable, but hints that
// aggregations should be issued only once per user request.
- EnclosingAttr enclosingAttr=null;
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- // MUTATION PREPROCESSING AND PRE-EVENTS:
- // If we're within the scope of an Attr and DOMAttrModified
- // was requested, we need to preserve its previous value for
- // that event.
- LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
- if(lc.captures+lc.bubbles+lc.defaults>0)
- {
- enclosingAttr=getEnclosingAttr();
- }
- } // End mutation preprocessing
+ // notify document
+ ownerDocument.replacingNode(this);
- internalInsertBefore(newChild, oldChild,MUTATION_LOCAL);
+ internalInsertBefore(newChild, oldChild, true);
if (newChild != oldChild) {
- internalRemoveChild(oldChild,MUTATION_LOCAL);
+ internalRemoveChild(oldChild, true);
}
- if(MUTATIONEVENTS && ownerDocument.mutationEvents)
- {
- dispatchAggregateEvents(enclosingAttr);
- }
+ // notify document
+ ownerDocument.replacedNode(this);
return oldChild;
}
@@ -968,55 +830,6 @@
// By default just change the flag to avoid calling this method again
needsSyncChildren(false);
}
-
- /**
- * Synchronizes the node's children with the internal structure.
- * Fluffing the children at once solves a lot of work to keep
- * the two structures in sync. The problem gets worse when
- * editing the tree -- this makes it a lot easier.
- * Even though this is only used in deferred classes this method is
- * put here so that it can be shared by all deferred classes.
- */
- protected final void synchronizeChildren(int nodeIndex) {
-
- // we don't want to generate any event for this so turn them off
- boolean orig = ownerDocument.mutationEvents;
- ownerDocument.mutationEvents = false;
-
- // no need to sync in the future
- needsSyncChildren(false);
-
- // create children and link them as siblings
- DeferredDocumentImpl ownerDocument =
- (DeferredDocumentImpl)this.ownerDocument;
- ChildNode first = null;
- ChildNode last = null;
- for (int index = ownerDocument.getLastChild(nodeIndex);
- index != -1;
- index = ownerDocument.getPrevSibling(index)) {
-
- ChildNode node = (ChildNode)ownerDocument.getNodeObject(index);
- if (last == null) {
- last = node;
- }
- else {
- first.previousSibling = node;
- }
- node.ownerNode = this;
- node.isOwned(true);
- node.nextSibling = first;
- first = node;
- }
- if (last != null) {
- firstChild = first;
- first.isFirstChild(true);
- lastChild(last);
- }
-
- // set mutation events flag back to its original value
- ownerDocument.mutationEvents = orig;
-
- } // synchronizeChildren()
/**
* Checks the normalized state of this node after inserting a child.
1.8 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/ProcessingInstructionImpl.java
Index: ProcessingInstructionImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/ProcessingInstructionImpl.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- ProcessingInstructionImpl.java 2001/07/24 00:42:26 1.7
+++ ProcessingInstructionImpl.java 2001/08/10 01:18:16 1.8
@@ -92,7 +92,7 @@
//
/** Factory constructor. */
- public ProcessingInstructionImpl(DocumentImpl ownerDoc,
+ public ProcessingInstructionImpl(CoreDocumentImpl ownerDoc,
String target, String data) {
super(ownerDoc, data);
this.target = target;
1.11 +1 -1 xml-xerces/java/src/org/apache/xerces/dom/TextImpl.java
Index: TextImpl.java
===================================================================
RCS file: /home/cvs/xml-xerces/java/src/org/apache/xerces/dom/TextImpl.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- TextImpl.java 2001/07/24 00:42:26 1.10
+++ TextImpl.java 2001/08/10 01:18:16 1.11
@@ -94,7 +94,7 @@
//
/** Factory constructor. */
- public TextImpl(DocumentImpl ownerDoc, String data) {
+ public TextImpl(CoreDocumentImpl ownerDoc, String data) {
super(ownerDoc, data);
}
1.1 xml-xerces/java/src/org/apache/xerces/dom/CoreDOMImplementationImpl.java
Index: CoreDOMImplementationImpl.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
/**
* The DOMImplementation class is description of a particular
* implementation of the Document Object Model. As such its data is
* static, shared by all instances of this implementation.
* <P>
* The DOM API requires that it be a real object rather than static
* methods. However, there's nothing that says it can't be a singleton,
* so that's how I've implemented it.
* <P>
* This particular class, along with CoreDocumentImpl, only supports the DOM
* Core. Optional modules are supported by the more complete DOMImplementation
* class along with DocumentImpl.
*
* @version
* @since PR-DOM-Level-1-19980818.
*/
public class CoreDOMImplementationImpl
implements DOMImplementation {
//
// Data
//
// static
/** Dom implementation singleton. */
static CoreDOMImplementationImpl singleton =
new CoreDOMImplementationImpl();
//
// DOMImplementation methods
//
/**
* Test if the DOM implementation supports a specific "feature" --
* currently meaning language and level thereof.
*
* @param feature The package name of the feature to test.
* In Level 1, supported values are "HTML" and "XML" (case-insensitive).
* At this writing, org.apache.xerces.dom supports only XML.
*
* @param version The version number of the feature being tested.
* This is interpreted as "Version of the DOM API supported for the
* specified Feature", and in Level 1 should be "1.0"
*
* @returns true iff this implementation is compatable with the
* specified feature and version.
*/
public boolean hasFeature(String feature, String version) {
// Currently, we support only XML Level 1 version 1.0
boolean anyVersion = version == null || version.length() == 0;
return
(feature.equalsIgnoreCase("Core")
&& (anyVersion
|| version.equals("1.0")
|| version.equals("2.0")))
|| (feature.equalsIgnoreCase("XML")
&& (anyVersion
|| version.equals("1.0")
|| version.equals("2.0")))
;
} // hasFeature(String,String):boolean
//
// Public methods
//
/** NON-DOM: Obtain and return the single shared object */
public static DOMImplementation getDOMImplementation() {
return singleton;
}
/**
* Introduced in DOM Level 2. <p>
*
* Creates an empty DocumentType node.
*
* @param qualifiedName The qualified name of the document type to be created.
* @param publicID The document type public identifier.
* @param systemID The document type system identifier.
* @since WD-DOM-Level-2-19990923
*/
public DocumentType createDocumentType(String qualifiedName,
String publicID,
String systemID)
{
if (!CoreDocumentImpl.isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
int index = qualifiedName.indexOf(':');
if (index == 0 || index == qualifiedName.length() - 1) {
throw new DOMException(DOMException.NAMESPACE_ERR,
"DOM003 Namespace error");
}
return new DocumentTypeImpl(null, qualifiedName, publicID, systemID);
}
/**
* Introduced in DOM Level 2. <p>
*
* Creates an XML Document object of the specified type with its document
* element.
*
* @param namespaceURI The namespace URI of the document
* element to create, or null.
* @param qualifiedName The qualified name of the document
* element to create.
* @param doctype The type of document to be created or null.<p>
*
* When doctype is not null, its
* Node.ownerDocument attribute is set to
* the document being created.
* @return Document A new Document object.
* @throws DOMException WRONG_DOCUMENT_ERR: Raised if doctype has
* already been used with a different document.
* @since WD-DOM-Level-2-19990923
*/
public Document createDocument(String namespaceURI,
String qualifiedName,
DocumentType doctype)
throws DOMException
{
if (doctype != null && doctype.getOwnerDocument() != null) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
CoreDocumentImpl doc = new CoreDocumentImpl(doctype);
Element e = doc.createElementNS( namespaceURI, qualifiedName);
doc.appendChild(e);
return doc;
}
} // class DOMImplementationImpl
1.1 xml-xerces/java/src/org/apache/xerces/dom/CoreDocumentImpl.java
Index: CoreDocumentImpl.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import java.util.Enumeration;
import java.util.Hashtable;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Entity;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Notation;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.apache.xerces.utils.XMLCharacterProperties;
/**
* The Document interface represents the entire HTML or XML document.
* Conceptually, it is the root of the document tree, and provides the
* primary access to the document's data.
* <P>
* Since elements, text nodes, comments, processing instructions,
* etc. cannot exist outside the context of a Document, the Document
* interface also contains the factory methods needed to create these
* objects. The Node objects created have a ownerDocument attribute
* which associates them with the Document within whose context they
* were created.
* <p>
* The CoreDocumentImpl class only implements the DOM Core. Additional modules
* are supported by the more complete DocumentImpl subclass.
* <p>
* <b>Note:</b> When any node in the document is serialized, the
* entire document is serialized along with it.
*
* @author Arnaud Le Hors, IBM
* @author Joe Kesselman, IBM
* @author Andy Clark, IBM
* @author Ralf Pfeiffer, IBM
* @version
* @since PR-DOM-Level-1-19980818.
*/
public class CoreDocumentImpl
extends ParentNode implements Document {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = 0;
//
// Data
//
// document information
/** Document type. */
protected DocumentTypeImpl docType;
/** Document element. */
protected ElementImpl docElement;
/**Experimental DOM Level 3 feature: Document encoding */
protected String encoding;
/**Experimental DOM Level 3 feature: Document version */
protected String version;
/**Experimental DOM Level 3 feature: Document standalone */
protected boolean standalone;
/** Identifiers. */
protected Hashtable identifiers;
/** Table for quick check of child insertion. */
protected static int[] kidOK;
/**
* Number of alterations made to this document since its creation.
* Serves as a "dirty bit" so that live objects such as NodeList can
* recognize when an alteration has been made and discard its cached
* state information.
* <p>
* Any method that alters the tree structure MUST cause or be
* accompanied by a call to changed(), to inform it that any outstanding
* NodeLists may have to be updated.
* <p>
* (Required because NodeList is simultaneously "live" and integer-
* indexed -- a bad decision in the DOM's design.)
* <p>
* Note that changes which do not affect the tree's structure -- changing
* the node's name, for example -- do _not_ have to call changed().
* <p>
* Alternative implementation would be to use a cryptographic
* Digest value rather than a count. This would have the advantage that
* "harmless" changes (those producing equal() trees) would not force
* NodeList to resynchronize. Disadvantage is that it's slightly more prone
* to "false negatives", though that's the difference between "wildly
* unlikely" and "absurdly unlikely". IF we start maintaining digests,
* we should consider taking advantage of them.
*
* Note: This used to be done a node basis, so that we knew what
* subtree changed. But since only DeepNodeList really use this today,
* the gain appears to be really small compared to the cost of having
* an int on every (parent) node plus having to walk up the tree all the
* way to the root to mark the branch as changed everytime a node is
* changed.
* So we now have a single counter global to the document. It means that
* some objects may flush their cache more often than necessary, but this
* makes nodes smaller and only the document needs to be marked as changed.
*/
protected int changes = 0;
// experimental
/** Allow grammar access. */
protected boolean allowGrammarAccess;
/** Bypass error checking. */
protected boolean errorChecking = true;
//
// Static initialization
//
static {
kidOK = new int[13];
kidOK[DOCUMENT_NODE] =
1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
1 << COMMENT_NODE | 1 << DOCUMENT_TYPE_NODE;
kidOK[DOCUMENT_FRAGMENT_NODE] =
kidOK[ENTITY_NODE] =
kidOK[ENTITY_REFERENCE_NODE] =
kidOK[ELEMENT_NODE] =
1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
1 << COMMENT_NODE | 1 << TEXT_NODE |
1 << CDATA_SECTION_NODE | 1 << ENTITY_REFERENCE_NODE ;
kidOK[ATTRIBUTE_NODE] =
1 << TEXT_NODE | 1 << ENTITY_REFERENCE_NODE;
kidOK[DOCUMENT_TYPE_NODE] =
kidOK[PROCESSING_INSTRUCTION_NODE] =
kidOK[COMMENT_NODE] =
kidOK[TEXT_NODE] =
kidOK[CDATA_SECTION_NODE] =
kidOK[NOTATION_NODE] =
0;
} // static
//
// Constructors
//
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public CoreDocumentImpl() {
this(false);
// make sure the XMLCharacterProperties class is initilialized
XMLCharacterProperties.initCharFlags();
}
/** Constructor. */
public CoreDocumentImpl(boolean grammarAccess) {
super(null);
ownerDocument = this;
allowGrammarAccess = grammarAccess;
// make sure the XMLCharacterProperties class is initilialized
XMLCharacterProperties.initCharFlags();
}
/**
* For DOM2 support.
* The createDocument factory method is in DOMImplementation.
*/
public CoreDocumentImpl(DocumentType doctype)
{
this(doctype, false);
// make sure the XMLCharacterProperties class is initilialized
XMLCharacterProperties.initCharFlags();
}
/** For DOM2 support. */
public CoreDocumentImpl(DocumentType doctype, boolean grammarAccess) {
this(grammarAccess);
if (doctype != null) {
DocumentTypeImpl doctypeImpl;
try {
doctypeImpl = (DocumentTypeImpl) doctype;
} catch (ClassCastException e) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
doctypeImpl.ownerDocument = this;
appendChild(doctype);
}
// make sure the XMLCharacterProperties class is initilialized
XMLCharacterProperties.initCharFlags();
}
//
// Node methods
//
// even though ownerDocument refers to this in this implementation
// the DOM Level 2 spec says it must be null, so make it appear so
final public Document getOwnerDocument() {
return null;
}
/** Returns the node type. */
public short getNodeType() {
return Node.DOCUMENT_NODE;
}
/** Returns the node name. */
public String getNodeName() {
return "#document";
}
/**
* Deep-clone a document, including fixing ownerDoc for the cloned
* children. Note that this requires bypassing the WRONG_DOCUMENT_ERR
* protection. I've chosen to implement it by calling importNode
* which is DOM Level 2.
*
* @return org.w3c.dom.Node
* @param deep boolean, iff true replicate children
*/
public Node cloneNode(boolean deep) {
CoreDocumentImpl newdoc = new CoreDocumentImpl();
cloneNode(newdoc, deep);
return newdoc;
} // cloneNode(boolean):Node
/**
* internal method to share code with subclass
**/
protected void cloneNode(CoreDocumentImpl newdoc, boolean deep) {
// clone the children by importing them
if (needsSyncChildren()) {
synchronizeChildren();
}
if (deep) {
Hashtable reversedIdentifiers = null;
if (identifiers != null) {
// Build a reverse mapping from element to identifier.
reversedIdentifiers = new Hashtable();
Enumeration elementIds = identifiers.keys();
while (elementIds.hasMoreElements()) {
Object elementId = elementIds.nextElement();
reversedIdentifiers.put(identifiers.get(elementId),
elementId);
}
}
// Copy children into new document.
for (ChildNode kid = firstChild; kid != null;
kid = kid.nextSibling) {
newdoc.appendChild(newdoc.importNode(kid, true,
reversedIdentifiers));
}
}
// experimental
newdoc.allowGrammarAccess = allowGrammarAccess;
newdoc.errorChecking = errorChecking;
} // cloneNode(CoreDocumentImpl,boolean):void
/**
* Since a Document may contain at most one top-level Element child,
* and at most one DocumentType declaraction, we need to subclass our
* add-children methods to implement this constraint.
* Since appendChild() is implemented as insertBefore(,null),
* altering the latter fixes both.
* <p>
* While I'm doing so, I've taken advantage of the opportunity to
* cache documentElement and docType so we don't have to
* search for them.
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node insertBefore(Node newChild, Node refChild)
throws DOMException {
// Only one such child permitted
int type = newChild.getNodeType();
if (errorChecking) {
if((type == Node.ELEMENT_NODE && docElement != null) ||
(type == Node.DOCUMENT_TYPE_NODE && docType != null)) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"DOM006 Hierarchy request error");
}
}
super.insertBefore(newChild,refChild);
// If insert succeeded, cache the kid appropriately
if (type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)newChild;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType=(DocumentTypeImpl)newChild;
}
return newChild;
} // insertBefore(Node,Node):Node
/**
* Since insertBefore caches the docElement (and, currently, docType),
* removeChild has to know how to undo the cache
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node removeChild(Node oldChild)
throws DOMException {
super.removeChild(oldChild);
// If remove succeeded, un-cache the kid appropriately
int type = oldChild.getNodeType();
if(type == Node.ELEMENT_NODE) {
docElement = null;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType=null;
}
return oldChild;
} // removeChild(Node):Node
/**
* Since we cache the docElement (and, currently, docType),
* replaceChild has to update the cache
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node replaceChild(Node newChild, Node oldChild)
throws DOMException {
super.replaceChild(newChild, oldChild);
int type = oldChild.getNodeType();
if(type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)newChild;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = (DocumentTypeImpl)newChild;
}
return oldChild;
} // replaceChild(Node,Node):Node
//
// Document methods
//
// factory methods
/**
* Factory method; creates an Attribute having this Document as its
* OwnerDoc.
*
* @param name The name of the attribute. Note that the attribute's value
* is _not_ established at the factory; remember to set it!
*
* @throws DOMException(INVALID_NAME_ERR) if the attribute name is not
* acceptable.
*/
public Attr createAttribute(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new AttrImpl(this, name);
} // createAttribute(String):Attr
/**
* Factory method; creates a CDATASection having this Document as
* its OwnerDoc.
*
* @param data The initial contents of the CDATA
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
* not yet implemented.)
*/
public CDATASection createCDATASection(String data)
throws DOMException {
return new CDATASectionImpl(this, data);
}
/**
* Factory method; creates a Comment having this Document as its
* OwnerDoc.
*
* @param data The initial contents of the Comment. */
public Comment createComment(String data) {
return new CommentImpl(this, data);
}
/**
* Factory method; creates a DocumentFragment having this Document
* as its OwnerDoc.
*/
public DocumentFragment createDocumentFragment() {
return new DocumentFragmentImpl(this);
}
/**
* Factory method; creates an Element having this Document
* as its OwnerDoc.
*
* @param tagName The name of the element type to instantiate. For
* XML, this is case-sensitive. For HTML, the tagName parameter may
* be provided in any case, but it must be mapped to the canonical
* uppercase form by the DOM implementation.
*
* @throws DOMException(INVALID_NAME_ERR) if the tag name is not
* acceptable.
*/
public Element createElement(String tagName)
throws DOMException {
if (errorChecking && !isXMLName(tagName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementImpl(this, tagName);
} // createElement(String):Element
/**
* Factory method; creates an EntityReference having this Document
* as its OwnerDoc.
*
* @param name The name of the Entity we wish to refer to
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* nonstandard entities are not permitted. (HTML not yet
* implemented.)
*/
public EntityReference createEntityReference(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new EntityReferenceImpl(this, name);
} // createEntityReference(String):EntityReference
/**
* Factory method; creates a ProcessingInstruction having this Document
* as its OwnerDoc.
*
* @param target The target "processor channel"
* @param data Parameter string to be passed to the target.
*
* @throws DOMException(INVALID_NAME_ERR) if the target name is not
* acceptable.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
* not yet implemented.)
*/
public ProcessingInstruction createProcessingInstruction(String target,
String data)
throws DOMException {
if (errorChecking && !isXMLName(target)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ProcessingInstructionImpl(this, target, data);
} // createProcessingInstruction(String,String):ProcessingInstruction
/**
* Factory method; creates a Text node having this Document as its
* OwnerDoc.
*
* @param data The initial contents of the Text.
*/
public Text createTextNode(String data) {
return new TextImpl(this, data);
}
// other document methods
/**
* For XML, this provides access to the Document Type Definition.
* For HTML documents, and XML documents which don't specify a DTD,
* it will be null.
*/
public DocumentType getDoctype() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return docType;
}
/**
* DOM Level 3 WD - Experimental.
* The encoding of this document (part of XML Declaration)
*/
public String getEncoding() {
return encoding;
}
/**
* DOM Level 3 WD - Experimental.
* The version of this document (part of XML Declaration)
*/
public String getVersion() {
return version;
}
/**
* DOM Level 3 WD - Experimental.
* standalone that specifies whether this document is standalone
* (part of XML Declaration)
*/
public boolean getStandalone() {
return standalone;
}
/**
* Convenience method, allowing direct access to the child node
* which is considered the root of the actual document content. For
* HTML, where it is legal to have more than one Element at the top
* level of the document, we pick the one with the tagName
* "HTML". For XML there should be only one top-level
*
* (HTML not yet supported.)
*/
public Element getDocumentElement() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return docElement;
}
/**
* Return a <em>live</em> collection of all descendent Elements (not just
* immediate children) having the specified tag name.
*
* @param tagname The type of Element we want to gather. "*" will be
* taken as a wildcard, meaning "all elements in the document."
*
* @see DeepNodeListImpl
*/
public NodeList getElementsByTagName(String tagname) {
return new DeepNodeListImpl(this,tagname);
}
/**
* Retrieve information describing the abilities of this particular
* DOM implementation. Intended to support applications that may be
* using DOMs retrieved from several different sources, potentially
* with different underlying representations.
*/
public DOMImplementation getImplementation() {
// Currently implemented as a singleton, since it's hardcoded
// information anyway.
return CoreDOMImplementationImpl.getDOMImplementation();
}
//
// Public methods
//
// properties
/**
* Sets whether the DOM implementation performs error checking
* upon operations. Turning off error checking only affects
* the following DOM checks:
* <ul>
* <li>Checking strings to make sure that all characters are
* legal XML characters
* <li>Hierarchy checking such as allowed children, checks for
* cycles, etc.
* </ul>
* <p>
* Turning off error checking does <em>not</em> turn off the
* following checks:
* <ul>
* <li>Read only checks
* <li>Checks related to DOM events
* </ul>
*/
public void setErrorChecking(boolean check) {
errorChecking = check;
}
/*
* DOM Level 3 WD - Experimental.
*/
public void setStrictErrorChecking(boolean check) {
errorChecking = check;
}
/**
* DOM Level 3 WD - Experimental.
* An attribute specifying, as part of the XML declaration,
* the encoding of this document. This is null when unspecified.
*/
public void setEncoding(String value) {
encoding = value;
}
/**
* DOM Level 3 WD - Experimental.
* version - An attribute specifying, as part of the XML declaration,
* the version number of this document. This is null when unspecified
*/
public void setVersion(String value) {
version = value;
}
/**
* DOM Level 3 WD - Experimental.
* standalone - An attribute specifying, as part of the XML declaration,
* whether this document is standalone
*/
public void setStandalone(boolean value) {
standalone = value;
}
/**
* Returns true if the DOM implementation performs error checking.
*/
public boolean getErrorChecking() {
return errorChecking;
}
/*
* DOM Level 3 WD - Experimental.
*/
public boolean getStrictErrorChecking() {
return errorChecking;
}
/**
* Sets whether the DOM implementation generates mutation events
* upon operations.
*/
void setMutationEvents(boolean set) {
// does nothing by default - overidden in subclass
}
/**
* Returns true if the DOM implementation generates mutation events.
*/
boolean getMutationEvents() {
// does nothing by default - overriden in subclass
return false;
}
// non-DOM factory methods
/**
* NON-DOM
* Factory method; creates a DocumentType having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Entity we wish to provide a value for.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* DTDs are not permitted. (HTML not yet implemented.)
*/
public DocumentType createDocumentType(String qualifiedName,
String publicID,
String systemID)
throws DOMException {
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new DocumentTypeImpl(this, qualifiedName, publicID, systemID);
} // createDocumentType(String):DocumentType
/**
* NON-DOM
* Factory method; creates an Entity having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Entity we wish to provide a value for.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* nonstandard entities are not permitted. (HTML not yet
* implemented.)
*/
public Entity createEntity(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new EntityImpl(this, name);
} // createEntity(String):Entity
/**
* NON-DOM
* Factory method; creates a Notation having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Notation we wish to describe
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* notations are not permitted. (HTML not yet
* implemented.)
*/
public Notation createNotation(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new NotationImpl(this, name);
} // createNotation(String):Notation
/**
* NON-DOM Factory method: creates an element definition. Element
* definitions hold default attribute values.
*/
public ElementDefinitionImpl createElementDefinition(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementDefinitionImpl(this, name);
} // createElementDefinition(String):ElementDefinitionImpl
// other non-DOM methods
/**
* Copies a node from another document to this document. The new nodes are
* created using this document's factory methods and are populated with the
* data from the source's accessor methods defined by the DOM interfaces.
* Its behavior is otherwise similar to that of cloneNode.
* <p>
* According to the DOM specifications, document nodes cannot be imported
* and a NOT_SUPPORTED_ERR exception is thrown if attempted.
*/
public Node importNode(Node source, boolean deep)
throws DOMException {
return importNode(source, deep, null);
} // importNode(Node,boolean):Node
/**
* Overloaded implementation of DOM's importNode method. This method
* provides the core functionality for the public importNode and cloneNode
* methods.
*
* The reversedIdentifiers parameter is provided for cloneNode to
* preserve the document's identifiers. The Hashtable has Elements as the
* keys and their identifiers as the values. When an element is being
* imported, a check is done for an associated identifier. If one exists,
* the identifier is registered with the new, imported element. If
* reversedIdentifiers is null, the parameter is not applied.
*/
private Node importNode(Node source, boolean deep,
Hashtable reversedIdentifiers)
throws DOMException {
Node newnode=null;
// Sigh. This doesn't work; too many nodes have private data that
// would have to be manually tweaked. May be able to add local
// shortcuts to each nodetype. Consider ?????
// if(source instanceof NodeImpl &&
// !(source instanceof DocumentImpl))
// {
// // Can't clone DocumentImpl since it invokes us...
// newnode=(NodeImpl)source.cloneNode(false);
// newnode.ownerDocument=this;
// }
// else
// get source implementation
DOMImplementation domImplementation =
source.getOwnerDocument().getImplementation();
// DOM Level 2.0 implementation?
boolean domLevel20 =
domImplementation.hasFeature("XML", "2.0" );
int type = source.getNodeType();
switch (type) {
case ELEMENT_NODE: {
Element newElement;
// Create element according to namespace support/qualification.
if(domLevel20 == false || source.getLocalName() == null)
newElement = createElement(source.getNodeName());
else
newElement = createElementNS(source.getNamespaceURI(),
source.getNodeName());
// Copy element's attributes, if any.
NamedNodeMap sourceAttrs = source.getAttributes();
if (sourceAttrs != null) {
int length = sourceAttrs.getLength();
for (int index = 0; index < length; index++) {
Attr attr = (Attr)sourceAttrs.item(index);
// Copy the attribute only if it is not a default.
if (attr.getSpecified()) {
Attr newAttr = (Attr)importNode(attr, true,
reversedIdentifiers);
// Attach attribute according to namespace
// support/qualification.
if (domLevel20 == false ||
attr.getLocalName() == null)
newElement.setAttributeNode(newAttr);
else
newElement.setAttributeNodeNS(newAttr);
}
}
}
// Register element identifier.
if (reversedIdentifiers != null) {
// Does element have an associated identifier?
Object elementId = reversedIdentifiers.get(source);
if (elementId != null) {
if (identifiers == null)
identifiers = new Hashtable();
identifiers.put(elementId, newElement);
}
}
newnode = newElement;
break;
}
case ATTRIBUTE_NODE: {
if( domLevel20 == true ){
if (source.getLocalName() == null) {
newnode = createAttribute(source.getNodeName());
} else {
newnode = createAttributeNS(source.getNamespaceURI(),
source.getNodeName());
}
}
else {
newnode = createAttribute(source.getNodeName());
}
// if source is an AttrImpl from this very same implementation
// avoid creating the child nodes if possible
if (source instanceof AttrImpl) {
AttrImpl attr = (AttrImpl) source;
if (attr.hasStringValue()) {
AttrImpl newattr = (AttrImpl) newnode;
newattr.setValue(attr.getValue());
deep = false;
}
else {
deep = true;
}
}
else {
// According to the DOM spec the kids carry the value.
// However, there are non compliant implementations out
// there that fail to do so. To avoid ending up with no
// value at all, in this case we simply copy the text value
// directly.
if (source.getFirstChild() == null) {
newnode.setNodeValue(source.getNodeValue());
deep = false;
} else {
deep = true;
}
}
break;
}
case TEXT_NODE: {
newnode = createTextNode(source.getNodeValue());
break;
}
case CDATA_SECTION_NODE: {
newnode = createCDATASection(source.getNodeValue());
break;
}
case ENTITY_REFERENCE_NODE: {
newnode = createEntityReference(source.getNodeName());
// allow deep import temporarily
((EntityReferenceImpl)newnode).isReadOnly(false);
break;
}
case ENTITY_NODE: {
Entity srcentity = (Entity)source;
EntityImpl newentity =
(EntityImpl)createEntity(source.getNodeName());
newentity.setPublicId(srcentity.getPublicId());
newentity.setSystemId(srcentity.getSystemId());
newentity.setNotationName(srcentity.getNotationName());
// Kids carry additional value
newentity.isReadOnly(false); // allow deep import temporarily
newnode = newentity;
break;
}
case PROCESSING_INSTRUCTION_NODE: {
newnode = createProcessingInstruction(source.getNodeName(),
source.getNodeValue());
break;
}
case COMMENT_NODE: {
newnode = createComment(source.getNodeValue());
break;
}
// REVISIT: The DOM specifications say that DocumentType nodes
// cannot be imported. Is this OK?
case DOCUMENT_TYPE_NODE: {
DocumentType srcdoctype = (DocumentType)source;
DocumentTypeImpl newdoctype = (DocumentTypeImpl)
createDocumentType(srcdoctype.getNodeName(),
srcdoctype.getPublicId(),
srcdoctype.getSystemId());
// Values are on NamedNodeMaps
NamedNodeMap smap = srcdoctype.getEntities();
NamedNodeMap tmap = newdoctype.getEntities();
if(smap != null) {
for(int i = 0; i < smap.getLength(); i++) {
tmap.setNamedItem(importNode(smap.item(i), true,
reversedIdentifiers));
}
}
smap = srcdoctype.getNotations();
tmap = newdoctype.getNotations();
if (smap != null) {
for(int i = 0; i < smap.getLength(); i++) {
tmap.setNamedItem(importNode(smap.item(i), true,
reversedIdentifiers));
}
}
// NOTE: At this time, the DOM definition of DocumentType
// doesn't cover Elements and their Attributes. domimpl's
// extentions in that area will not be preserved, even if
// copying from domimpl to domimpl. We could special-case
// that here. Arguably we should. Consider. ?????
newnode = newdoctype;
break;
}
case DOCUMENT_FRAGMENT_NODE: {
newnode = createDocumentFragment();
// No name, kids carry value
break;
}
case NOTATION_NODE: {
Notation srcnotation = (Notation)source;
NotationImpl newnotation =
(NotationImpl)createNotation(source.getNodeName());
newnotation.setPublicId(srcnotation.getPublicId());
newnotation.setSystemId(srcnotation.getSystemId());
// Kids carry additional value
newnode = newnotation;
// No name, no value
break;
}
case DOCUMENT_NODE : // Can't import document nodes
default: { // Unknown node type
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Node type being imported is not supported");
}
}
// If deep, replicate and attach the kids.
if (deep) {
for (Node srckid = source.getFirstChild();
srckid != null;
srckid = srckid.getNextSibling()) {
newnode.appendChild(importNode(srckid, true,
reversedIdentifiers));
}
}
if (newnode.getNodeType() == Node.ENTITY_REFERENCE_NODE
|| newnode.getNodeType() == Node.ENTITY_NODE) {
((NodeImpl)newnode).setReadOnly(true, true);
}
return newnode;
} // importNode(Node,boolean,Hashtable):Node
/**
* DOM Level 3 WD - Experimental
* Change the node's ownerDocument, and its subtree, to this Document
*
* @param source The node to adopt.
* @see DocumentImpl.importNode
**/
public Node adoptNode(Node source) {
NodeImpl node;
try {
node = (NodeImpl) source;
} catch (ClassCastException e) {
// source node comes from a different DOMImplementation
return null;
}
switch (node.getNodeType()) {
case ATTRIBUTE_NODE: {
AttrImpl attr = (AttrImpl) node;
// remove node from wherever it is
attr.getOwnerElement().removeAttributeNode(attr);
// mark it as specified
attr.isSpecified(true);
// change ownership
attr.setOwnerDocument(this);
break;
}
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE: {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"cannot adopt this type of node.");
}
case ENTITY_REFERENCE_NODE: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// discard its replacement value
Node child;
while ((child = node.getFirstChild()) != null) {
node.removeChild(child);
}
// change ownership
node.setOwnerDocument(this);
// set its new replacement value if any
if (docType == null) {
break;
}
NamedNodeMap entities = docType.getEntities();
Node entityNode = entities.getNamedItem(node.getNodeName());
if (entityNode == null) {
break;
}
EntityImpl entity = (EntityImpl) entityNode;
for (child = entityNode.getFirstChild();
child != null; child = child.getNextSibling()) {
Node childClone = child.cloneNode(true);
node.appendChild(childClone);
}
break;
}
case ELEMENT_NODE: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// change ownership
node.setOwnerDocument(this);
// reconcile default attributes
((ElementImpl)node).reconcileDefaultAttributes();
break;
}
default: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// change ownership
node.setOwnerDocument(this);
}
}
return node;
}
// identifier maintenence
/**
* Introduced in DOM Level 2
* Returns the Element whose ID is given by elementId. If no such element
* exists, returns null. Behavior is not defined if more than one element
* has this ID.
* <p>
* Note: The DOM implementation must have information that says which
* attributes are of type ID. Attributes with the name "ID" are not of type
* ID unless so defined. Implementations that do not know whether
* attributes are of type ID or not are expected to return null.
* @see #getIdentifier
*/
public Element getElementById(String elementId) {
return getIdentifier(elementId);
}
/**
* Registers an identifier name with a specified element node.
* If the identifier is already registered, the new element
* node replaces the previous node. If the specified element
* node is null, removeIdentifier() is called.
*
* @see #getIdentifier
* @see #removeIdentifier
*/
public void putIdentifier(String idName, Element element) {
if (element == null) {
removeIdentifier(idName);
return;
}
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
identifiers = new Hashtable();
}
identifiers.put(idName, element);
} // putIdentifier(String,Element)
/**
* Returns a previously registered element with the specified
* identifier name, or null if no element is registered.
*
* @see #putIdentifier
* @see #removeIdentifier
*/
public Element getIdentifier(String idName) {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
return null;
}
return (Element)identifiers.get(idName);
} // getIdentifier(String):Element
/**
* Removes a previously registered element with the specified
* identifier name.
*
* @see #putIdentifier
* @see #getIdentifier
*/
public void removeIdentifier(String idName) {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
return;
}
identifiers.remove(idName);
} // removeIdentifier(String)
/** Returns an enumeration registered of identifier names. */
public Enumeration getIdentifiers() {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
identifiers = new Hashtable();
}
return identifiers.keys();
} // getIdentifiers():Enumeration
//
// DOM2: Namespace methods
//
/**
* Introduced in DOM Level 2. <p>
* Creates an element of the given qualified name and namespace URI.
* If the given namespaceURI is null or an empty string and the
* qualifiedName has a prefix that is "xml", the created element
* is bound to the predefined namespace
* "http://www.w3.org/XML/1998/namespace" [Namespaces].
* @param namespaceURI The namespace URI of the element to
* create.
* @param qualifiedName The qualified name of the element type to
* instantiate.
* @return Element A new Element object with the following attributes:
* @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
name contains an invalid character.
* @throws DOMException NAMESPACE_ERR: Raised if the qualifiedName has a
* prefix that is "xml" and the namespaceURI is
* neither null nor an empty string nor
* "http://www.w3.org/XML/1998/namespace", or
* if the qualifiedName has a prefix different
* from "xml" and the namespaceURI is null or an
* empty string.
* @since WD-DOM-Level-2-19990923
*/
public Element createElementNS(String namespaceURI, String qualifiedName)
throws DOMException
{
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementNSImpl(this, namespaceURI, qualifiedName);
}
/**
* Introduced in DOM Level 2. <p>
* Creates an attribute of the given qualified name and namespace URI.
* If the given namespaceURI is null or an empty string and the
* qualifiedName has a prefix that is "xml", the created element
* is bound to the predefined namespace
* "http://www.w3.org/XML/1998/namespace" [Namespaces].
*
* @param namespaceURI The namespace URI of the attribute to
* create. When it is null or an empty string,
* this method behaves like createAttribute.
* @param qualifiedName The qualified name of the attribute to
* instantiate.
* @return Attr A new Attr object.
* @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
name contains an invalid character.
* @since WD-DOM-Level-2-19990923
*/
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
throws DOMException
{
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new AttrNSImpl(this, namespaceURI, qualifiedName);
}
/**
* Introduced in DOM Level 2. <p>
* Returns a NodeList of all the Elements with a given local name and
* namespace URI in the order in which they would be encountered in a
* preorder traversal of the Document tree.
* @param namespaceURI The namespace URI of the elements to match
* on. The special value "*" matches all
* namespaces. When it is null or an empty
* string, this method behaves like
* getElementsByTagName.
* @param localName The local name of the elements to match on.
* The special value "*" matches all local names.
* @return NodeList A new NodeList object containing all the matched
* Elements.
* @since WD-DOM-Level-2-19990923
*/
public NodeList getElementsByTagNameNS(String namespaceURI,
String localName)
{
return new DeepNodeListImpl(this, namespaceURI, localName);
}
//
// Object methods
//
/** Clone. */
public Object clone() throws CloneNotSupportedException {
CoreDocumentImpl newdoc = (CoreDocumentImpl) super.clone();
newdoc.docType = null;
newdoc.docElement = null;
return newdoc;
}
//
// Public static methods
//
/**
* Check the string against XML's definition of acceptable names for
* elements and attributes and so on using the XMLCharacterProperties
* utility class
*/
public static boolean isXMLName(String s) {
if (s == null) {
return false;
}
return XMLCharacterProperties.validName(s);
} // isXMLName(String):boolean
//
// Protected methods
//
/**
* Uses the kidOK lookup table to check whether the proposed
* tree structure is legal.
*/
protected boolean isKidOK(Node parent, Node child) {
if (allowGrammarAccess &&
parent.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
return child.getNodeType() == Node.ELEMENT_NODE;
}
return 0 != (kidOK[parent.getNodeType()] & 1 << child.getNodeType());
}
/**
* Denotes that this node has changed.
*/
protected void changed() {
changes++;
}
/**
* Returns the number of changes to this node.
*/
protected int changes() {
return changes;
}
/**
* Store user data related to a given node
* This is a place where we could use weak references! Indeed, the node
* here won't be GC'ed as long as some user data is attached to it, since
* the userData table will have a reference to the node.
*/
protected void setUserData(NodeImpl n, Object data) {
// does nothing by default - overidden in subclass
}
/**
* Retreive user data related to a given node
*/
protected Object getUserData(NodeImpl n) {
// does nothing by default - overidden in subclass
return null;
}
protected void addEventListener(NodeImpl node, String type,
EventListener listener,
boolean useCapture) {
// does nothing by default - overidden in subclass
}
protected void removeEventListener(NodeImpl node, String type,
EventListener listener,
boolean useCapture) {
// does nothing by default - overidden in subclass
}
protected boolean dispatchEvent(NodeImpl node, Event event) {
// does nothing by default - overidden in subclass
return false;
}
// Notification methods overidden in subclasses
/**
* A method to be called when some text was changed in a text node,
* so that live objects can be notified.
*/
void replacedText(NodeImpl node) {
}
/**
* A method to be called when some text was deleted from a text node,
* so that live objects can be notified.
*/
void deletedText(NodeImpl node, int offset, int count) {
}
/**
* A method to be called when some text was inserted into a text node,
* so that live objects can be notified.
*/
void insertedText(NodeImpl node, int offset, int count) {
}
/**
* A method to be called when a character data node has been modified
*/
void modifyingCharacterData(NodeImpl node) {
}
/**
* A method to be called when a character data node has been modified
*/
void modifiedCharacterData(NodeImpl node, String oldvalue, String value) {
}
/**
* A method to be called when a node is about to be inserted in the tree.
*/
void insertingNode(NodeImpl node, boolean replace) {
}
/**
* A method to be called when a node has been inserted in the tree.
*/
void insertedNode(NodeImpl node, NodeImpl newInternal, boolean replace) {
}
/**
* A method to be called when a node is about to be removed from the tree.
*/
void removingNode(NodeImpl node, NodeImpl oldChild, boolean replace) {
}
/**
* A method to be called when a node has been removed from the tree.
*/
void removedNode(NodeImpl node, boolean replace) {
}
/**
* A method to be called when a node is about to be replaced in the tree.
*/
void replacingNode(NodeImpl node) {
}
/**
* A method to be called when a node has been replaced in the tree.
*/
void replacedNode(NodeImpl node) {
}
/**
* A method to be called when an attribute value has been modified
*/
void modifiedAttrValue(AttrImpl attr, String oldvalue) {
}
/**
* A method to be called when an attribute node has been set
*/
void setAttrNode(AttrImpl attr, AttrImpl previous) {
}
/**
* A method to be called when an attribute node has been removed
*/
void removedAttrNode(AttrImpl attr, NodeImpl oldOwner, String name) {
}
} // class CoreDocumentImpl
---------------------------------------------------------------------
To unsubscribe, e-mail: xerces-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: xerces-cvs-help@xml.apache.org