702
// in src/org/apache/xml/utils/ListingErrorHandler.java
public void warning (SAXParseException exception)
throws SAXException
{
logExceptionLocation(m_pw, exception);
// Note: should we really call .toString() below, since
// sometimes the message is not properly set?
m_pw.println("warning: " + exception.getMessage());
m_pw.flush();
if (getThrowOnWarning())
throw exception;
}
// in src/org/apache/xml/utils/ListingErrorHandler.java
public void error (SAXParseException exception)
throws SAXException
{
logExceptionLocation(m_pw, exception);
m_pw.println("error: " + exception.getMessage());
m_pw.flush();
if (getThrowOnError())
throw exception;
}
// in src/org/apache/xml/utils/ListingErrorHandler.java
public void fatalError (SAXParseException exception)
throws SAXException
{
logExceptionLocation(m_pw, exception);
m_pw.println("fatalError: " + exception.getMessage());
m_pw.flush();
if (getThrowOnFatalError())
throw exception;
}
// in src/org/apache/xml/utils/FastStringBuffer.java
public void sendSAXcharacters(
org.xml.sax.ContentHandler ch, int start, int length)
throws org.xml.sax.SAXException
{
int startChunk = start >>> m_chunkBits;
int startColumn = start & m_chunkMask;
if (startColumn + length < m_chunkMask && m_innerFSB == null) {
ch.characters(m_array[startChunk], startColumn, length);
return;
}
int stop = start + length;
int stopChunk = stop >>> m_chunkBits;
int stopColumn = stop & m_chunkMask;
for (int i = startChunk; i < stopChunk; ++i)
{
if (i == 0 && m_innerFSB != null)
m_innerFSB.sendSAXcharacters(ch, startColumn,
m_chunkSize - startColumn);
else
ch.characters(m_array[i], startColumn, m_chunkSize - startColumn);
startColumn = 0; // after first chunk
}
// Last, or only, chunk
if (stopChunk == 0 && m_innerFSB != null)
m_innerFSB.sendSAXcharacters(ch, startColumn, stopColumn - startColumn);
else if (stopColumn > startColumn)
{
ch.characters(m_array[stopChunk], startColumn,
stopColumn - startColumn);
}
}
// in src/org/apache/xml/utils/FastStringBuffer.java
public int sendNormalizedSAXcharacters(
org.xml.sax.ContentHandler ch, int start, int length)
throws org.xml.sax.SAXException
{
// This call always starts at the beginning of the
// string being written out, either because it was called directly or
// because it was an m_innerFSB recursion. This is important since
// it gives us a well-known initial state for this flag:
int stateForNextChunk=SUPPRESS_LEADING_WS;
int stop = start + length;
int startChunk = start >>> m_chunkBits;
int startColumn = start & m_chunkMask;
int stopChunk = stop >>> m_chunkBits;
int stopColumn = stop & m_chunkMask;
for (int i = startChunk; i < stopChunk; ++i)
{
if (i == 0 && m_innerFSB != null)
stateForNextChunk=
m_innerFSB.sendNormalizedSAXcharacters(ch, startColumn,
m_chunkSize - startColumn);
else
stateForNextChunk=
sendNormalizedSAXcharacters(m_array[i], startColumn,
m_chunkSize - startColumn,
ch,stateForNextChunk);
startColumn = 0; // after first chunk
}
// Last, or only, chunk
if (stopChunk == 0 && m_innerFSB != null)
stateForNextChunk= // %REVIEW% Is this update really needed?
m_innerFSB.sendNormalizedSAXcharacters(ch, startColumn, stopColumn - startColumn);
else if (stopColumn > startColumn)
{
stateForNextChunk= // %REVIEW% Is this update really needed?
sendNormalizedSAXcharacters(m_array[stopChunk],
startColumn, stopColumn - startColumn,
ch, stateForNextChunk | SUPPRESS_TRAILING_WS);
}
return stateForNextChunk;
}
// in src/org/apache/xml/utils/FastStringBuffer.java
static int sendNormalizedSAXcharacters(char ch[],
int start, int length,
org.xml.sax.ContentHandler handler,
int edgeTreatmentFlags)
throws org.xml.sax.SAXException
{
boolean processingLeadingWhitespace =
((edgeTreatmentFlags & SUPPRESS_LEADING_WS) != 0);
boolean seenWhitespace = ((edgeTreatmentFlags & CARRY_WS) != 0);
int currPos = start;
int limit = start+length;
// Strip any leading spaces first, if required
if (processingLeadingWhitespace) {
for (; currPos < limit
&& XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
currPos++) { }
// If we've only encountered leading spaces, the
// current state remains unchanged
if (currPos == limit) {
return edgeTreatmentFlags;
}
}
// If we get here, there are no more leading spaces to strip
while (currPos < limit) {
int startNonWhitespace = currPos;
// Grab a chunk of non-whitespace characters
for (; currPos < limit
&& !XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
currPos++) { }
// Non-whitespace seen - emit them, along with a single
// space for any preceding whitespace characters
if (startNonWhitespace != currPos) {
if (seenWhitespace) {
handler.characters(SINGLE_SPACE, 0, 1);
seenWhitespace = false;
}
handler.characters(ch, startNonWhitespace,
currPos - startNonWhitespace);
}
int startWhitespace = currPos;
// Consume any whitespace characters
for (; currPos < limit
&& XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
currPos++) { }
if (startWhitespace != currPos) {
seenWhitespace = true;
}
}
return (seenWhitespace ? CARRY_WS : 0)
| (edgeTreatmentFlags & SUPPRESS_TRAILING_WS);
}
// in src/org/apache/xml/utils/FastStringBuffer.java
public static void sendNormalizedSAXcharacters(char ch[],
int start, int length,
org.xml.sax.ContentHandler handler)
throws org.xml.sax.SAXException
{
sendNormalizedSAXcharacters(ch, start, length,
handler, SUPPRESS_BOTH);
}
// in src/org/apache/xml/utils/FastStringBuffer.java
public void sendSAXComment(
org.xml.sax.ext.LexicalHandler ch, int start, int length)
throws org.xml.sax.SAXException
{
// %OPT% Do it this way for now...
String comment = getString(start, length);
ch.comment(comment.toCharArray(), 0, length);
}
// in src/org/apache/xml/utils/TreeWalker.java
public void traverse(Node pos) throws org.xml.sax.SAXException
{
this.m_contentHandler.startDocument();
traverseFragment(pos);
this.m_contentHandler.endDocument();
}
// in src/org/apache/xml/utils/TreeWalker.java
public void traverseFragment(Node pos) throws org.xml.sax.SAXException
{
Node top = pos;
while (null != pos)
{
startNode(pos);
Node nextNode = pos.getFirstChild();
while (null == nextNode)
{
endNode(pos);
if (top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode)
{
pos = pos.getParentNode();
if ((null == pos) || (top.equals(pos)))
{
if (null != pos)
endNode(pos);
nextNode = null;
break;
}
}
}
pos = nextNode;
}
}
// in src/org/apache/xml/utils/TreeWalker.java
public void traverse(Node pos, Node top) throws org.xml.sax.SAXException
{
this.m_contentHandler.startDocument();
while (null != pos)
{
startNode(pos);
Node nextNode = pos.getFirstChild();
while (null == nextNode)
{
endNode(pos);
if ((null != top) && top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode)
{
pos = pos.getParentNode();
if ((null == pos) || ((null != top) && top.equals(pos)))
{
nextNode = null;
break;
}
}
}
pos = nextNode;
}
this.m_contentHandler.endDocument();
}
// in src/org/apache/xml/utils/TreeWalker.java
private final void dispatachChars(Node node)
throws org.xml.sax.SAXException
{
if(m_contentHandler instanceof org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.CharacterNodeHandler)
{
((org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.CharacterNodeHandler)m_contentHandler).characters(node);
}
else
{
String data = ((Text) node).getData();
this.m_contentHandler.characters(data.toCharArray(), 0, data.length());
}
}
// in src/org/apache/xml/utils/TreeWalker.java
protected void startNode(Node node) throws org.xml.sax.SAXException
{
if (m_contentHandler instanceof NodeConsumer)
{
((NodeConsumer) m_contentHandler).setOriginatingNode(node);
}
if (node instanceof Locator)
{
Locator loc = (Locator)node;
m_locator.setColumnNumber(loc.getColumnNumber());
m_locator.setLineNumber(loc.getLineNumber());
m_locator.setPublicId(loc.getPublicId());
m_locator.setSystemId(loc.getSystemId());
}
else
{
m_locator.setColumnNumber(0);
m_locator.setLineNumber(0);
}
switch (node.getNodeType())
{
case Node.COMMENT_NODE :
{
String data = ((Comment) node).getData();
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.comment(data.toCharArray(), 0, data.length());
}
}
break;
case Node.DOCUMENT_FRAGMENT_NODE :
// ??;
break;
case Node.DOCUMENT_NODE :
break;
case Node.ELEMENT_NODE :
NamedNodeMap atts = ((Element) node).getAttributes();
int nAttrs = atts.getLength();
// System.out.println("TreeWalker#startNode: "+node.getNodeName());
for (int i = 0; i < nAttrs; i++)
{
Node attr = atts.item(i);
String attrName = attr.getNodeName();
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:"))
{
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
int index;
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
String prefix = (index = attrName.indexOf(":")) < 0
? "" : attrName.substring(index + 1);
this.m_contentHandler.startPrefixMapping(prefix,
attr.getNodeValue());
}
}
// System.out.println("m_dh.getNamespaceOfNode(node): "+m_dh.getNamespaceOfNode(node));
// System.out.println("m_dh.getLocalNameOfNode(node): "+m_dh.getLocalNameOfNode(node));
String ns = m_dh.getNamespaceOfNode(node);
if(null == ns)
ns = "";
this.m_contentHandler.startElement(ns,
m_dh.getLocalNameOfNode(node),
node.getNodeName(),
new AttList(atts, m_dh));
break;
case Node.PROCESSING_INSTRUCTION_NODE :
{
ProcessingInstruction pi = (ProcessingInstruction) node;
String name = pi.getNodeName();
// String data = pi.getData();
if (name.equals("xslt-next-is-raw"))
{
nextIsRaw = true;
}
else
{
this.m_contentHandler.processingInstruction(pi.getNodeName(),
pi.getData());
}
}
break;
case Node.CDATA_SECTION_NODE :
{
boolean isLexH = (m_contentHandler instanceof LexicalHandler);
LexicalHandler lh = isLexH
? ((LexicalHandler) this.m_contentHandler) : null;
if (isLexH)
{
lh.startCDATA();
}
dispatachChars(node);
{
if (isLexH)
{
lh.endCDATA();
}
}
}
break;
case Node.TEXT_NODE :
{
//String data = ((Text) node).getData();
if (nextIsRaw)
{
nextIsRaw = false;
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
dispatachChars(node);
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
}
else
{
dispatachChars(node);
}
}
break;
case Node.ENTITY_REFERENCE_NODE :
{
EntityReference eref = (EntityReference) node;
if (m_contentHandler instanceof LexicalHandler)
{
((LexicalHandler) this.m_contentHandler).startEntity(
eref.getNodeName());
}
else
{
// warning("Can not output entity to a pure SAX ContentHandler");
}
}
break;
default :
}
}
// in src/org/apache/xml/utils/TreeWalker.java
protected void endNode(Node node) throws org.xml.sax.SAXException
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE :
break;
case Node.ELEMENT_NODE :
String ns = m_dh.getNamespaceOfNode(node);
if(null == ns)
ns = "";
this.m_contentHandler.endElement(ns,
m_dh.getLocalNameOfNode(node),
node.getNodeName());
NamedNodeMap atts = ((Element) node).getAttributes();
int nAttrs = atts.getLength();
for (int i = 0; i < nAttrs; i++)
{
Node attr = atts.item(i);
String attrName = attr.getNodeName();
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:"))
{
int index;
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
String prefix = (index = attrName.indexOf(":")) < 0
? "" : attrName.substring(index + 1);
this.m_contentHandler.endPrefixMapping(prefix);
}
}
break;
case Node.CDATA_SECTION_NODE :
break;
case Node.ENTITY_REFERENCE_NODE :
{
EntityReference eref = (EntityReference) node;
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.endEntity(eref.getNodeName());
}
}
break;
default :
}
}
// in src/org/apache/xml/utils/DefaultErrorHandler.java
public void warning(SAXParseException exception) throws SAXException
{
PrintWriter pw = getErrorWriter();
printLocation(pw, exception);
pw.println("Parser warning: " + exception.getMessage());
}
// in src/org/apache/xml/utils/DefaultErrorHandler.java
public void error(SAXParseException exception) throws SAXException
{
//printLocation(exception);
// getErrorWriter().println(exception.getMessage());
throw exception;
}
// in src/org/apache/xml/utils/DefaultErrorHandler.java
public void fatalError(SAXParseException exception) throws SAXException
{
// printLocation(exception);
// getErrorWriter().println(exception.getMessage());
throw exception;
}
// in src/org/apache/xml/utils/StylesheetPIHandler.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
if (target.equals("xml-stylesheet"))
{
String href = null; // CDATA #REQUIRED
String type = null; // CDATA #REQUIRED
String title = null; // CDATA #IMPLIED
String media = null; // CDATA #IMPLIED
String charset = null; // CDATA #IMPLIED
boolean alternate = false; // (yes|no) "no"
StringTokenizer tokenizer = new StringTokenizer(data, " \t=\n", true);
boolean lookedAhead = false;
Source source = null;
String token = "";
while (tokenizer.hasMoreTokens())
{
if (!lookedAhead)
token = tokenizer.nextToken();
else
lookedAhead = false;
if (tokenizer.hasMoreTokens() &&
(token.equals(" ") || token.equals("\t") || token.equals("=")))
continue;
String name = token;
if (name.equals("type"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
type = token.substring(1, token.length() - 1);
}
else if (name.equals("href"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
href = token;
if (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
// If the href value has parameters to be passed to a
// servlet(something like "foobar?id=12..."),
// we want to make sure we get them added to
// the href value. Without this check, we would move on
// to try to process another attribute and that would be
// wrong.
// We need to set lookedAhead here to flag that we
// already have the next token.
while ( token.equals("=") && tokenizer.hasMoreTokens())
{
href = href + token + tokenizer.nextToken();
if (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
lookedAhead = true;
}
else
{
break;
}
}
}
href = href.substring(1, href.length() - 1);
try
{
// Add code to use a URIResolver. Patch from Dmitri Ilyin.
if (m_uriResolver != null)
{
source = m_uriResolver.resolve(href, m_baseID);
}
else
{
href = SystemIDResolver.getAbsoluteURI(href, m_baseID);
source = new SAXSource(new InputSource(href));
}
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
else if (name.equals("title"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
title = token.substring(1, token.length() - 1);
}
else if (name.equals("media"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
media = token.substring(1, token.length() - 1);
}
else if (name.equals("charset"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
charset = token.substring(1, token.length() - 1);
}
else if (name.equals("alternate"))
{
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() &&
(token.equals(" " ) || token.equals("\t") || token.equals("=")))
token = tokenizer.nextToken();
alternate = token.substring(1, token.length()
- 1).equals("yes");
}
}
if ((null != type)
&& (type.equals("text/xsl") || type.equals("text/xml") || type.equals("application/xml+xslt"))
&& (null != href))
{
if (null != m_media)
{
if (null != media)
{
if (!media.equals(m_media))
return;
}
else
return;
}
if (null != m_charset)
{
if (null != charset)
{
if (!charset.equals(m_charset))
return;
}
else
return;
}
if (null != m_title)
{
if (null != title)
{
if (!title.equals(m_title))
return;
}
else
return;
}
m_stylesheets.addElement(source);
}
}
}
// in src/org/apache/xml/utils/StylesheetPIHandler.java
public void startElement(
String namespaceURI, String localName, String qName, Attributes atts)
throws org.xml.sax.SAXException
{
throw new StopParseException();
}
// in src/org/apache/xml/utils/DOMBuilder.java
protected void append(Node newNode) throws org.xml.sax.SAXException
{
Node currentNode = m_currentNode;
if (null != currentNode)
{
if (currentNode == m_root && m_nextSibling != null)
currentNode.insertBefore(newNode, m_nextSibling);
else
currentNode.appendChild(newNode);
// System.out.println(newNode.getNodeName());
}
else if (null != m_docFrag)
{
if (m_nextSibling != null)
m_docFrag.insertBefore(newNode, m_nextSibling);
else
m_docFrag.appendChild(newNode);
}
else
{
boolean ok = true;
short type = newNode.getNodeType();
if (type == Node.TEXT_NODE)
{
String data = newNode.getNodeValue();
if ((null != data) && (data.trim().length() > 0))
{
throw new org.xml.sax.SAXException(
XMLMessages.createXMLMessage(
XMLErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC, null)); //"Warning: can't output text before document element! Ignoring...");
}
ok = false;
}
else if (type == Node.ELEMENT_NODE)
{
if (m_doc.getDocumentElement() != null)
{
ok = false;
throw new org.xml.sax.SAXException(
XMLMessages.createXMLMessage(
XMLErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT, null)); //"Can't have more than one root on a DOM!");
}
}
if (ok)
{
if (m_nextSibling != null)
m_doc.insertBefore(newNode, m_nextSibling);
else
m_doc.appendChild(newNode);
}
}
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startDocument() throws org.xml.sax.SAXException
{
// No action for the moment.
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endDocument() throws org.xml.sax.SAXException
{
// No action for the moment.
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startElement(
String ns, String localName, String name, Attributes atts)
throws org.xml.sax.SAXException
{
Element elem;
// Note that the namespace-aware call must be used to correctly
// construct a Level 2 DOM, even for non-namespaced nodes.
if ((null == ns) || (ns.length() == 0))
elem = m_doc.createElementNS(null,name);
else
elem = m_doc.createElementNS(ns, name);
append(elem);
try
{
int nAtts = atts.getLength();
if (0 != nAtts)
{
for (int i = 0; i < nAtts; i++)
{
//System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) );
// First handle a possible ID attribute
if (atts.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(atts.getValue(i), elem);
String attrNS = atts.getURI(i);
if("".equals(attrNS))
attrNS = null; // DOM represents no-namespace as null
// System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i)
// +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
// Crimson won't let us set an xmlns: attribute on the DOM.
String attrQName = atts.getQName(i);
// In SAX, xmlns[:] attributes have an empty namespace, while in DOM they
// should have the xmlns namespace
if (attrQName.startsWith("xmlns:") || attrQName.equals("xmlns")) {
attrNS = "http://www.w3.org/2000/xmlns/";
}
// ALWAYS use the DOM Level 2 call!
elem.setAttributeNS(attrNS,attrQName, atts.getValue(i));
}
}
/*
* Adding namespace nodes to the DOM tree;
*/
int nDecls = m_prefixMappings.size();
String prefix, declURL;
for (int i = 0; i < nDecls; i += 2)
{
prefix = (String) m_prefixMappings.elementAt(i);
if (prefix == null)
continue;
declURL = (String) m_prefixMappings.elementAt(i + 1);
elem.setAttributeNS("http://www.w3.org/2000/xmlns/", prefix, declURL);
}
m_prefixMappings.clear();
// append(elem);
m_elemStack.push(elem);
m_currentNode = elem;
// append(elem);
}
catch(java.lang.Exception de)
{
// de.printStackTrace();
throw new org.xml.sax.SAXException(de);
}
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endElement(String ns, String localName, String name)
throws org.xml.sax.SAXException
{
m_elemStack.pop();
m_currentNode = m_elemStack.isEmpty() ? null : (Node)m_elemStack.peek();
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
if(isOutsideDocElem()
&& org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
return; // avoid DOM006 Hierarchy request error
if (m_inCData)
{
cdata(ch, start, length);
return;
}
String s = new String(ch, start, length);
Node childNode;
childNode = m_currentNode != null ? m_currentNode.getLastChild(): null;
if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
((Text)childNode).appendData(s);
}
else{
Text text = m_doc.createTextNode(s);
append(text);
}
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void charactersRaw(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if(isOutsideDocElem()
&& org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
append(m_doc.createProcessingInstruction("xslt-next-is-raw",
"formatter-to-dom"));
append(m_doc.createTextNode(s));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startEntity(String name) throws org.xml.sax.SAXException
{
// Almost certainly the wrong behavior...
// entityReference(name);
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endEntity(String name) throws org.xml.sax.SAXException{}
// in src/org/apache/xml/utils/DOMBuilder.java
public void entityReference(String name) throws org.xml.sax.SAXException
{
append(m_doc.createEntityReference(name));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if(isOutsideDocElem())
return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
append(m_doc.createTextNode(s));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
append(m_doc.createProcessingInstruction(target, data));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException
{
append(m_doc.createComment(new String(ch, start, length)));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startCDATA() throws org.xml.sax.SAXException
{
m_inCData = true;
append(m_doc.createCDATASection(""));
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endCDATA() throws org.xml.sax.SAXException
{
m_inCData = false;
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException
{
if(isOutsideDocElem()
&& org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
return; // avoid DOM006 Hierarchy request error
String s = new String(ch, start, length);
CDATASection section =(CDATASection) m_currentNode.getLastChild();
section.appendData(s);
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startDTD(String name, String publicId, String systemId)
throws org.xml.sax.SAXException
{
// Do nothing for now.
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endDTD() throws org.xml.sax.SAXException
{
// Do nothing for now.
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
if(null == prefix || prefix.length() == 0)
prefix = "xmlns";
else prefix = "xmlns:"+prefix;
m_prefixMappings.addElement(prefix);
m_prefixMappings.addElement(uri);
}
// in src/org/apache/xml/utils/DOMBuilder.java
public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException{}
// in src/org/apache/xml/utils/DOMBuilder.java
public void skippedEntity(String name) throws org.xml.sax.SAXException{}
// in src/org/apache/xml/utils/XMLStringDefault.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
}
// in src/org/apache/xml/utils/XMLStringDefault.java
public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
throws org.xml.sax.SAXException
{
}
// in src/org/apache/xml/utils/XMLReaderManager.java
public synchronized XMLReader getXMLReader() throws SAXException {
XMLReader reader;
boolean readerInUse;
if (m_readers == null) {
// When the m_readers.get() method is called for the first time
// on a thread, a new XMLReader will automatically be created.
m_readers = new ThreadLocal();
}
if (m_inUse == null) {
m_inUse = new Hashtable();
}
// If the cached reader for this thread is in use, construct a new
// one; otherwise, return the cached reader.
reader = (XMLReader) m_readers.get();
boolean threadHasReader = (reader != null);
if (!threadHasReader || m_inUse.get(reader) == Boolean.TRUE) {
try {
try {
// According to JAXP 1.2 specification, if a SAXSource
// is created using a SAX InputSource the Transformer or
// TransformerFactory creates a reader via the
// XMLReaderFactory if setXMLReader is not used
reader = XMLReaderFactory.createXMLReader();
} catch (Exception e) {
try {
// If unable to create an instance, let's try to use
// the XMLReader from JAXP
if (m_parserFactory == null) {
m_parserFactory = SAXParserFactory.newInstance();
m_parserFactory.setNamespaceAware(true);
}
reader = m_parserFactory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException pce) {
throw pce; // pass along pce
}
}
try {
reader.setFeature(NAMESPACES_FEATURE, true);
reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
} catch (SAXException se) {
// Try to carry on if we've got a parser that
// doesn't know about namespace prefixes.
}
} catch (ParserConfigurationException ex) {
throw new SAXException(ex);
} catch (FactoryConfigurationError ex1) {
throw new SAXException(ex1.toString());
} catch (NoSuchMethodError ex2) {
} catch (AbstractMethodError ame) {
}
// Cache the XMLReader if this is the first time we've created
// a reader for this thread.
if (!threadHasReader) {
m_readers.set(reader);
m_inUse.put(reader, Boolean.TRUE);
}
} else {
m_inUse.put(reader, Boolean.TRUE);
}
return reader;
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void characters(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.characters(ch,start,length);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endDocument()
throws org.xml.sax.SAXException
{
// EXCEPTION: In this case we need to run the event BEFORE we yield.
if(clientContentHandler!=null)
clientContentHandler.endDocument();
eventcounter=0;
co_yield(false);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endElement(java.lang.String namespaceURI, java.lang.String localName,
java.lang.String qName)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.endElement(namespaceURI,localName,qName);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endPrefixMapping(java.lang.String prefix)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.endPrefixMapping(prefix);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.ignorableWhitespace(ch,start,length);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void processingInstruction(java.lang.String target, java.lang.String data)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.processingInstruction(target,data);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void skippedEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.skippedEntity(name);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startDocument()
throws org.xml.sax.SAXException
{
co_entry_pause();
// Otherwise, begin normal event delivery
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.startDocument();
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startElement(java.lang.String namespaceURI, java.lang.String localName,
java.lang.String qName, Attributes atts)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.startElement(namespaceURI, localName, qName, atts);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startPrefixMapping(java.lang.String prefix, java.lang.String uri)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.startPrefixMapping(prefix,uri);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void comment(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.comment(ch,start,length);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endCDATA()
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.endCDATA();
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endDTD()
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.endDTD();
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void endEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.endEntity(name);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startCDATA()
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.startCDATA();
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startDTD(java.lang.String name, java.lang.String publicId,
java.lang.String systemId)
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler. startDTD(name, publicId, systemId);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
if(null!=clientLexicalHandler)
clientLexicalHandler.startEntity(name);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void notationDecl(String a, String b, String c) throws SAXException
{
if(null!=clientDTDHandler)
clientDTDHandler.notationDecl(a,b,c);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void unparsedEntityDecl(String a, String b, String c, String d) throws SAXException
{
if(null!=clientDTDHandler)
clientDTDHandler.unparsedEntityDecl(a,b,c,d);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void error(SAXParseException exception) throws SAXException
{
if(null!=clientErrorHandler)
clientErrorHandler.error(exception);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void fatalError(SAXParseException exception) throws SAXException
{
// EXCEPTION: In this case we need to run the event BEFORE we yield --
// just as with endDocument, this terminates the event stream.
if(null!=clientErrorHandler)
clientErrorHandler.error(exception);
eventcounter=0;
co_yield(false);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void warning(SAXParseException exception) throws SAXException
{
if(null!=clientErrorHandler)
clientErrorHandler.error(exception);
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
protected void count_and_yield(boolean moreExpected) throws SAXException
{
if(!moreExpected) eventcounter=0;
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
private void co_entry_pause() throws SAXException
{
if(fCoroutineManager==null)
{
// Nobody called init()? Do it now...
init(null,-1,-1);
}
try
{
Object arg=fCoroutineManager.co_entry_pause(fSourceCoroutineID);
if(arg==Boolean.FALSE)
co_yield(false);
}
catch(NoSuchMethodException e)
{
// Coroutine system says we haven't registered. That's an
// application coding error, and is unrecoverable.
if(DEBUG) e.printStackTrace();
throw new SAXException(e);
}
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
private void co_yield(boolean moreRemains) throws SAXException
{
// Horrendous kluge to run filter to completion. See below.
if(fNoMoreEvents)
return;
try // Coroutine manager might throw no-such.
{
Object arg=Boolean.FALSE;
if(moreRemains)
{
// Yield control, resume parsing when done
arg = fCoroutineManager.co_resume(Boolean.TRUE, fSourceCoroutineID,
fControllerCoroutineID);
}
// If we're at end of document or were told to stop early
if(arg==Boolean.FALSE)
{
fNoMoreEvents=true;
if(fXMLReader!=null) // Running under startParseThread()
throw new StopException(); // We'll co_exit from there.
// Yield control. We do NOT expect anyone to ever ask us again.
fCoroutineManager.co_exit_to(Boolean.FALSE, fSourceCoroutineID,
fControllerCoroutineID);
}
}
catch(NoSuchMethodException e)
{
// Shouldn't happen unless we've miscoded our coroutine logic
// "Shut down the garbage smashers on the detention level!"
fNoMoreEvents=true;
fCoroutineManager.co_exit(fSourceCoroutineID);
throw new SAXException(e);
}
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java
public void startParse(InputSource source) throws SAXException
{
if(fNoMoreEvents)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_INCRSAXSRCFILTER_NOT_RESTARTABLE, null)); //"IncrmentalSAXSource_Filter not currently restartable.");
if(fXMLReader==null)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_XMLRDR_NOT_BEFORE_STARTPARSE, null)); //"XMLReader not before startParse request");
fXMLReaderInputSource=source;
// Xalan thread pooling...
// org.apache.xalan.transformer.TransformerImpl.runTransformThread(this);
ThreadControllerWrapper.runThread(this, -1);
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void characters(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
// Actually creating the text node is handled by
// processAccumulatedText(); here we just accumulate the
// characters into the buffer.
m_char.append(ch,start,length);
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endDocument()
throws org.xml.sax.SAXException
{
// May need to tell the low-level builder code to pop up a level.
// There _should't_ be any significant pending text at this point.
appendEndDocument();
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endElement(java.lang.String namespaceURI, java.lang.String localName,
java.lang.String qName)
throws org.xml.sax.SAXException
{
processAccumulatedText();
// No args but we do need to tell the low-level builder code to
// pop up a level.
appendEndElement();
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endPrefixMapping(java.lang.String prefix)
throws org.xml.sax.SAXException
{
// No-op
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
// %TBD% I believe ignorable text isn't part of the DTM model...?
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void processingInstruction(java.lang.String target, java.lang.String data)
throws org.xml.sax.SAXException
{
processAccumulatedText();
// %TBD% Which pools do target and data go into?
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void skippedEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
processAccumulatedText();
//%TBD%
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startDocument()
throws org.xml.sax.SAXException
{
appendStartDocument();
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startElement(java.lang.String namespaceURI, java.lang.String localName,
java.lang.String qName, Attributes atts)
throws org.xml.sax.SAXException
{
processAccumulatedText();
// %TBD% Split prefix off qname
String prefix=null;
int colon=qName.indexOf(':');
if(colon>0)
prefix=qName.substring(0,colon);
// %TBD% Where do we pool expandedName, or is it just the union, or...
/**/System.out.println("Prefix="+prefix+" index="+m_prefixNames.stringToIndex(prefix));
appendStartElement(m_nsNames.stringToIndex(namespaceURI),
m_localNames.stringToIndex(localName),
m_prefixNames.stringToIndex(prefix)); /////// %TBD%
// %TBD% I'm assuming that DTM will require resequencing of
// NS decls before other attrs, hence two passes are taken.
// %TBD% Is there an easier way to test for NSDecl?
int nAtts=(atts==null) ? 0 : atts.getLength();
// %TBD% Countdown is more efficient if nobody cares about sequence.
for(int i=nAtts-1;i>=0;--i)
{
qName=atts.getQName(i);
if(qName.startsWith("xmlns:") || "xmlns".equals(qName))
{
prefix=null;
colon=qName.indexOf(':');
if(colon>0)
{
prefix=qName.substring(0,colon);
}
else
{
// %REVEIW% Null or ""?
prefix=null; // Default prefix
}
appendNSDeclaration(
m_prefixNames.stringToIndex(prefix),
m_nsNames.stringToIndex(atts.getValue(i)),
atts.getType(i).equalsIgnoreCase("ID"));
}
}
for(int i=nAtts-1;i>=0;--i)
{
qName=atts.getQName(i);
if(!(qName.startsWith("xmlns:") || "xmlns".equals(qName)))
{
// %TBD% I hate having to extract the prefix into a new
// string when we may never use it. Consider pooling whole
// qNames, which are already strings?
prefix=null;
colon=qName.indexOf(':');
if(colon>0)
{
prefix=qName.substring(0,colon);
localName=qName.substring(colon+1);
}
else
{
prefix=""; // Default prefix
localName=qName;
}
m_char.append(atts.getValue(i)); // Single-string value
int contentEnd=m_char.length();
if(!("xmlns".equals(prefix) || "xmlns".equals(qName)))
appendAttribute(m_nsNames.stringToIndex(atts.getURI(i)),
m_localNames.stringToIndex(localName),
m_prefixNames.stringToIndex(prefix),
atts.getType(i).equalsIgnoreCase("ID"),
m_char_current_start, contentEnd-m_char_current_start);
m_char_current_start=contentEnd;
}
}
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startPrefixMapping(java.lang.String prefix, java.lang.String uri)
throws org.xml.sax.SAXException
{
// No-op in DTM, handled during element/attr processing?
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void comment(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
processAccumulatedText();
m_char.append(ch,start,length); // Single-string value
appendComment(m_char_current_start,length);
m_char_current_start+=length;
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endCDATA()
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endDTD()
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void endEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startCDATA()
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startDTD(java.lang.String name, java.lang.String publicId,
java.lang.String systemId)
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void startEntity(java.lang.String name)
throws org.xml.sax.SAXException
{
// No-op in DTM
}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void dispatchCharactersEvents(
int nodeHandle, org.xml.sax.ContentHandler ch, boolean normalize)
throws org.xml.sax.SAXException {}
// in src/org/apache/xml/dtm/ref/DTMDocumentImpl.java
public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException {}
// in src/org/apache/xml/dtm/ref/DTMTreeWalker.java
public void traverse(int pos) throws org.xml.sax.SAXException
{
// %REVIEW% Why isn't this just traverse(pos,pos)?
int top = pos; // Remember the root of this subtree
while (DTM.NULL != pos)
{
startNode(pos);
int nextNode = m_dtm.getFirstChild(pos);
while (DTM.NULL == nextNode)
{
endNode(pos);
if (top == pos)
break;
nextNode = m_dtm.getNextSibling(pos);
if (DTM.NULL == nextNode)
{
pos = m_dtm.getParent(pos);
if ((DTM.NULL == pos) || (top == pos))
{
// %REVIEW% This condition isn't tested in traverse(pos,top)
// -- bug?
if (DTM.NULL != pos)
endNode(pos);
nextNode = DTM.NULL;
break;
}
}
}
pos = nextNode;
}
}
// in src/org/apache/xml/dtm/ref/DTMTreeWalker.java
public void traverse(int pos, int top) throws org.xml.sax.SAXException
{
// %OPT% Can we simplify the loop conditionals by adding:
// if(top==DTM.NULL) top=0
// -- or by simply ignoring this case and relying on the fact that
// pos will never equal DTM.NULL until we're ready to exit?
while (DTM.NULL != pos)
{
startNode(pos);
int nextNode = m_dtm.getFirstChild(pos);
while (DTM.NULL == nextNode)
{
endNode(pos);
if ((DTM.NULL != top) && top == pos)
break;
nextNode = m_dtm.getNextSibling(pos);
if (DTM.NULL == nextNode)
{
pos = m_dtm.getParent(pos);
if ((DTM.NULL == pos) || ((DTM.NULL != top) && (top == pos)))
{
nextNode = DTM.NULL;
break;
}
}
}
pos = nextNode;
}
}
// in src/org/apache/xml/dtm/ref/DTMTreeWalker.java
private final void dispatachChars(int node)
throws org.xml.sax.SAXException
{
m_dtm.dispatchCharactersEvents(node, m_contentHandler, false);
}
// in src/org/apache/xml/dtm/ref/DTMTreeWalker.java
protected void startNode(int node) throws org.xml.sax.SAXException
{
if (m_contentHandler instanceof NodeConsumer)
{
// %TBD%
// ((NodeConsumer) m_contentHandler).setOriginatingNode(node);
}
switch (m_dtm.getNodeType(node))
{
case DTM.COMMENT_NODE :
{
XMLString data = m_dtm.getStringValue(node);
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
data.dispatchAsComment(lh);
}
}
break;
case DTM.DOCUMENT_FRAGMENT_NODE :
// ??;
break;
case DTM.DOCUMENT_NODE :
this.m_contentHandler.startDocument();
break;
case DTM.ELEMENT_NODE :
DTM dtm = m_dtm;
for (int nsn = dtm.getFirstNamespaceNode(node, true); DTM.NULL != nsn;
nsn = dtm.getNextNamespaceNode(node, nsn, true))
{
// String prefix = dtm.getPrefix(nsn);
String prefix = dtm.getNodeNameX(nsn);
this.m_contentHandler.startPrefixMapping(prefix, dtm.getNodeValue(nsn));
}
// System.out.println("m_dh.getNamespaceOfNode(node): "+m_dh.getNamespaceOfNode(node));
// System.out.println("m_dh.getLocalNameOfNode(node): "+m_dh.getLocalNameOfNode(node));
String ns = dtm.getNamespaceURI(node);
if(null == ns)
ns = "";
// %OPT% !!
org.xml.sax.helpers.AttributesImpl attrs =
new org.xml.sax.helpers.AttributesImpl();
for (int i = dtm.getFirstAttribute(node);
i != DTM.NULL;
i = dtm.getNextAttribute(i))
{
attrs.addAttribute(dtm.getNamespaceURI(i),
dtm.getLocalName(i),
dtm.getNodeName(i),
"CDATA",
dtm.getNodeValue(i));
}
this.m_contentHandler.startElement(ns,
m_dtm.getLocalName(node),
m_dtm.getNodeName(node),
attrs);
break;
case DTM.PROCESSING_INSTRUCTION_NODE :
{
String name = m_dtm.getNodeName(node);
// String data = pi.getData();
if (name.equals("xslt-next-is-raw"))
{
nextIsRaw = true;
}
else
{
this.m_contentHandler.processingInstruction(name,
m_dtm.getNodeValue(node));
}
}
break;
case DTM.CDATA_SECTION_NODE :
{
boolean isLexH = (m_contentHandler instanceof LexicalHandler);
LexicalHandler lh = isLexH
? ((LexicalHandler) this.m_contentHandler) : null;
if (isLexH)
{
lh.startCDATA();
}
dispatachChars(node);
{
if (isLexH)
{
lh.endCDATA();
}
}
}
break;
case DTM.TEXT_NODE :
{
if (nextIsRaw)
{
nextIsRaw = false;
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
dispatachChars(node);
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
}
else
{
dispatachChars(node);
}
}
break;
case DTM.ENTITY_REFERENCE_NODE :
{
if (m_contentHandler instanceof LexicalHandler)
{
((LexicalHandler) this.m_contentHandler).startEntity(
m_dtm.getNodeName(node));
}
else
{
// warning("Can not output entity to a pure SAX ContentHandler");
}
}
break;
default :
}
}
// in src/org/apache/xml/dtm/ref/DTMTreeWalker.java
protected void endNode(int node) throws org.xml.sax.SAXException
{
switch (m_dtm.getNodeType(node))
{
case DTM.DOCUMENT_NODE :
this.m_contentHandler.endDocument();
break;
case DTM.ELEMENT_NODE :
String ns = m_dtm.getNamespaceURI(node);
if(null == ns)
ns = "";
this.m_contentHandler.endElement(ns,
m_dtm.getLocalName(node),
m_dtm.getNodeName(node));
for (int nsn = m_dtm.getFirstNamespaceNode(node, true); DTM.NULL != nsn;
nsn = m_dtm.getNextNamespaceNode(node, nsn, true))
{
// String prefix = m_dtm.getPrefix(nsn);
String prefix = m_dtm.getNodeNameX(nsn);
this.m_contentHandler.endPrefixMapping(prefix);
}
break;
case DTM.CDATA_SECTION_NODE :
break;
case DTM.ENTITY_REFERENCE_NODE :
{
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.endEntity(m_dtm.getNodeName(node));
}
}
break;
default :
}
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Xerces.java
public void startParse(InputSource source) throws SAXException
{
if (fIncrementalParser==null)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_NEEDS_SAXPARSER, null)); //"startParse needs a non-null SAXParser.");
if (fParseInProgress)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_WHILE_PARSING, null)); //"startParse may not be called while parsing.");
boolean ok=false;
try
{
ok = parseSomeSetup(source);
}
catch(Exception ex)
{
throw new SAXException(ex);
}
if(!ok)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COULD_NOT_INIT_PARSER, null)); //"could not initialize parser with");
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Xerces.java
private boolean parseSomeSetup(InputSource source)
throws SAXException, IOException, IllegalAccessException,
java.lang.reflect.InvocationTargetException,
java.lang.InstantiationException
{
if(fConfigSetInput!=null)
{
// Obtain input from SAX inputSource object, construct XNI version of
// that object. Logic adapted from Xerces2.
Object[] parms1={source.getPublicId(),source.getSystemId(),null};
Object xmlsource=fConfigInputSourceCtor.newInstance(parms1);
Object[] parmsa={source.getByteStream()};
fConfigSetByteStream.invoke(xmlsource,parmsa);
parmsa[0]=source.getCharacterStream();
fConfigSetCharStream.invoke(xmlsource,parmsa);
parmsa[0]=source.getEncoding();
fConfigSetEncoding.invoke(xmlsource,parmsa);
// Bugzilla5272 patch suggested by Sandy Gao.
// Has to be reflection to run with Xerces2
// after compilation against Xerces1. or vice
// versa, due to return type mismatches.
Object[] noparms=new Object[0];
fReset.invoke(fIncrementalParser,noparms);
parmsa[0]=xmlsource;
fConfigSetInput.invoke(fPullParserConfig,parmsa);
// %REVIEW% Do first pull. Should we instead just return true?
return parseSome();
}
else
{
Object[] parm={source};
Object ret=fParseSomeSetup.invoke(fIncrementalParser,parm);
return ((Boolean)ret).booleanValue();
}
}
// in src/org/apache/xml/dtm/ref/IncrementalSAXSource_Xerces.java
private boolean parseSome()
throws SAXException, IOException, IllegalAccessException,
java.lang.reflect.InvocationTargetException
{
// Take next parsing step, return false iff parsing complete:
if(fConfigSetInput!=null)
{
Object ret=(Boolean)(fConfigParse.invoke(fPullParserConfig,parmsfalse));
return ((Boolean)ret).booleanValue();
}
else
{
Object ret=fParseSome.invoke(fIncrementalParser,noparms);
return ((Boolean)ret).booleanValue();
}
}
// in src/org/apache/xml/dtm/ref/dom2dtm/DOM2DTM.java
public void dispatchCharactersEvents(
int nodeHandle, org.xml.sax.ContentHandler ch,
boolean normalize)
throws org.xml.sax.SAXException
{
if(normalize)
{
XMLString str = getStringValue(nodeHandle);
str = str.fixWhiteSpace(true, true, false);
str.dispatchCharactersEvents(ch);
}
else
{
int type = getNodeType(nodeHandle);
Node node = getNode(nodeHandle);
dispatchNodeData(node, ch, 0);
// Text coalition -- a DTM text node may represent multiple
// DOM nodes.
if(TEXT_NODE == type || CDATA_SECTION_NODE == type)
{
while( null != (node=logicalNextDOMTextNode(node)) )
{
dispatchNodeData(node, ch, 0);
}
}
}
}
// in src/org/apache/xml/dtm/ref/dom2dtm/DOM2DTM.java
protected static void dispatchNodeData(Node node,
org.xml.sax.ContentHandler ch,
int depth)
throws org.xml.sax.SAXException
{
switch (node.getNodeType())
{
case Node.DOCUMENT_FRAGMENT_NODE :
case Node.DOCUMENT_NODE :
case Node.ELEMENT_NODE :
{
for (Node child = node.getFirstChild(); null != child;
child = child.getNextSibling())
{
dispatchNodeData(child, ch, depth+1);
}
}
break;
case Node.PROCESSING_INSTRUCTION_NODE : // %REVIEW%
case Node.COMMENT_NODE :
if(0 != depth)
break;
// NOTE: Because this operation works in the DOM space, it does _not_ attempt
// to perform Text Coalition. That should only be done in DTM space.
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE :
case Node.ATTRIBUTE_NODE :
String str = node.getNodeValue();
if(ch instanceof CharacterNodeHandler)
{
((CharacterNodeHandler)ch).characters(node);
}
else
{
ch.characters(str.toCharArray(), 0, str.length());
}
break;
// /* case Node.PROCESSING_INSTRUCTION_NODE :
// // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
// break; */
default :
// ignore
break;
}
}
// in src/org/apache/xml/dtm/ref/dom2dtm/DOM2DTM.java
public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
TreeWalker treeWalker = m_walker;
ContentHandler prevCH = treeWalker.getContentHandler();
if(null != prevCH)
{
treeWalker = new TreeWalker(null);
}
treeWalker.setContentHandler(ch);
try
{
Node node = getNode(nodeHandle);
treeWalker.traverseFragment(node);
}
finally
{
treeWalker.setContentHandler(null);
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2RTFDTM.java
public void startDocument() throws SAXException
{
// Re-initialize the tree append process
m_endDocumentOccured = false;
m_prefixMappings = new java.util.Vector();
m_contextIndexes = new IntStack();
m_parents = new IntStack();
m_currentDocumentNode=m_size;
super.startDocument();
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2RTFDTM.java
public void endDocument() throws SAXException
{
charactersFlush();
m_nextsib.setElementAt(NULL,m_currentDocumentNode);
if (m_firstch.elementAt(m_currentDocumentNode) == NOTPROCESSED)
m_firstch.setElementAt(NULL,m_currentDocumentNode);
if (DTM.NULL != m_previous)
m_nextsib.setElementAt(DTM.NULL,m_previous);
m_parents = null;
m_prefixMappings = null;
m_contextIndexes = null;
m_currentDocumentNode= NULL; // no longer open
m_endDocumentOccured = true;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void dispatchCharactersEvents(int nodeHandle, ContentHandler ch,
boolean normalize)
throws SAXException
{
int identity = makeNodeIdentity(nodeHandle);
if (identity == DTM.NULL)
return;
int type = _type(identity);
if (isTextType(type))
{
int dataIndex = m_dataOrQName.elementAt(identity);
int offset = m_data.elementAt(dataIndex);
int length = m_data.elementAt(dataIndex + 1);
if(normalize)
m_chars.sendNormalizedSAXcharacters(ch, offset, length);
else
m_chars.sendSAXcharacters(ch, offset, length);
}
else
{
int firstChild = _firstch(identity);
if (DTM.NULL != firstChild)
{
int offset = -1;
int length = 0;
int startNode = identity;
identity = firstChild;
do {
type = _type(identity);
if (isTextType(type))
{
int dataIndex = _dataOrQName(identity);
if (-1 == offset)
{
offset = m_data.elementAt(dataIndex);
}
length += m_data.elementAt(dataIndex + 1);
}
identity = getNextNodeIdentity(identity);
} while (DTM.NULL != identity && (_parent(identity) >= startNode));
if (length > 0)
{
if(normalize)
m_chars.sendNormalizedSAXcharacters(ch, offset, length);
else
m_chars.sendSAXcharacters(ch, offset, length);
}
}
else if(type != DTM.ELEMENT_NODE)
{
int dataIndex = _dataOrQName(identity);
if (dataIndex < 0)
{
dataIndex = -dataIndex;
dataIndex = m_data.elementAt(dataIndex + 1);
}
String str = m_valuesOrPrefixes.indexToString(dataIndex);
if(normalize)
FastStringBuffer.sendNormalizedSAXcharacters(str.toCharArray(),
0, str.length(), ch);
else
ch.characters(str.toCharArray(), 0, str.length());
}
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
DTMTreeWalker treeWalker = m_walker;
ContentHandler prevCH = treeWalker.getcontentHandler();
if (null != prevCH)
{
treeWalker = new DTMTreeWalker();
}
treeWalker.setcontentHandler(ch);
treeWalker.setDTM(this);
try
{
treeWalker.traverse(nodeHandle);
}
finally
{
treeWalker.setcontentHandler(null);
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException
{
return null;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void notationDecl(String name, String publicId, String systemId)
throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void unparsedEntityDecl(
String name, String publicId, String systemId, String notationName)
throws SAXException
{
if (null == m_entities)
{
m_entities = new Vector();
}
try
{
systemId = SystemIDResolver.getAbsoluteURI(systemId,
getDocumentBaseURI());
}
catch (Exception e)
{
throw new org.xml.sax.SAXException(e);
}
// private static final int ENTITY_FIELD_PUBLICID = 0;
m_entities.addElement(publicId);
// private static final int ENTITY_FIELD_SYSTEMID = 1;
m_entities.addElement(systemId);
// private static final int ENTITY_FIELD_NOTATIONNAME = 2;
m_entities.addElement(notationName);
// private static final int ENTITY_FIELD_NAME = 3;
m_entities.addElement(name);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startDocument() throws SAXException
{
if (DEBUG)
System.out.println("startDocument");
int doc = addNode(DTM.DOCUMENT_NODE,
m_expandedNameTable.getExpandedTypeID(DTM.DOCUMENT_NODE),
DTM.NULL, DTM.NULL, 0, true);
m_parents.push(doc);
m_previous = DTM.NULL;
m_contextIndexes.push(m_prefixMappings.size()); // for the next element.
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endDocument() throws SAXException
{
if (DEBUG)
System.out.println("endDocument");
charactersFlush();
m_nextsib.setElementAt(NULL,0);
if (m_firstch.elementAt(0) == NOTPROCESSED)
m_firstch.setElementAt(NULL,0);
if (DTM.NULL != m_previous)
m_nextsib.setElementAt(DTM.NULL,m_previous);
m_parents = null;
m_prefixMappings = null;
m_contextIndexes = null;
m_endDocumentOccured = true;
// Bugzilla 4858: throw away m_locator. we cache m_systemId
m_locator = null;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (DEBUG)
System.out.println("startPrefixMapping: prefix: " + prefix + ", uri: "
+ uri);
if(null == prefix)
prefix = "";
m_prefixMappings.addElement(prefix); // JDK 1.1.x compat -sc
m_prefixMappings.addElement(uri); // JDK 1.1.x compat -sc
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endPrefixMapping(String prefix) throws SAXException
{
if (DEBUG)
System.out.println("endPrefixMapping: prefix: " + prefix);
if(null == prefix)
prefix = "";
int index = m_contextIndexes.peek() - 1;
do
{
index = m_prefixMappings.indexOf(prefix, ++index);
} while ( (index >= 0) && ((index & 0x01) == 0x01) );
if (index > -1)
{
m_prefixMappings.setElementAt("%@$#^@#", index);
m_prefixMappings.setElementAt("%@$#^@#", index + 1);
}
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startElement(
String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
if (DEBUG)
{
System.out.println("startElement: uri: " + uri + ", localname: "
+ localName + ", qname: "+qName+", atts: " + attributes);
boolean DEBUG_ATTRS=true;
if(DEBUG_ATTRS & attributes!=null)
{
int n = attributes.getLength();
if(n==0)
System.out.println("\tempty attribute list");
else for (int i = 0; i < n; i++)
System.out.println("\t attr: uri: " + attributes.getURI(i) +
", localname: " + attributes.getLocalName(i) +
", qname: " + attributes.getQName(i) +
", type: " + attributes.getType(i) +
", value: " + attributes.getValue(i)
);
}
}
charactersFlush();
int exName = m_expandedNameTable.getExpandedTypeID(uri, localName, DTM.ELEMENT_NODE);
String prefix = getPrefix(qName, uri);
int prefixIndex = (null != prefix)
? m_valuesOrPrefixes.stringToIndex(qName) : 0;
int elemNode = addNode(DTM.ELEMENT_NODE, exName,
m_parents.peek(), m_previous, prefixIndex, true);
if(m_indexing)
indexNode(exName, elemNode);
m_parents.push(elemNode);
int startDecls = m_contextIndexes.peek();
int nDecls = m_prefixMappings.size();
int prev = DTM.NULL;
if(!m_pastFirstElement)
{
// SPECIAL CASE: Implied declaration at root element
prefix="xml";
String declURL = "http://www.w3.org/XML/1998/namespace";
exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
int val = m_valuesOrPrefixes.stringToIndex(declURL);
prev = addNode(DTM.NAMESPACE_NODE, exName, elemNode,
prev, val, false);
m_pastFirstElement=true;
}
for (int i = startDecls; i < nDecls; i += 2)
{
prefix = (String) m_prefixMappings.elementAt(i);
if (prefix == null)
continue;
String declURL = (String) m_prefixMappings.elementAt(i + 1);
exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
int val = m_valuesOrPrefixes.stringToIndex(declURL);
prev = addNode(DTM.NAMESPACE_NODE, exName, elemNode,
prev, val, false);
}
int n = attributes.getLength();
for (int i = 0; i < n; i++)
{
String attrUri = attributes.getURI(i);
String attrQName = attributes.getQName(i);
String valString = attributes.getValue(i);
prefix = getPrefix(attrQName, attrUri);
int nodeType;
String attrLocalName = attributes.getLocalName(i);
if ((null != attrQName)
&& (attrQName.equals("xmlns")
|| attrQName.startsWith("xmlns:")))
{
if (declAlreadyDeclared(prefix))
continue; // go to the next attribute.
nodeType = DTM.NAMESPACE_NODE;
}
else
{
nodeType = DTM.ATTRIBUTE_NODE;
if (attributes.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(valString, elemNode);
}
// Bit of a hack... if somehow valString is null, stringToIndex will
// return -1, which will make things very unhappy.
if(null == valString)
valString = "";
int val = m_valuesOrPrefixes.stringToIndex(valString);
//String attrLocalName = attributes.getLocalName(i);
if (null != prefix)
{
prefixIndex = m_valuesOrPrefixes.stringToIndex(attrQName);
int dataIndex = m_data.size();
m_data.addElement(prefixIndex);
m_data.addElement(val);
val = -dataIndex;
}
exName = m_expandedNameTable.getExpandedTypeID(attrUri, attrLocalName, nodeType);
prev = addNode(nodeType, exName, elemNode, prev, val,
false);
}
if (DTM.NULL != prev)
m_nextsib.setElementAt(DTM.NULL,prev);
if (null != m_wsfilter)
{
short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(elemNode), this);
boolean shouldStrip = (DTMWSFilter.INHERIT == wsv)
? getShouldStripWhitespace()
: (DTMWSFilter.STRIP == wsv);
pushShouldStripWhitespace(shouldStrip);
}
m_previous = DTM.NULL;
m_contextIndexes.push(m_prefixMappings.size()); // for the children.
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (DEBUG)
System.out.println("endElement: uri: " + uri + ", localname: "
+ localName + ", qname: "+qName);
charactersFlush();
// If no one noticed, startPrefixMapping is a drag.
// Pop the context for the last child (the one pushed by startElement)
m_contextIndexes.quickPop(1);
// Do it again for this one (the one pushed by the last endElement).
int topContextIndex = m_contextIndexes.peek();
if (topContextIndex != m_prefixMappings.size()) {
m_prefixMappings.setSize(topContextIndex);
}
int lastNode = m_previous;
m_previous = m_parents.pop();
// If lastNode is still DTM.NULL, this element had no children
if (DTM.NULL == lastNode)
m_firstch.setElementAt(DTM.NULL,m_previous);
else
m_nextsib.setElementAt(DTM.NULL,lastNode);
popShouldStripWhitespace();
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void characters(char ch[], int start, int length) throws SAXException
{
if (m_textPendingStart == -1) // First one in this block
{
m_textPendingStart = m_chars.size();
m_coalescedTextType = m_textType;
}
// Type logic: If all adjacent text is CDATASections, the
// concatentated text is treated as a single CDATASection (see
// initialization above). If any were ordinary Text, the whole
// thing is treated as Text. This may be worth %REVIEW%ing.
else if (m_textType == DTM.TEXT_NODE)
{
m_coalescedTextType = DTM.TEXT_NODE;
}
m_chars.append(ch, start, length);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException
{
// %OPT% We can probably take advantage of the fact that we know this
// is whitespace.
characters(ch, start, length);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void processingInstruction(String target, String data)
throws SAXException
{
if (DEBUG)
System.out.println("processingInstruction: target: " + target +", data: "+data);
charactersFlush();
int exName = m_expandedNameTable.getExpandedTypeID(null, target,
DTM.PROCESSING_INSTRUCTION_NODE);
int dataIndex = m_valuesOrPrefixes.stringToIndex(data);
m_previous = addNode(DTM.PROCESSING_INSTRUCTION_NODE, exName,
m_parents.peek(), m_previous,
dataIndex, false);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void skippedEntity(String name) throws SAXException
{
// %REVIEW% What should be done here?
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void warning(SAXParseException e) throws SAXException
{
// %REVIEW% Is there anyway to get the JAXP error listener here?
System.err.println(e.getMessage());
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void error(SAXParseException e) throws SAXException
{
throw e;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void fatalError(SAXParseException e) throws SAXException
{
throw e;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void elementDecl(String name, String model) throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void attributeDecl(
String eName, String aName, String type, String valueDefault, String value)
throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void externalEntityDecl(
String name, String publicId, String systemId) throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
m_insideDTD = true;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endDTD() throws SAXException
{
m_insideDTD = false;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startEntity(String name) throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endEntity(String name) throws SAXException
{
// no op
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void startCDATA() throws SAXException
{
m_textType = DTM.CDATA_SECTION_NODE;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void endCDATA() throws SAXException
{
m_textType = DTM.TEXT_NODE;
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM.java
public void comment(char ch[], int start, int length) throws SAXException
{
if (m_insideDTD) // ignore comments if we're inside the DTD
return;
charactersFlush();
int exName = m_expandedNameTable.getExpandedTypeID(DTM.COMMENT_NODE);
// For now, treat comments as strings... I guess we should do a
// seperate FSB buffer instead.
int dataIndex = m_valuesOrPrefixes.stringToIndex(new String(ch, start,
length));
m_previous = addNode(DTM.COMMENT_NODE, exName,
m_parents.peek(), m_previous, dataIndex, false);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
charactersFlush();
int exName = m_expandedNameTable.getExpandedTypeID(uri, localName, DTM.ELEMENT_NODE);
int prefixIndex = (qName.length() != localName.length())
? m_valuesOrPrefixes.stringToIndex(qName) : 0;
int elemNode = addNode(DTM.ELEMENT_NODE, exName,
m_parents.peek(), m_previous, prefixIndex, true);
if(m_indexing)
indexNode(exName, elemNode);
m_parents.push(elemNode);
int startDecls = m_contextIndexes.peek();
int nDecls = m_prefixMappings.size();
String prefix;
if(!m_pastFirstElement)
{
// SPECIAL CASE: Implied declaration at root element
prefix="xml";
String declURL = "http://www.w3.org/XML/1998/namespace";
exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
m_values.addElement(declURL);
int val = m_valueIndex++;
addNode(DTM.NAMESPACE_NODE, exName, elemNode,
DTM.NULL, val, false);
m_pastFirstElement=true;
}
for (int i = startDecls; i < nDecls; i += 2)
{
prefix = (String) m_prefixMappings.elementAt(i);
if (prefix == null)
continue;
String declURL = (String) m_prefixMappings.elementAt(i + 1);
exName = m_expandedNameTable.getExpandedTypeID(null, prefix, DTM.NAMESPACE_NODE);
m_values.addElement(declURL);
int val = m_valueIndex++;
addNode(DTM.NAMESPACE_NODE, exName, elemNode, DTM.NULL, val, false);
}
int n = attributes.getLength();
for (int i = 0; i < n; i++)
{
String attrUri = attributes.getURI(i);
String attrQName = attributes.getQName(i);
String valString = attributes.getValue(i);
int nodeType;
String attrLocalName = attributes.getLocalName(i);
if ((null != attrQName)
&& (attrQName.equals("xmlns")
|| attrQName.startsWith("xmlns:")))
{
prefix = getPrefix(attrQName, attrUri);
if (declAlreadyDeclared(prefix))
continue; // go to the next attribute.
nodeType = DTM.NAMESPACE_NODE;
}
else
{
nodeType = DTM.ATTRIBUTE_NODE;
if (m_buildIdIndex && attributes.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(valString, elemNode);
}
// Bit of a hack... if somehow valString is null, stringToIndex will
// return -1, which will make things very unhappy.
if(null == valString)
valString = "";
m_values.addElement(valString);
int val = m_valueIndex++;
if (attrLocalName.length() != attrQName.length())
{
prefixIndex = m_valuesOrPrefixes.stringToIndex(attrQName);
int dataIndex = m_data.size();
m_data.addElement(prefixIndex);
m_data.addElement(val);
val = -dataIndex;
}
exName = m_expandedNameTable.getExpandedTypeID(attrUri, attrLocalName, nodeType);
addNode(nodeType, exName, elemNode, DTM.NULL, val,
false);
}
if (null != m_wsfilter)
{
short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(elemNode), this);
boolean shouldStrip = (DTMWSFilter.INHERIT == wsv)
? getShouldStripWhitespace()
: (DTMWSFilter.STRIP == wsv);
pushShouldStripWhitespace(shouldStrip);
}
m_previous = DTM.NULL;
m_contextIndexes.push(m_prefixMappings.size()); // for the children.
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
charactersFlush();
// If no one noticed, startPrefixMapping is a drag.
// Pop the context for the last child (the one pushed by startElement)
m_contextIndexes.quickPop(1);
// Do it again for this one (the one pushed by the last endElement).
int topContextIndex = m_contextIndexes.peek();
if (topContextIndex != m_prefixMappings.size()) {
m_prefixMappings.setSize(topContextIndex);
}
m_previous = m_parents.pop();
popShouldStripWhitespace();
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void comment(char ch[], int start, int length) throws SAXException
{
if (m_insideDTD) // ignore comments if we're inside the DTD
return;
charactersFlush();
// %OPT% Saving the comment string in a Vector has a lower cost than
// saving it in DTMStringPool.
m_values.addElement(new String(ch, start, length));
int dataIndex = m_valueIndex++;
m_previous = addNode(DTM.COMMENT_NODE, DTM.COMMENT_NODE,
m_parents.peek(), m_previous, dataIndex, false);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void startDocument() throws SAXException
{
int doc = addNode(DTM.DOCUMENT_NODE,
DTM.DOCUMENT_NODE,
DTM.NULL, DTM.NULL, 0, true);
m_parents.push(doc);
m_previous = DTM.NULL;
m_contextIndexes.push(m_prefixMappings.size()); // for the next element.
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void endDocument() throws SAXException
{
super.endDocument();
// Add a NULL entry to the end of the node arrays as
// the end indication.
m_exptype.addElement(NULL);
m_parent.addElement(NULL);
m_nextsib.addElement(NULL);
m_firstch.addElement(NULL);
// Set the cached references after the document is built.
m_extendedTypes = m_expandedNameTable.getExtendedTypes();
m_exptype_map = m_exptype.getMap();
m_nextsib_map = m_nextsib.getMap();
m_firstch_map = m_firstch.getMap();
m_parent_map = m_parent.getMap();
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public void processingInstruction(String target, String data)
throws SAXException
{
charactersFlush();
int dataIndex = m_data.size();
m_previous = addNode(DTM.PROCESSING_INSTRUCTION_NODE,
DTM.PROCESSING_INSTRUCTION_NODE,
m_parents.peek(), m_previous,
-dataIndex, false);
m_data.addElement(m_valuesOrPrefixes.stringToIndex(target));
m_values.addElement(data);
m_data.addElement(m_valueIndex++);
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
public final void dispatchCharactersEvents(int nodeHandle, ContentHandler ch,
boolean normalize)
throws SAXException
{
int identity = makeNodeIdentity(nodeHandle);
if (identity == DTM.NULL)
return;
int type = _type2(identity);
if (type == DTM.ELEMENT_NODE || type == DTM.DOCUMENT_NODE)
{
int startNode = identity;
identity = _firstch2(identity);
if (DTM.NULL != identity)
{
int offset = -1;
int length = 0;
do
{
type = _exptype2(identity);
if (type == DTM.TEXT_NODE || type == DTM.CDATA_SECTION_NODE)
{
int dataIndex = m_dataOrQName.elementAt(identity);
if (dataIndex >= 0)
{
if (-1 == offset)
{
offset = dataIndex >>> TEXT_LENGTH_BITS;
}
length += dataIndex & TEXT_LENGTH_MAX;
}
else
{
if (-1 == offset)
{
offset = m_data.elementAt(-dataIndex);
}
length += m_data.elementAt(-dataIndex + 1);
}
}
identity++;
} while (_parent2(identity) >= startNode);
if (length > 0)
{
if(normalize)
m_chars.sendNormalizedSAXcharacters(ch, offset, length);
else
m_chars.sendSAXcharacters(ch, offset, length);
}
}
}
else if (DTM.TEXT_NODE == type || DTM.CDATA_SECTION_NODE == type)
{
int dataIndex = m_dataOrQName.elementAt(identity);
if (dataIndex >= 0)
{
if (normalize)
m_chars.sendNormalizedSAXcharacters(ch, dataIndex >>> TEXT_LENGTH_BITS,
dataIndex & TEXT_LENGTH_MAX);
else
m_chars.sendSAXcharacters(ch, dataIndex >>> TEXT_LENGTH_BITS,
dataIndex & TEXT_LENGTH_MAX);
}
else
{
if (normalize)
m_chars.sendNormalizedSAXcharacters(ch, m_data.elementAt(-dataIndex),
m_data.elementAt(-dataIndex+1));
else
m_chars.sendSAXcharacters(ch, m_data.elementAt(-dataIndex),
m_data.elementAt(-dataIndex+1));
}
}
else
{
int dataIndex = m_dataOrQName.elementAt(identity);
if (dataIndex < 0)
{
dataIndex = -dataIndex;
dataIndex = m_data.elementAt(dataIndex + 1);
}
String str = (String)m_values.elementAt(dataIndex);
if(normalize)
FastStringBuffer.sendNormalizedSAXcharacters(str.toCharArray(),
0, str.length(), ch);
else
ch.characters(str.toCharArray(), 0, str.length());
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
protected final void copyTextNode(final int nodeID, SerializationHandler handler)
throws SAXException
{
if (nodeID != DTM.NULL) {
int dataIndex = m_dataOrQName.elementAt(nodeID);
if (dataIndex >= 0) {
m_chars.sendSAXcharacters(handler,
dataIndex >>> TEXT_LENGTH_BITS,
dataIndex & TEXT_LENGTH_MAX);
} else {
m_chars.sendSAXcharacters(handler, m_data.elementAt(-dataIndex),
m_data.elementAt(-dataIndex+1));
}
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
protected final String copyElement(int nodeID, int exptype,
SerializationHandler handler)
throws SAXException
{
final ExtendedType extType = m_extendedTypes[exptype];
String uri = extType.getNamespace();
String name = extType.getLocalName();
if (uri.length() == 0) {
handler.startElement(name);
return name;
}
else {
int qnameIndex = m_dataOrQName.elementAt(nodeID);
if (qnameIndex == 0) {
handler.startElement(name);
handler.namespaceAfterStartElement(EMPTY_STR, uri);
return name;
}
if (qnameIndex < 0) {
qnameIndex = -qnameIndex;
qnameIndex = m_data.elementAt(qnameIndex);
}
String qName = m_valuesOrPrefixes.indexToString(qnameIndex);
handler.startElement(qName);
int prefixIndex = qName.indexOf(':');
String prefix;
if (prefixIndex > 0) {
prefix = qName.substring(0, prefixIndex);
}
else {
prefix = null;
}
handler.namespaceAfterStartElement(prefix, uri);
return qName;
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
protected final void copyNS(final int nodeID, SerializationHandler handler, boolean inScope)
throws SAXException
{
// %OPT% Optimization for documents which does not have any explicit
// namespace nodes. For these documents, there is an implicit
// namespace node (xmlns:xml="http://www.w3.org/XML/1998/namespace")
// declared on the root element node. In this case, there is no
// need to do namespace copying. We can safely return without
// doing anything.
if (m_namespaceDeclSetElements != null &&
m_namespaceDeclSetElements.size() == 1 &&
m_namespaceDeclSets != null &&
((SuballocatedIntVector)m_namespaceDeclSets.elementAt(0))
.size() == 1)
return;
SuballocatedIntVector nsContext = null;
int nextNSNode;
// Find the first namespace node
if (inScope) {
nsContext = findNamespaceContext(nodeID);
if (nsContext == null || nsContext.size() < 1)
return;
else
nextNSNode = makeNodeIdentity(nsContext.elementAt(0));
}
else
nextNSNode = getNextNamespaceNode2(nodeID);
int nsIndex = 1;
while (nextNSNode != DTM.NULL) {
// Retrieve the name of the namespace node
int eType = _exptype2(nextNSNode);
String nodeName = m_extendedTypes[eType].getLocalName();
// Retrieve the node value of the namespace node
int dataIndex = m_dataOrQName.elementAt(nextNSNode);
if (dataIndex < 0) {
dataIndex = -dataIndex;
dataIndex = m_data.elementAt(dataIndex + 1);
}
String nodeValue = (String)m_values.elementAt(dataIndex);
handler.namespaceAfterStartElement(nodeName, nodeValue);
if (inScope) {
if (nsIndex < nsContext.size()) {
nextNSNode = makeNodeIdentity(nsContext.elementAt(nsIndex));
nsIndex++;
}
else
return;
}
else
nextNSNode = getNextNamespaceNode2(nextNSNode);
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
protected final void copyAttributes(final int nodeID, SerializationHandler handler)
throws SAXException{
for(int current = getFirstAttributeIdentity(nodeID); current != DTM.NULL; current = getNextAttributeIdentity(current)){
int eType = _exptype2(current);
copyAttribute(current, eType, handler);
}
}
// in src/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java
protected final void copyAttribute(int nodeID, int exptype,
SerializationHandler handler)
throws SAXException
{
/*
final String uri = getNamespaceName(node);
if (uri.length() != 0) {
final String prefix = getPrefix(node);
handler.namespaceAfterStartElement(prefix, uri);
}
handler.addAttribute(getNodeName(node), getNodeValue(node));
*/
final ExtendedType extType = m_extendedTypes[exptype];
final String uri = extType.getNamespace();
final String localName = extType.getLocalName();
String prefix = null;
String qname = null;
int dataIndex = _dataOrQName(nodeID);
int valueIndex = dataIndex;
if (dataIndex <= 0) {
int prefixIndex = m_data.elementAt(-dataIndex);
valueIndex = m_data.elementAt(-dataIndex+1);
qname = m_valuesOrPrefixes.indexToString(prefixIndex);
int colonIndex = qname.indexOf(':');
if (colonIndex > 0) {
prefix = qname.substring(0, colonIndex);
}
}
if (uri.length() != 0) {
handler.namespaceAfterStartElement(prefix, uri);
}
String nodeName = (prefix != null) ? qname : localName;
String nodeValue = (String)m_values.elementAt(valueIndex);
handler.addAttribute(nodeName, nodeValue);
}
// in src/org/apache/xml/serializer/TreeWalker.java
public void traverse(Node pos) throws org.xml.sax.SAXException
{
this.m_contentHandler.startDocument();
Node top = pos;
while (null != pos)
{
startNode(pos);
Node nextNode = pos.getFirstChild();
while (null == nextNode)
{
endNode(pos);
if (top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode)
{
pos = pos.getParentNode();
if ((null == pos) || (top.equals(pos)))
{
if (null != pos)
endNode(pos);
nextNode = null;
break;
}
}
}
pos = nextNode;
}
this.m_contentHandler.endDocument();
}
// in src/org/apache/xml/serializer/TreeWalker.java
public void traverse(Node pos, Node top) throws org.xml.sax.SAXException
{
this.m_contentHandler.startDocument();
while (null != pos)
{
startNode(pos);
Node nextNode = pos.getFirstChild();
while (null == nextNode)
{
endNode(pos);
if ((null != top) && top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode)
{
pos = pos.getParentNode();
if ((null == pos) || ((null != top) && top.equals(pos)))
{
nextNode = null;
break;
}
}
}
pos = nextNode;
}
this.m_contentHandler.endDocument();
}
// in src/org/apache/xml/serializer/TreeWalker.java
private final void dispatachChars(Node node)
throws org.xml.sax.SAXException
{
if(m_Serializer != null)
{
this.m_Serializer.characters(node);
}
else
{
String data = ((Text) node).getData();
this.m_contentHandler.characters(data.toCharArray(), 0, data.length());
}
}
// in src/org/apache/xml/serializer/TreeWalker.java
protected void startNode(Node node) throws org.xml.sax.SAXException
{
// TODO: <REVIEW>
// A Serializer implements ContentHandler, but not NodeConsumer
// so drop this reference to NodeConsumer which would otherwise
// pull in all sorts of things
// if (m_contentHandler instanceof NodeConsumer)
// {
// ((NodeConsumer) m_contentHandler).setOriginatingNode(node);
// }
// TODO: </REVIEW>
if (node instanceof Locator)
{
Locator loc = (Locator)node;
m_locator.setColumnNumber(loc.getColumnNumber());
m_locator.setLineNumber(loc.getLineNumber());
m_locator.setPublicId(loc.getPublicId());
m_locator.setSystemId(loc.getSystemId());
}
else
{
m_locator.setColumnNumber(0);
m_locator.setLineNumber(0);
}
switch (node.getNodeType())
{
case Node.COMMENT_NODE :
{
String data = ((Comment) node).getData();
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.comment(data.toCharArray(), 0, data.length());
}
}
break;
case Node.DOCUMENT_FRAGMENT_NODE :
// ??;
break;
case Node.DOCUMENT_NODE :
break;
case Node.ELEMENT_NODE :
Element elem_node = (Element) node;
{
// Make sure the namespace node
// for the element itself is declared
// to the ContentHandler
String uri = elem_node.getNamespaceURI();
if (uri != null) {
String prefix = elem_node.getPrefix();
if (prefix==null)
prefix="";
this.m_contentHandler.startPrefixMapping(prefix,uri);
}
}
NamedNodeMap atts = elem_node.getAttributes();
int nAttrs = atts.getLength();
// System.out.println("TreeWalker#startNode: "+node.getNodeName());
// Make sure the namespace node of
// each attribute is declared to the ContentHandler
for (int i = 0; i < nAttrs; i++)
{
final Node attr = atts.item(i);
final String attrName = attr.getNodeName();
final int colon = attrName.indexOf(':');
final String prefix;
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:"))
{
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
if (colon < 0)
prefix = "";
else
prefix = attrName.substring(colon + 1);
this.m_contentHandler.startPrefixMapping(prefix,
attr.getNodeValue());
}
else if (colon > 0) {
prefix = attrName.substring(0,colon);
String uri = attr.getNamespaceURI();
if (uri != null)
this.m_contentHandler.startPrefixMapping(prefix,uri);
}
}
String ns = m_dh.getNamespaceOfNode(node);
if(null == ns)
ns = "";
this.m_contentHandler.startElement(ns,
m_dh.getLocalNameOfNode(node),
node.getNodeName(),
new AttList(atts, m_dh));
break;
case Node.PROCESSING_INSTRUCTION_NODE :
{
ProcessingInstruction pi = (ProcessingInstruction) node;
String name = pi.getNodeName();
// String data = pi.getData();
if (name.equals("xslt-next-is-raw"))
{
nextIsRaw = true;
}
else
{
this.m_contentHandler.processingInstruction(pi.getNodeName(),
pi.getData());
}
}
break;
case Node.CDATA_SECTION_NODE :
{
boolean isLexH = (m_contentHandler instanceof LexicalHandler);
LexicalHandler lh = isLexH
? ((LexicalHandler) this.m_contentHandler) : null;
if (isLexH)
{
lh.startCDATA();
}
dispatachChars(node);
{
if (isLexH)
{
lh.endCDATA();
}
}
}
break;
case Node.TEXT_NODE :
{
//String data = ((Text) node).getData();
if (nextIsRaw)
{
nextIsRaw = false;
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
dispatachChars(node);
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
}
else
{
dispatachChars(node);
}
}
break;
case Node.ENTITY_REFERENCE_NODE :
{
EntityReference eref = (EntityReference) node;
if (m_contentHandler instanceof LexicalHandler)
{
((LexicalHandler) this.m_contentHandler).startEntity(
eref.getNodeName());
}
else
{
// warning("Can not output entity to a pure SAX ContentHandler");
}
}
break;
default :
}
}
// in src/org/apache/xml/serializer/TreeWalker.java
protected void endNode(Node node) throws org.xml.sax.SAXException
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE :
break;
case Node.ELEMENT_NODE :
String ns = m_dh.getNamespaceOfNode(node);
if(null == ns)
ns = "";
this.m_contentHandler.endElement(ns,
m_dh.getLocalNameOfNode(node),
node.getNodeName());
if (m_Serializer == null) {
// Don't bother with endPrefixMapping calls if the ContentHandler is a
// SerializationHandler because SerializationHandler's ignore the
// endPrefixMapping() calls anyways. . . . This is an optimization.
Element elem_node = (Element) node;
NamedNodeMap atts = elem_node.getAttributes();
int nAttrs = atts.getLength();
// do the endPrefixMapping calls in reverse order
// of the startPrefixMapping calls
for (int i = (nAttrs-1); 0 <= i; i--)
{
final Node attr = atts.item(i);
final String attrName = attr.getNodeName();
final int colon = attrName.indexOf(':');
final String prefix;
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:"))
{
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
if (colon < 0)
prefix = "";
else
prefix = attrName.substring(colon + 1);
this.m_contentHandler.endPrefixMapping(prefix);
}
else if (colon > 0) {
prefix = attrName.substring(0, colon);
this.m_contentHandler.endPrefixMapping(prefix);
}
}
{
String uri = elem_node.getNamespaceURI();
if (uri != null) {
String prefix = elem_node.getPrefix();
if (prefix==null)
prefix="";
this.m_contentHandler.endPrefixMapping(prefix);
}
}
}
break;
case Node.CDATA_SECTION_NODE :
break;
case Node.ENTITY_REFERENCE_NODE :
{
EntityReference eref = (EntityReference) node;
if (m_contentHandler instanceof LexicalHandler)
{
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.endEntity(eref.getNodeName());
}
}
break;
default :
}
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void indent(int n) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public boolean setEscaping(boolean escape) throws SAXException
{
boolean oldEscapeSetting = m_escapeSetting;
m_escapeSetting = escape;
if (escape) {
processingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "");
} else {
processingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "");
}
return oldEscapeSetting;
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void attributeDecl(
String arg0,
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void elementDecl(String arg0, String arg1) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void externalEntityDecl(String arg0, String arg1, String arg2)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void internalEntityDecl(String arg0, String arg1)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endDocument() throws SAXException
{
flushPending();
// Close output document
m_saxHandler.endDocument();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
protected void closeStartTag() throws SAXException
{
m_elemContext.m_startTagOpen = false;
final String localName = getLocalName(m_elemContext.m_elementName);
final String uri = getNamespaceURI(m_elemContext.m_elementName, true);
// Now is time to send the startElement event
if (m_needToCallStartDocument)
{
startDocumentInternal();
}
m_saxHandler.startElement(uri, localName, m_elemContext.m_elementName, m_attributes);
// we've sent the official SAX attributes on their way,
// now we don't need them anymore.
m_attributes.clear();
if(m_state != null)
m_state.setCurrentNode(null);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void closeCDATA() throws SAXException
{
// Output closing bracket - "]]>"
if (m_lexHandler != null && m_cdataTagOpen) {
m_lexHandler.endCDATA();
}
// There are no longer any calls made to
// m_lexHandler.startCDATA() without a balancing call to
// m_lexHandler.endCDATA()
// so we set m_cdataTagOpen to false to remember this.
m_cdataTagOpen = false;
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException
{
// Close any open elements etc.
flushPending();
if (namespaceURI == null)
{
if (m_elemContext.m_elementURI != null)
namespaceURI = m_elemContext.m_elementURI;
else
namespaceURI = getNamespaceURI(qName, true);
}
if (localName == null)
{
if (m_elemContext.m_elementLocalName != null)
localName = m_elemContext.m_elementLocalName;
else
localName = getLocalName(qName);
}
m_saxHandler.endElement(namespaceURI, localName, qName);
if (m_tracer != null)
super.fireEndElem(qName);
/* Pop all namespaces at the current element depth.
* We are not waiting for official endPrefixMapping() calls.
*/
m_prefixMap.popNamespaces(m_elemContext.m_currentElemDepth,
m_saxHandler);
m_elemContext = m_elemContext.m_prev;
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endPrefixMapping(String prefix) throws SAXException
{
/* poping all prefix mappings should have been done
* in endElement() already
*/
return;
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
throws SAXException
{
m_saxHandler.ignorableWhitespace(arg0,arg1,arg2);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void skippedEntity(String arg0) throws SAXException
{
m_saxHandler.skippedEntity(arg0);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
startPrefixMapping(prefix, uri, true);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws org.xml.sax.SAXException
{
/* Remember the mapping, and at what depth it was declared
* This is one greater than the current depth because these
* mappings will apply to the next depth. This is in
* consideration that startElement() will soon be called
*/
boolean pushed;
int pushDepth;
if (shouldFlush)
{
flushPending();
// the prefix mapping applies to the child element (one deeper)
pushDepth = m_elemContext.m_currentElemDepth + 1;
}
else
{
// the prefix mapping applies to the current element
pushDepth = m_elemContext.m_currentElemDepth;
}
pushed = m_prefixMap.pushNamespace(prefix, uri, pushDepth);
if (pushed)
{
m_saxHandler.startPrefixMapping(prefix,uri);
if (getShouldOutputNSAttr())
{
/* I don't know if we really needto do this. The
* callers of this object should have injected both
* startPrefixMapping and the attributes. We are
* just covering our butt here.
*/
String name;
if (EMPTYSTRING.equals(prefix))
{
name = "xmlns";
addAttributeAlways(XMLNS_URI, name, name,"CDATA",uri, false);
}
else
{
if (!EMPTYSTRING.equals(uri)) // hack for attribset16 test
{ // that maps ns1 prefix to "" URI
name = "xmlns:" + prefix;
/* for something like xmlns:abc="w3.pretend.org"
* the uri is the value, that is why we pass it in the
* value, or 5th slot of addAttributeAlways()
*/
addAttributeAlways(XMLNS_URI, prefix, name,"CDATA",uri, false );
}
}
}
}
return pushed;
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void comment(char[] arg0, int arg1, int arg2) throws SAXException
{
flushPending();
if (m_lexHandler != null)
m_lexHandler.comment(arg0, arg1, arg2);
if (m_tracer != null)
super.fireCommentEvent(arg0, arg1, arg2);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endCDATA() throws SAXException
{
/* Normally we would do somthing with this but we ignore it.
* The neccessary call to m_lexHandler.endCDATA() will be made
* in flushPending().
*
* This is so that if we get calls like these:
* this.startCDATA();
* this.characters(chars1, off1, len1);
* this.endCDATA();
* this.startCDATA();
* this.characters(chars2, off2, len2);
* this.endCDATA();
*
* that we will only make these calls to the wrapped handlers:
*
* m_lexHandler.startCDATA();
* m_saxHandler.characters(chars1, off1, len1);
* m_saxHandler.characters(chars1, off2, len2);
* m_lexHandler.endCDATA();
*
* We will merge adjacent CDATA blocks.
*/
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endDTD() throws SAXException
{
if (m_lexHandler != null)
m_lexHandler.endDTD();
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startEntity(String arg0) throws SAXException
{
if (m_lexHandler != null)
m_lexHandler.startEntity(arg0);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void characters(String chars) throws SAXException
{
final int length = chars.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
chars.getChars(0, length, m_charsBuff, 0);
this.characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName) throws SAXException
{
startElement(
elementNamespaceURI,elementLocalName,elementName, null);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startElement(String elementName) throws SAXException
{
startElement(null, null, elementName, null);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void characters(char[] ch, int off, int len) throws SAXException
{
// We do the first two things in flushPending() but we don't
// close any open CDATA calls.
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
if (m_elemContext.m_isCdataSection && !m_cdataTagOpen
&& m_lexHandler != null)
{
m_lexHandler.startCDATA();
// We have made a call to m_lexHandler.startCDATA() with
// no balancing call to m_lexHandler.endCDATA()
// so we set m_cdataTagOpen true to remember this.
m_cdataTagOpen = true;
}
/* If there are any occurances of "]]>" in the character data
* let m_saxHandler worry about it, we've already warned them with
* the previous call of m_lexHandler.startCDATA();
*/
m_saxHandler.characters(ch, off, len);
// time to generate characters event
if (m_tracer != null)
fireCharEvent(ch, off, len);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void endElement(String elemName) throws SAXException
{
endElement(null, null, elemName);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
startPrefixMapping(prefix,uri,false);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void processingInstruction(String target, String data)
throws SAXException
{
flushPending();
// Pass the processing instruction to the SAX handler
m_saxHandler.processingInstruction(target, data);
// we don't want to leave serializer to fire off this event,
// so do it here.
if (m_tracer != null)
super.fireEscapingEvent(target, data);
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startCDATA() throws SAXException
{
/* m_cdataTagOpen can only be true here if we have ignored the
* previous call to this.endCDATA() and the previous call
* this.startCDATA() before that is still "open". In this way
* we merge adjacent CDATA. If anything else happened after the
* ignored call to this.endCDATA() and this call then a call to
* flushPending() would have been made which would have
* closed the CDATA and set m_cdataTagOpen to false.
*/
if (!m_cdataTagOpen )
{
flushPending();
if (m_lexHandler != null) {
m_lexHandler.startCDATA();
// We have made a call to m_lexHandler.startCDATA() with
// no balancing call to m_lexHandler.endCDATA()
// so we set m_cdataTagOpen true to remember this.
m_cdataTagOpen = true;
}
}
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void startElement(
String namespaceURI,
String localName,
String name,
Attributes atts)
throws SAXException
{
flushPending();
super.startElement(namespaceURI, localName, name, atts);
// Handle document type declaration (for first element only)
if (m_needToOutputDocTypeDecl)
{
String doctypeSystem = getDoctypeSystem();
if (doctypeSystem != null && m_lexHandler != null)
{
String doctypePublic = getDoctypePublic();
if (doctypeSystem != null)
m_lexHandler.startDTD(
name,
doctypePublic,
doctypeSystem);
}
m_needToOutputDocTypeDecl = false;
}
m_elemContext = m_elemContext.push(namespaceURI, localName, name);
// ensurePrefixIsDeclared depends on the current depth, so
// the previous increment is necessary where it is.
if (namespaceURI != null)
ensurePrefixIsDeclared(namespaceURI, name);
// add the attributes to the collected ones
if (atts != null)
addAttributes(atts);
// do we really need this CDATA section state?
m_elemContext.m_isCdataSection = isCdataSection();
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
private void ensurePrefixIsDeclared(String ns, String rawName)
throws org.xml.sax.SAXException
{
if (ns != null && ns.length() > 0)
{
int index;
final boolean no_prefix = ((index = rawName.indexOf(":")) < 0);
String prefix = (no_prefix) ? "" : rawName.substring(0, index);
if (null != prefix)
{
String foundURI = m_prefixMap.lookupNamespace(prefix);
if ((null == foundURI) || !foundURI.equals(ns))
{
this.startPrefixMapping(prefix, ns, false);
if (getShouldOutputNSAttr()) {
// Bugzilla1133: Generate attribute as well as namespace event.
// SAX does expect both.
this.addAttributeAlways(
"http://www.w3.org/2000/xmlns/",
no_prefix ? "xmlns" : prefix, // local name
no_prefix ? "xmlns" : ("xmlns:"+ prefix), // qname
"CDATA",
ns,
false);
}
}
}
}
}
// in src/org/apache/xml/serializer/ToXMLSAXHandler.java
public void addAttribute(
String uri,
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
ensurePrefixIsDeclared(uri, rawName);
addAttributeAlways(uri, localName, rawName, type, value, false);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireEndElem(String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireCharEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void comment(String data) throws SAXException
{
m_docIsEmpty = false;
final int length = data.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length * 2 + 1];
}
data.getChars(0, length, m_charsBuff, 0);
comment(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void addAttribute(
String uri,
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void addAttributes(Attributes atts) throws SAXException
{
int nAtts = atts.getLength();
for (int i = 0; i < nAtts; i++)
{
String uri = atts.getURI(i);
if (null == uri)
uri = "";
addAttributeAlways(
uri,
atts.getLocalName(i),
atts.getQName(i),
atts.getType(i),
atts.getValue(i),
false);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void endEntity(String name) throws org.xml.sax.SAXException
{
if (name.equals("[dtd]"))
m_inExternalDTD = false;
m_inEntityRef = false;
if (m_tracer != null)
this.fireEndEntity(name);
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void namespaceAfterStartElement(String uri, String prefix)
throws SAXException
{
// default behavior is to do nothing
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void entityReference(String name) throws org.xml.sax.SAXException
{
flushPending();
startEntity(name);
endEntity(name);
if (m_tracer != null)
fireEntityReference(name);
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void characters(org.w3c.dom.Node node)
throws org.xml.sax.SAXException
{
flushPending();
String data = node.getNodeValue();
if (data != null)
{
final int length = data.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length * 2 + 1];
}
data.getChars(0, length, m_charsBuff, 0);
characters(m_charsBuff, 0, length);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void error(SAXParseException exc) throws SAXException {
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void fatalError(SAXParseException exc) throws SAXException {
m_elemContext.m_startTagOpen = false;
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void warning(SAXParseException exc) throws SAXException
{
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireStartEntity(String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENTITYREF, name);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireCDATAEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireCommentEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length));
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void fireEndEntity(String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
flushMyWriter();
// we do not need to handle this.
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireStartDoc()
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_STARTDOCUMENT);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireEndDoc()
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDDOCUMENT);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireStartElem(String elemName)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_STARTELEMENT,
elemName, m_attributes);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireEscapingEvent(String name, String data)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_PI,name, data);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void fireEntityReference(String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENTITYREF,name, (Attributes)null);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void startDocument() throws org.xml.sax.SAXException
{
// if we do get called with startDocument(), handle it right away
startDocumentInternal();
m_needToCallStartDocument = false;
return;
}
// in src/org/apache/xml/serializer/SerializerBase.java
protected void startDocumentInternal() throws org.xml.sax.SAXException
{
if (m_tracer != null)
this.fireStartDoc();
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
addAttributeAlways(uri, localName, rawName, type, value, false);
}
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void notationDecl(String arg0, String arg1, String arg2)
throws SAXException {
// This method just provides a definition to satisfy the interface
// A particular sub-class of SerializerBase provides the implementation (if desired)
}
// in src/org/apache/xml/serializer/SerializerBase.java
public void unparsedEntityDecl(
String arg0,
String arg1,
String arg2,
String arg3)
throws SAXException {
// This method just provides a definition to satisfy the interface
// A particular sub-class of SerializerBase provides the implementation (if desired)
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void startDocumentInternal() throws org.xml.sax.SAXException
{
if (m_needToCallStartDocument)
{
super.startDocumentInternal();
m_needToCallStartDocument = false;
if (m_inEntityRef)
return;
m_needToOutputDocTypeDecl = true;
m_startNewLine = false;
/* The call to getXMLVersion() might emit an error message
* and we should emit this message regardless of if we are
* writing out an XML header or not.
*/
final String version = getXMLVersion();
if (getOmitXMLDeclaration() == false)
{
String encoding = Encodings.getMimeEncoding(getEncoding());
String standalone;
if (m_standaloneWasSpecified)
{
standalone = " standalone=\"" + getStandalone() + "\"";
}
else
{
standalone = "";
}
try
{
final java.io.Writer writer = m_writer;
writer.write("<?xml version=\"");
writer.write(version);
writer.write("\" encoding=\"");
writer.write(encoding);
writer.write('\"');
writer.write(standalone);
writer.write("?>");
if (m_doIndent) {
if (m_standaloneWasSpecified
|| getDoctypePublic() != null
|| getDoctypeSystem() != null) {
// We almost never put a newline after the XML
// header because this XML could be used as
// an extenal general parsed entity
// and we don't know the context into which it
// will be used in the future. Only when
// standalone, or a doctype system or public is
// specified are we free to insert a new line
// after the header. Is it even worth bothering
// in these rare cases?
writer.write(m_lineSep, 0, m_lineSepLen);
}
}
}
catch(IOException e)
{
throw new SAXException(e);
}
}
}
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void endDocument() throws org.xml.sax.SAXException
{
flushPending();
if (m_doIndent && !m_isprevtext)
{
try
{
outputLineSep();
}
catch(IOException e)
{
throw new SAXException(e);
}
}
flushWriter();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void startPreserving() throws org.xml.sax.SAXException
{
// Not sure this is really what we want. -sb
m_preserves.push(true);
m_ispreserve = true;
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void endPreserving() throws org.xml.sax.SAXException
{
// Not sure this is really what we want. -sb
m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop();
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
if (m_inEntityRef)
return;
flushPending();
if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING))
{
startNonEscaping();
}
else if (target.equals(Result.PI_ENABLE_OUTPUT_ESCAPING))
{
endNonEscaping();
}
else
{
try
{
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
else if (m_needToCallStartDocument)
startDocumentInternal();
if (shouldIndent())
indent();
final java.io.Writer writer = m_writer;
writer.write("<?");
writer.write(target);
if (data.length() > 0
&& !Character.isSpaceChar(data.charAt(0)))
writer.write(' ');
int indexOfQLT = data.indexOf("?>");
if (indexOfQLT >= 0)
{
// See XSLT spec on error recovery of "?>" in PIs.
if (indexOfQLT > 0)
{
writer.write(data.substring(0, indexOfQLT));
}
writer.write("? >"); // add space between.
if ((indexOfQLT + 2) < data.length())
{
writer.write(data.substring(indexOfQLT + 2));
}
}
else
{
writer.write(data);
}
writer.write('?');
writer.write('>');
/*
* Don't write out any indentation whitespace now,
* because there may be non-whitespace text after this.
*
* Simply mark that at this point if we do decide
* to indent that we should
* add a newline on the end of the current line before
* the indentation at the start of the next line.
*/
m_startNewLine = true;
}
catch(IOException e)
{
throw new SAXException(e);
}
}
if (m_tracer != null)
super.fireEscapingEvent(target, data);
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void entityReference(String name) throws org.xml.sax.SAXException
{
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
try
{
if (shouldIndent())
indent();
final java.io.Writer writer = m_writer;
writer.write('&');
writer.write(name);
writer.write(';');
}
catch(IOException e)
{
throw new SAXException(e);
}
if (m_tracer != null)
super.fireEntityReference(name);
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void addUniqueAttribute(String name, String value, int flags)
throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
try
{
final String patchedName = patchName(name);
final java.io.Writer writer = m_writer;
if ((flags & NO_BAD_CHARS) > 0 && m_xmlcharInfo.onlyQuotAmpLtGt)
{
// "flags" has indicated that the characters
// '>' '<' '&' and '"' are not in the value and
// m_htmlcharInfo has recorded that there are no other
// entities in the range 32 to 127 so we write out the
// value directly
writer.write(' ');
writer.write(patchedName);
writer.write("=\"");
writer.write(value);
writer.write('"');
}
else
{
writer.write(' ');
writer.write(patchedName);
writer.write("=\"");
writeAttrString(writer, value, this.getEncoding());
writer.write('"');
}
} catch (IOException e) {
throw new SAXException(e);
}
}
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void addAttribute(
String uri,
String localName,
String rawName,
String type,
String value,
boolean xslAttribute)
throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
boolean was_added = addAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
/*
* We don't run this block of code if:
* 1. The attribute value was only replaced (was_added is false).
* 2. The attribute is from an xsl:attribute element (that is handled
* in the addAttributeAlways() call just above.
* 3. The name starts with "xmlns", i.e. it is a namespace declaration.
*/
if (was_added && !xslAttribute && !rawName.startsWith("xmlns"))
{
String prefixUsed =
ensureAttributesNamespaceIsDeclared(
uri,
localName,
rawName);
if (prefixUsed != null
&& rawName != null
&& !rawName.startsWith(prefixUsed))
{
// use a different raw name, with the prefix used in the
// generated namespace declaration
rawName = prefixUsed + ":" + localName;
}
}
addAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
}
else
{
/*
* The startTag is closed, yet we are adding an attribute?
*
* Section: 7.1.3 Creating Attributes Adding an attribute to an
* element after a PI (for example) has been added to it is an
* error. The attributes can be ignored. The spec doesn't explicitly
* say this is disallowed, as it does for child elements, but it
* makes sense to have the same treatment.
*
* We choose to ignore the attribute which is added too late.
*/
// Generate a warning of the ignored attributes
// Create the warning message
String msg = Utils.messages.createMessage(
MsgKey.ER_ILLEGAL_ATTRIBUTE_POSITION,new Object[]{ localName });
try {
// Prepare to issue the warning message
Transformer tran = super.getTransformer();
ErrorListener errHandler = tran.getErrorListener();
// Issue the warning message
if (null != errHandler && m_sourceLocator != null)
errHandler.warning(new TransformerException(msg, m_sourceLocator));
else
System.out.println(msg);
}
catch (TransformerException e){
// A user defined error handler, errHandler, may throw
// a TransformerException if it chooses to, and if it does
// we will wrap it with a SAXException and re-throw.
// Of course if the handler throws another type of
// exception, like a RuntimeException, then that is OK too.
SAXException se = new SAXException(e);
throw se;
}
}
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void endElement(String elemName) throws SAXException
{
endElement(null, null, elemName);
}
// in src/org/apache/xml/serializer/ToXMLStream.java
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
// hack for XSLTC with finding URI for default namespace
if (m_elemContext.m_elementURI == null)
{
String prefix1 = getPrefixPart(m_elemContext.m_elementName);
if (prefix1 == null && EMPTYSTRING.equals(prefix))
{
// the elements URI is not known yet, and it
// doesn't have a prefix, and we are currently
// setting the uri for prefix "", so we have
// the uri for the element... lets remember it
m_elemContext.m_elementURI = uri;
}
}
startPrefixMapping(prefix,uri,false);
return;
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public boolean setEscaping(boolean escape) throws SAXException
{
return m_handler.setEscaping(escape);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void addAttribute(
String uri,
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.addAttribute(uri, localName, rawName, type, value, XSLAttribute);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void addUniqueAttribute(String rawName, String value, int flags)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.addUniqueAttribute(rawName, value, flags);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void characters(String chars) throws SAXException
{
final int length = chars.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
chars.getChars(0, length, m_charsBuff, 0);
this.characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endElement(String elementName) throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.endElement(elementName);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startPrefixMapping(String prefix, String uri) throws SAXException
{
this.startPrefixMapping(prefix,uri, true);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void namespaceAfterStartElement(String prefix, String uri)
throws SAXException
{
// hack for XSLTC with finding URI for default namespace
if (m_firstTagNotEmitted && m_firstElementURI == null && m_firstElementName != null)
{
String prefix1 = getPrefixPart(m_firstElementName);
if (prefix1 == null && EMPTYSTRING.equals(prefix))
{
// the elements URI is not known yet, and it
// doesn't have a prefix, and we are currently
// setting the uri for prefix "", so we have
// the uri for the element... lets remember it
m_firstElementURI = uri;
}
}
startPrefixMapping(prefix,uri, false);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public boolean startPrefixMapping(String prefix, String uri, boolean shouldFlush)
throws SAXException
{
boolean pushed = false;
if (m_firstTagNotEmitted)
{
if (m_firstElementName != null && shouldFlush)
{
/* we've already seen a startElement, and this is a prefix mapping
* for the up coming element, so flush the old element
* then send this event on its way.
*/
flush();
pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush);
}
else
{
if (m_namespacePrefix == null)
{
m_namespacePrefix = new Vector();
m_namespaceURI = new Vector();
}
m_namespacePrefix.addElement(prefix);
m_namespaceURI.addElement(uri);
if (m_firstElementURI == null)
{
if (prefix.equals(m_firstElementPrefix))
m_firstElementURI = uri;
}
}
}
else
{
pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush);
}
return pushed;
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startDocument() throws SAXException
{
m_needToCallStartDocument = true;
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startElement(String qName) throws SAXException
{
this.startElement(null, null, qName, null);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startElement(String namespaceURI, String localName, String qName) throws SAXException
{
this.startElement(namespaceURI, localName, qName, null);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startElement(
String namespaceURI,
String localName,
String elementName,
Attributes atts) throws SAXException
{
/* we are notified of the start of an element */
if (m_firstTagNotEmitted)
{
/* we have not yet sent the first element on its way */
if (m_firstElementName != null)
{
/* this is not the first element, but a later one.
* But we have the old element pending, so flush it out,
* then send this one on its way.
*/
flush();
m_handler.startElement(namespaceURI, localName, elementName, atts);
}
else
{
/* this is the very first element that we have seen,
* so save it for flushing later. We may yet get to know its
* URI due to added attributes.
*/
m_wrapped_handler_not_initialized = true;
m_firstElementName = elementName;
// null if not known
m_firstElementPrefix = getPrefixPartUnknown(elementName);
// null if not known
m_firstElementURI = namespaceURI;
// null if not known
m_firstElementLocalName = localName;
if (m_tracer != null)
firePseudoElement(elementName);
/* we don't want to call our own addAttributes, which
* merely delegates to the wrapped handler, but we want to
* add these attributes to m_attributes. So me must call super.
* addAttributes() In this case m_attributes is only used for the
* first element, after that this class totally delegates to the
* wrapped handler which is either XML or HTML.
*/
if (atts != null)
super.addAttributes(atts);
// if there are attributes, then lets make the flush()
// call the startElement on the handler and send the
// attributes on their way.
if (atts != null)
flush();
}
}
else
{
// this is not the first element, but a later one, so just
// send it on its way.
m_handler.startElement(namespaceURI, localName, elementName, atts);
}
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void comment(String comment) throws SAXException
{
if (m_firstTagNotEmitted && m_firstElementName != null)
{
emitFirstTag();
}
else if (m_needToCallStartDocument)
{
m_handler.startDocument();
m_needToCallStartDocument = false;
}
m_handler.comment(comment);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void attributeDecl(
String arg0,
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void elementDecl(String arg0, String arg1) throws SAXException
{
if (m_firstTagNotEmitted)
{
emitFirstTag();
}
m_handler.elementDecl(arg0, arg1);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void externalEntityDecl(
String name,
String publicId,
String systemId)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.externalEntityDecl(name, publicId, systemId);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void internalEntityDecl(String arg0, String arg1)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.internalEntityDecl(arg0, arg1);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void characters(char[] characters, int offset, int length)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.characters(characters, offset, length);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endDocument() throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.endDocument();
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
if (namespaceURI == null && m_firstElementURI != null)
namespaceURI = m_firstElementURI;
if (localName == null && m_firstElementLocalName != null)
localName = m_firstElementLocalName;
}
m_handler.endElement(namespaceURI, localName, qName);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endPrefixMapping(String prefix) throws SAXException
{
m_handler.endPrefixMapping(prefix);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.ignorableWhitespace(ch, start, length);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void processingInstruction(String target, String data)
throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.processingInstruction(target, data);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void skippedEntity(String name) throws SAXException
{
m_handler.skippedEntity(name);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void comment(char[] ch, int start, int length) throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.comment(ch, start, length);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endCDATA() throws SAXException
{
m_handler.endCDATA();
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endDTD() throws SAXException
{
m_handler.endDTD();
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void endEntity(String name) throws SAXException
{
if (m_firstTagNotEmitted)
{
emitFirstTag();
}
m_handler.endEntity(name);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startCDATA() throws SAXException
{
m_handler.startCDATA();
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
m_handler.startDTD(name, publicId, systemId);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void startEntity(String name) throws SAXException
{
m_handler.startEntity(name);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
private void initStreamOutput() throws SAXException
{
// Try to rule out if this is an not to be an HTML document based on prefix
boolean firstElementIsHTML = isFirstElemHTML();
if (firstElementIsHTML)
{
// create an HTML output handler, and initialize it
// keep a reference to the old handler, ... it will soon be gone
SerializationHandler oldHandler = m_handler;
/* We have to make sure we get an output properties with the proper
* defaults for the HTML method. The easiest way to do this is to
* have the OutputProperties class do it.
*/
Properties htmlProperties =
OutputPropertiesFactory.getDefaultMethodProperties(Method.HTML);
Serializer serializer =
SerializerFactory.getSerializer(htmlProperties);
// The factory should be returning a ToStream
// Don't know what to do if it doesn't
// i.e. the user has over-ridden the content-handler property
// for html
m_handler = (SerializationHandler) serializer;
//m_handler = new ToHTMLStream();
Writer writer = oldHandler.getWriter();
if (null != writer)
m_handler.setWriter(writer);
else
{
OutputStream os = oldHandler.getOutputStream();
if (null != os)
m_handler.setOutputStream(os);
}
// need to copy things from the old handler to the new one here
// if (_setVersion_called)
// {
m_handler.setVersion(oldHandler.getVersion());
// }
// if (_setDoctypeSystem_called)
// {
m_handler.setDoctypeSystem(oldHandler.getDoctypeSystem());
// }
// if (_setDoctypePublic_called)
// {
m_handler.setDoctypePublic(oldHandler.getDoctypePublic());
// }
// if (_setMediaType_called)
// {
m_handler.setMediaType(oldHandler.getMediaType());
// }
m_handler.setTransformer(oldHandler.getTransformer());
}
/* Now that we have a real wrapped handler (XML or HTML) lets
* pass any cached calls to it
*/
// Call startDocument() if necessary
if (m_needToCallStartDocument)
{
m_handler.startDocument();
m_needToCallStartDocument = false;
}
// the wrapped handler is now fully initialized
m_wrapped_handler_not_initialized = false;
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
private void emitFirstTag() throws SAXException
{
if (m_firstElementName != null)
{
if (m_wrapped_handler_not_initialized)
{
initStreamOutput();
m_wrapped_handler_not_initialized = false;
}
// Output first tag
m_handler.startElement(m_firstElementURI, null, m_firstElementName, m_attributes);
// don't need the collected attributes of the first element anymore.
m_attributes = null;
// Output namespaces of first tag
if (m_namespacePrefix != null)
{
final int n = m_namespacePrefix.size();
for (int i = 0; i < n; i++)
{
final String prefix =
(String) m_namespacePrefix.elementAt(i);
final String uri = (String) m_namespaceURI.elementAt(i);
m_handler.startPrefixMapping(prefix, uri, false);
}
m_namespacePrefix = null;
m_namespaceURI = null;
}
m_firstTagNotEmitted = false;
}
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void addAttributes(Attributes atts) throws SAXException
{
m_handler.addAttributes(atts);
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void flushPending() throws SAXException
{
flush();
m_handler.flushPending();
}
// in src/org/apache/xml/serializer/ToUnknownStream.java
public void entityReference(String entityName) throws SAXException
{
m_handler.entityReference(entityName);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endElement(String elemName) throws SAXException
{
if (m_tracer != null)
super.fireEndElem(elemName);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endElement(String arg0, String arg1, String arg2)
throws SAXException
{
if (m_tracer != null)
super.fireEndElem(arg2);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void comment(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
super.fireCommentEvent(ch, start, length);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void comment(String data) throws org.xml.sax.SAXException
{
final int length = data.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
data.getChars(0, length, m_charsBuff, 0);
comment(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void indent(int n) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void attributeDecl(
String arg0,
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void elementDecl(String arg0, String arg1) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void externalEntityDecl(String arg0, String arg1, String arg2)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void internalEntityDecl(String arg0, String arg1)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endPrefixMapping(String arg0) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void processingInstruction(String arg0, String arg1)
throws SAXException
{
if (m_tracer != null)
super.fireEscapingEvent(arg0, arg1);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void skippedEntity(String arg0) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startElement(
String arg0,
String arg1,
String arg2,
Attributes arg3)
throws SAXException
{
flushPending();
super.startElement(arg0, arg1, arg2, arg3);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endCDATA() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endDTD() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startCDATA() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startEntity(String arg0) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName) throws SAXException
{
super.startElement(elementNamespaceURI, elementLocalName, elementName);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startElement(
String elementName) throws SAXException
{
super.startElement(elementName);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void endDocument() throws SAXException {
flushPending();
m_saxHandler.endDocument();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void characters(String characters)
throws SAXException
{
final int length = characters.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
characters.getChars(0, length, m_charsBuff, 0);
m_saxHandler.characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void characters(char[] characters, int offset, int length)
throws SAXException
{
m_saxHandler.characters(characters, offset, length);
// time to fire off characters event
if (m_tracer != null)
super.fireCharEvent(characters, offset, length);
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws SAXException
{
// no namespace support for HTML
return false;
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// no namespace support for HTML
}
// in src/org/apache/xml/serializer/ToTextSAXHandler.java
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
// no namespace support for HTML
}
// in src/org/apache/xml/serializer/ToTextStream.java
protected void startDocumentInternal() throws org.xml.sax.SAXException
{
super.startDocumentInternal();
m_needToCallStartDocument = false;
// No action for the moment.
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void endDocument() throws org.xml.sax.SAXException
{
flushPending();
flushWriter();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void startElement(
String namespaceURI, String localName, String name, Attributes atts)
throws org.xml.sax.SAXException
{
// time to fire off startElement event
if (m_tracer != null) {
super.fireStartElem(name);
this.firePseudoAttributes();
}
return;
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void endElement(String namespaceURI, String localName, String name)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
super.fireEndElem(name);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void characters(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
flushPending();
try
{
if (inTemporaryOutputState()) {
/* leave characters un-processed as we are
* creating temporary output, the output generated by
* this serializer will be input to a final serializer
* later on and it will do the processing in final
* output state (not temporary output state).
*
* A "temporary" ToTextStream serializer is used to
* evaluate attribute value templates (for example),
* and the result of evaluating such a thing
* is fed into a final serializer later on.
*/
m_writer.write(ch, start, length);
}
else {
// In final output state we do process the characters!
writeNormalizedChars(ch, start, length, m_lineSepUse);
}
if (m_tracer != null)
super.fireCharEvent(ch, start, length);
}
catch(IOException ioe)
{
throw new SAXException(ioe);
}
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void charactersRaw(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
try
{
writeNormalizedChars(ch, start, length, m_lineSepUse);
}
catch(IOException ioe)
{
throw new SAXException(ioe);
}
}
// in src/org/apache/xml/serializer/ToTextStream.java
void writeNormalizedChars(
final char ch[],
final int start,
final int length,
final boolean useLineSep)
throws IOException, org.xml.sax.SAXException
{
final String encoding = getEncoding();
final java.io.Writer writer = m_writer;
final int end = start + length;
/* copy a few "constants" before the loop for performance */
final char S_LINEFEED = CharInfo.S_LINEFEED;
// This for() loop always increments i by one at the end
// of the loop. Additional increments of i adjust for when
// two input characters (a high/low UTF16 surrogate pair)
// are processed.
for (int i = start; i < end; i++) {
final char c = ch[i];
if (S_LINEFEED == c && useLineSep) {
writer.write(m_lineSep, 0, m_lineSepLen);
// one input char processed
} else if (m_encodingInfo.isInEncoding(c)) {
writer.write(c);
// one input char processed
} else if (Encodings.isHighUTF16Surrogate(c)) {
final int codePoint = writeUTF16Surrogate(c, ch, i, end);
if (codePoint != 0) {
// I think we can just emit the message,
// not crash and burn.
final String integralValue = Integer.toString(codePoint);
final String msg = Utils.messages.createMessage(
MsgKey.ER_ILLEGAL_CHARACTER,
new Object[] { integralValue, encoding });
//Older behavior was to throw the message,
//but newer gentler behavior is to write a message to System.err
//throw new SAXException(msg);
System.err.println(msg);
}
i++; // two input chars processed
} else {
// Don't know what to do with this char, it is
// not in the encoding and not a high char in
// a surrogate pair, so write out as an entity ref
if (encoding != null) {
/* The output encoding is known,
* so somthing is wrong.
*/
// not in the encoding, so write out a character reference
writer.write('&');
writer.write('#');
writer.write(Integer.toString(c));
writer.write(';');
// I think we can just emit the message,
// not crash and burn.
final String integralValue = Integer.toString(c);
final String msg = Utils.messages.createMessage(
MsgKey.ER_ILLEGAL_CHARACTER,
new Object[] { integralValue, encoding });
//Older behavior was to throw the message,
//but newer gentler behavior is to write a message to System.err
//throw new SAXException(msg);
System.err.println(msg);
} else {
/* The output encoding is not known,
* so just write it out as-is.
*/
writer.write(c);
}
// one input char was processed
}
}
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void cdata(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
try
{
writeNormalizedChars(ch, start, length, m_lineSepUse);
if (m_tracer != null)
super.fireCDATAEvent(ch, start, length);
}
catch(IOException ioe)
{
throw new SAXException(ioe);
}
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
try
{
writeNormalizedChars(ch, start, length, m_lineSepUse);
}
catch(IOException ioe)
{
throw new SAXException(ioe);
}
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
// flush anything pending first
flushPending();
if (m_tracer != null)
super.fireEscapingEvent(target, data);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void comment(String data) throws org.xml.sax.SAXException
{
final int length = data.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
data.getChars(0, length, m_charsBuff, 0);
comment(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void comment(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
flushPending();
if (m_tracer != null)
super.fireCommentEvent(ch, start, length);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void entityReference(String name) throws org.xml.sax.SAXException
{
if (m_tracer != null)
super.fireEntityReference(name);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void endCDATA() throws SAXException
{
// do nothing
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void endElement(String elemName) throws SAXException
{
if (m_tracer != null)
super.fireEndElem(elemName);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName)
throws SAXException
{
if (m_needToCallStartDocument)
startDocumentInternal();
// time to fire off startlement event.
if (m_tracer != null) {
super.fireStartElem(elementName);
this.firePseudoAttributes();
}
return;
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void characters(String characters)
throws SAXException
{
final int length = characters.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length*2 + 1];
}
characters.getChars(0, length, m_charsBuff, 0);
characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void addUniqueAttribute(String qName, String value, int flags)
throws SAXException
{
// do nothing, forget about the attribute
}
// in src/org/apache/xml/serializer/ToTextStream.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws SAXException
{
// no namespace support for HTML
return false;
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// no namespace support for HTML
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
// no namespace support for HTML
}
// in src/org/apache/xml/serializer/ToTextStream.java
public void flushPending() throws org.xml.sax.SAXException
{
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
protected void startDocumentInternal() throws org.xml.sax.SAXException
{
super.startDocumentInternal();
m_needToCallStartDocument = false;
m_needToOutputDocTypeDecl = true;
m_startNewLine = false;
setOmitXMLDeclaration(true);
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
private void outputDocTypeDecl(String name) throws SAXException {
if (true == m_needToOutputDocTypeDecl)
{
String doctypeSystem = getDoctypeSystem();
String doctypePublic = getDoctypePublic();
if ((null != doctypeSystem) || (null != doctypePublic))
{
final java.io.Writer writer = m_writer;
try
{
writer.write("<!DOCTYPE ");
writer.write(name);
if (null != doctypePublic)
{
writer.write(" PUBLIC \"");
writer.write(doctypePublic);
writer.write('"');
}
if (null != doctypeSystem)
{
if (null == doctypePublic)
writer.write(" SYSTEM \"");
else
writer.write(" \"");
writer.write(doctypeSystem);
writer.write('"');
}
writer.write('>');
outputLineSep();
}
catch(IOException e)
{
throw new SAXException(e);
}
}
}
m_needToOutputDocTypeDecl = false;
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void endDocument() throws org.xml.sax.SAXException
{
flushPending();
if (m_doIndent && !m_isprevtext)
{
try
{
outputLineSep();
}
catch(IOException e)
{
throw new SAXException(e);
}
}
flushWriter();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void startElement(
String namespaceURI,
String localName,
String name,
Attributes atts)
throws org.xml.sax.SAXException
{
ElemContext elemContext = m_elemContext;
// clean up any pending things first
if (elemContext.m_startTagOpen)
{
closeStartTag();
elemContext.m_startTagOpen = false;
}
else if (m_cdataTagOpen)
{
closeCDATA();
m_cdataTagOpen = false;
}
else if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
if (m_needToOutputDocTypeDecl) {
String n = name;
if (n == null || n.length() == 0) {
// If the lexical QName is not given
// use the localName in the DOCTYPE
n = localName;
}
outputDocTypeDecl(n);
}
// if this element has a namespace then treat it like XML
if (null != namespaceURI && namespaceURI.length() > 0)
{
super.startElement(namespaceURI, localName, name, atts);
return;
}
try
{
// getElemDesc2(name) is faster than getElemDesc(name)
ElemDesc elemDesc = getElemDesc2(name);
int elemFlags = elemDesc.getFlags();
// deal with indentation issues first
if (m_doIndent)
{
boolean isBlockElement = (elemFlags & ElemDesc.BLOCK) != 0;
if (m_ispreserve)
m_ispreserve = false;
else if (
(null != elemContext.m_elementName)
&& (!m_inBlockElem
|| isBlockElement) /* && !isWhiteSpaceSensitive */
)
{
m_startNewLine = true;
indent();
}
m_inBlockElem = !isBlockElement;
}
// save any attributes for later processing
if (atts != null)
addAttributes(atts);
m_isprevtext = false;
final java.io.Writer writer = m_writer;
writer.write('<');
writer.write(name);
if (m_tracer != null)
firePseudoAttributes();
if ((elemFlags & ElemDesc.EMPTY) != 0)
{
// an optimization for elements which are expected
// to be empty.
m_elemContext = elemContext.push();
/* XSLTC sometimes calls namespaceAfterStartElement()
* so we need to remember the name
*/
m_elemContext.m_elementName = name;
m_elemContext.m_elementDesc = elemDesc;
return;
}
else
{
elemContext = elemContext.push(namespaceURI,localName,name);
m_elemContext = elemContext;
elemContext.m_elementDesc = elemDesc;
elemContext.m_isRaw = (elemFlags & ElemDesc.RAW) != 0;
}
if ((elemFlags & ElemDesc.HEADELEM) != 0)
{
// This is the <HEAD> element, do some special processing
closeStartTag();
elemContext.m_startTagOpen = false;
if (!m_omitMetaTag)
{
if (m_doIndent)
indent();
writer.write(
"<META http-equiv=\"Content-Type\" content=\"text/html; charset=");
String encoding = getEncoding();
String encode = Encodings.getMimeEncoding(encoding);
writer.write(encode);
writer.write("\">");
}
}
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void endElement(
final String namespaceURI,
final String localName,
final String name)
throws org.xml.sax.SAXException
{
// deal with any pending issues
if (m_cdataTagOpen)
closeCDATA();
// if the element has a namespace, treat it like XML, not HTML
if (null != namespaceURI && namespaceURI.length() > 0)
{
super.endElement(namespaceURI, localName, name);
return;
}
try
{
ElemContext elemContext = m_elemContext;
final ElemDesc elemDesc = elemContext.m_elementDesc;
final int elemFlags = elemDesc.getFlags();
final boolean elemEmpty = (elemFlags & ElemDesc.EMPTY) != 0;
// deal with any indentation issues
if (m_doIndent)
{
final boolean isBlockElement = (elemFlags&ElemDesc.BLOCK) != 0;
boolean shouldIndent = false;
if (m_ispreserve)
{
m_ispreserve = false;
}
else if (m_doIndent && (!m_inBlockElem || isBlockElement))
{
m_startNewLine = true;
shouldIndent = true;
}
if (!elemContext.m_startTagOpen && shouldIndent)
indent(elemContext.m_currentElemDepth - 1);
m_inBlockElem = !isBlockElement;
}
final java.io.Writer writer = m_writer;
if (!elemContext.m_startTagOpen)
{
writer.write("</");
writer.write(name);
writer.write('>');
}
else
{
// the start-tag open when this method was called,
// so we need to process it now.
if (m_tracer != null)
super.fireStartElem(name);
// the starting tag was still open when we received this endElement() call
// so we need to process any gathered attributes NOW, before they go away.
int nAttrs = m_attributes.getLength();
if (nAttrs > 0)
{
processAttributes(m_writer, nAttrs);
// clear attributes object for re-use with next element
m_attributes.clear();
}
if (!elemEmpty)
{
// As per Dave/Paul recommendation 12/06/2000
// if (shouldIndent)
// writer.write('>');
// indent(m_currentIndent);
writer.write("></");
writer.write(name);
writer.write('>');
}
else
{
writer.write('>');
}
}
// clean up because the element has ended
if ((elemFlags & ElemDesc.WHITESPACESENSITIVE) != 0)
m_ispreserve = true;
m_isprevtext = false;
// fire off the end element event
if (m_tracer != null)
super.fireEndElem(name);
// OPTIMIZE-EMPTY
if (elemEmpty)
{
// a quick exit if the HTML element had no children.
// This block of code can be removed if the corresponding block of code
// in startElement() also labeled with "OPTIMIZE-EMPTY" is also removed
m_elemContext = elemContext.m_prev;
return;
}
// some more clean because the element has ended.
if (!elemContext.m_startTagOpen)
{
if (m_doIndent && !m_preserves.isEmpty())
m_preserves.pop();
}
m_elemContext = elemContext.m_prev;
// m_isRawStack.pop();
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void characters(char chars[], int start, int length)
throws org.xml.sax.SAXException
{
if (m_elemContext.m_isRaw)
{
try
{
// Clean up some pending issues.
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
m_ispreserve = true;
writeNormalizedChars(chars, start, length, false, m_lineSepUse);
// time to generate characters event
if (m_tracer != null)
super.fireCharEvent(chars, start, length);
return;
}
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(
Utils.messages.createMessage(MsgKey.ER_OIERROR,null),ioe);
}
}
else
{
super.characters(chars, start, length);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void cdata(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if ((null != m_elemContext.m_elementName)
&& (m_elemContext.m_elementName.equalsIgnoreCase("SCRIPT")
|| m_elemContext.m_elementName.equalsIgnoreCase("STYLE")))
{
try
{
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
m_ispreserve = true;
if (shouldIndent())
indent();
// writer.write(ch, start, length);
writeNormalizedChars(ch, start, length, true, m_lineSepUse);
}
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(
Utils.messages.createMessage(
MsgKey.ER_OIERROR,
null),
ioe);
//"IO error", ioe);
}
}
else
{
super.cdata(ch, start, length);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
// Process any pending starDocument and startElement first.
flushPending();
// Use a fairly nasty hack to tell if the next node is supposed to be
// unescaped text.
if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING))
{
startNonEscaping();
}
else if (target.equals(Result.PI_ENABLE_OUTPUT_ESCAPING))
{
endNonEscaping();
}
else
{
try
{
// clean up any pending things first
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
else if (m_cdataTagOpen)
{
closeCDATA();
}
else if (m_needToCallStartDocument)
{
startDocumentInternal();
}
/*
* Perhaps processing instructions can be written out in HTML before
* the DOCTYPE, in which case this could be emitted with the
* startElement call, that knows the name of the document element
* doing it right.
*/
if (true == m_needToOutputDocTypeDecl)
outputDocTypeDecl("html"); // best guess for the upcoming element
if (shouldIndent())
indent();
final java.io.Writer writer = m_writer;
//writer.write("<?" + target);
writer.write("<?");
writer.write(target);
if (data.length() > 0 && !Character.isSpaceChar(data.charAt(0)))
writer.write(' ');
//writer.write(data + ">"); // different from XML
writer.write(data); // different from XML
writer.write('>'); // different from XML
// Always output a newline char if not inside of an
// element. The whitespace is not significant in that
// case.
if (m_elemContext.m_currentElemDepth <= 0)
outputLineSep();
m_startNewLine = true;
}
catch(IOException e)
{
throw new SAXException(e);
}
}
// now generate the PI event
if (m_tracer != null)
super.fireEscapingEvent(target, data);
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void entityReference(String name)
throws org.xml.sax.SAXException
{
try
{
final java.io.Writer writer = m_writer;
writer.write('&');
writer.write(name);
writer.write(';');
} catch(IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public final void endElement(String elemName) throws SAXException
{
endElement(null, null, elemName);
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void processAttributes(java.io.Writer writer, int nAttrs)
throws IOException,SAXException
{
/*
* process the collected attributes
*/
for (int i = 0; i < nAttrs; i++)
{
processAttribute(
writer,
m_attributes.getQName(i),
m_attributes.getValue(i),
m_elemContext.m_elementDesc);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
protected void closeStartTag() throws SAXException
{
try
{
// finish processing attributes, time to fire off the start element event
if (m_tracer != null)
super.fireStartElem(m_elemContext.m_elementName);
int nAttrs = m_attributes.getLength();
if (nAttrs>0)
{
processAttributes(m_writer, nAttrs);
// clear attributes object for re-use with next element
m_attributes.clear();
}
m_writer.write('>');
/* At this point we have the prefix mappings now, so
* lets determine if the current element is specified in the cdata-
* section-elements list.
*/
if (m_CdataElems != null) // if there are any cdata sections
m_elemContext.m_isCdataSection = isCdataSection();
if (m_doIndent)
{
m_isprevtext = false;
m_preserves.push(m_ispreserve);
}
}
catch(IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void namespaceAfterStartElement(String prefix, String uri)
throws SAXException
{
// hack for XSLTC with finding URI for default namespace
if (m_elemContext.m_elementURI == null)
{
String prefix1 = getPrefixPart(m_elemContext.m_elementName);
if (prefix1 == null && EMPTYSTRING.equals(prefix))
{
// the elements URI is not known yet, and it
// doesn't have a prefix, and we are currently
// setting the uri for prefix "", so we have
// the uri for the element... lets remember it
m_elemContext.m_elementURI = uri;
}
}
startPrefixMapping(prefix,uri,false);
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
m_inDTD = true;
super.startDTD(name, publicId, systemId);
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void endDTD() throws org.xml.sax.SAXException
{
m_inDTD = false;
/* for ToHTMLStream the DOCTYPE is entirely output in the
* startDocumentInternal() method, so don't do anything here
*/
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void attributeDecl(
String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
// The internal DTD subset is not serialized by the ToHTMLStream serializer
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void elementDecl(String name, String model) throws SAXException
{
// The internal DTD subset is not serialized by the ToHTMLStream serializer
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
// The internal DTD subset is not serialized by the ToHTMLStream serializer
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void externalEntityDecl(
String name,
String publicId,
String systemId)
throws SAXException
{
// The internal DTD subset is not serialized by the ToHTMLStream serializer
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void addUniqueAttribute(String name, String value, int flags)
throws SAXException
{
try
{
final java.io.Writer writer = m_writer;
if ((flags & NO_BAD_CHARS) > 0 && m_htmlcharInfo.onlyQuotAmpLtGt)
{
// "flags" has indicated that the characters
// '>' '<' '&' and '"' are not in the value and
// m_htmlcharInfo has recorded that there are no other
// entities in the range 0 to 127 so we write out the
// value directly
writer.write(' ');
writer.write(name);
writer.write("=\"");
writer.write(value);
writer.write('"');
}
else if (
(flags & HTML_ATTREMPTY) > 0
&& (value.length() == 0 || value.equalsIgnoreCase(name)))
{
writer.write(' ');
writer.write(name);
}
else
{
writer.write(' ');
writer.write(name);
writer.write("=\"");
if ((flags & HTML_ATTRURL) > 0)
{
writeAttrURI(writer, value, m_specialEscapeURLs);
}
else
{
writeAttrString(writer, value, this.getEncoding());
}
writer.write('"');
}
} catch (IOException e) {
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToHTMLStream.java
public void comment(char ch[], int start, int length)
throws SAXException
{
// The internal DTD subset is not serialized by the ToHTMLStream serializer
if (m_inDTD)
return;
// Clean up some pending issues, just in case
// this call is coming right after a startElement()
// or we are in the middle of writing out CDATA
// or if a startDocument() call was not received
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
else if (m_cdataTagOpen)
{
closeCDATA();
}
else if (m_needToCallStartDocument)
{
startDocumentInternal();
}
/*
* Perhaps comments can be written out in HTML before the DOCTYPE.
* In this case we might delete this call to writeOutDOCTYPE, and
* it would be handled within the startElement() call.
*/
if (m_needToOutputDocTypeDecl)
outputDocTypeDecl("html"); // best guess for the upcoming element
super.comment(ch, start, length);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void indent(int n) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public boolean setEscaping(boolean escape) throws SAXException
{
boolean oldEscapeSetting = m_escapeSetting;
m_escapeSetting = escape;
if (escape) {
processingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, "");
} else {
processingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "");
}
return oldEscapeSetting;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void attributeDecl(
String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void elementDecl(String name, String model) throws SAXException
{
return;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void externalEntityDecl(String arg0, String arg1, String arg2)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
flushPending();
m_saxHandler.endElement(uri, localName, qName);
// time to fire off endElement event
if (m_tracer != null)
super.fireEndElem(qName);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endPrefixMapping(String prefix) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void processingInstruction(String target, String data)
throws SAXException
{
flushPending();
m_saxHandler.processingInstruction(target,data);
// time to fire off processing instruction event
if (m_tracer != null)
super.fireEscapingEvent(target,data);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void skippedEntity(String arg0) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startElement(
String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException
{
flushPending();
super.startElement(namespaceURI, localName, qName, atts);
m_saxHandler.startElement(namespaceURI, localName, qName, atts);
m_elemContext.m_startTagOpen = false;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void comment(char[] ch, int start, int length) throws SAXException
{
flushPending();
if (m_lexHandler != null)
m_lexHandler.comment(ch, start, length);
// time to fire off comment event
if (m_tracer != null)
super.fireCommentEvent(ch, start, length);
return;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endCDATA() throws SAXException
{
return;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endDTD() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startCDATA() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startEntity(String arg0) throws SAXException
{
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endDocument() throws SAXException
{
flushPending();
// Close output document
m_saxHandler.endDocument();
if (m_tracer != null)
super.fireEndDoc();
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
protected void closeStartTag() throws SAXException
{
m_elemContext.m_startTagOpen = false;
// Now is time to send the startElement event
m_saxHandler.startElement(
EMPTYSTRING,
m_elemContext.m_elementName,
m_elemContext.m_elementName,
m_attributes);
m_attributes.clear();
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void characters(final String chars) throws SAXException
{
final int length = chars.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length * 2 + 1];
}
chars.getChars(0, length, m_charsBuff, 0);
this.characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName) throws SAXException
{
super.startElement(elementNamespaceURI, elementLocalName, elementName);
flushPending();
// Handle document type declaration (for first element only)
if (!m_dtdHandled)
{
String doctypeSystem = getDoctypeSystem();
String doctypePublic = getDoctypePublic();
if ((doctypeSystem != null) || (doctypePublic != null)) {
if (m_lexHandler != null)
m_lexHandler.startDTD(
elementName,
doctypePublic,
doctypeSystem);
}
m_dtdHandled = true;
}
m_elemContext = m_elemContext.push(elementNamespaceURI, elementLocalName, elementName);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startElement(String elementName) throws SAXException
{
this.startElement(null,null, elementName);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void endElement(String elementName) throws SAXException
{
flushPending();
m_saxHandler.endElement(EMPTYSTRING, elementName, elementName);
// time to fire off endElement event
if (m_tracer != null)
super.fireEndElem(elementName);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void characters(char[] ch, int off, int len) throws SAXException
{
flushPending();
m_saxHandler.characters(ch, off, len);
// time to fire off characters event
if (m_tracer != null)
super.fireCharEvent(ch, off, len);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void flushPending() throws SAXException
{
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
// Close any open element
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws SAXException
{
// no namespace support for HTML
if (shouldFlush)
flushPending();
m_saxHandler.startPrefixMapping(prefix,uri);
return false;
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
startPrefixMapping(prefix,uri,true);
}
// in src/org/apache/xml/serializer/ToHTMLSAXHandler.java
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
// hack for XSLTC with finding URI for default namespace
if (m_elemContext.m_elementURI == null)
{
String prefix1 = getPrefixPart(m_elemContext.m_elementName);
if (prefix1 == null && EMPTYSTRING.equals(prefix))
{
// the elements URI is not known yet, and it
// doesn't have a prefix, and we are currently
// setting the uri for prefix "", so we have
// the uri for the element... lets remember it
m_elemContext.m_elementURI = uri;
}
}
startPrefixMapping(prefix,uri,false);
}
// in src/org/apache/xml/serializer/ToStream.java
protected void closeCDATA() throws org.xml.sax.SAXException
{
try
{
m_writer.write(CDATA_DELIMITER_CLOSE);
// write out a CDATA section closing "]]>"
m_cdataTagOpen = false; // Remember that we have done so.
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
protected final void flushWriter() throws org.xml.sax.SAXException
{
final java.io.Writer writer = m_writer;
if (null != writer)
{
try
{
if (writer instanceof WriterToUTF8Buffered)
{
if (m_shouldFlush)
((WriterToUTF8Buffered) writer).flush();
else
((WriterToUTF8Buffered) writer).flushBuffer();
}
if (writer instanceof WriterToASCI)
{
if (m_shouldFlush)
writer.flush();
}
else
{
// Flush always.
// Not a great thing if the writer was created
// by this class, but don't have a choice.
writer.flush();
}
}
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(ioe);
}
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void elementDecl(String name, String model) throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
final java.io.Writer writer = m_writer;
DTDprolog();
writer.write("<!ELEMENT ");
writer.write(name);
writer.write(' ');
writer.write(model);
writer.write('>');
writer.write(m_lineSep, 0, m_lineSepLen);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
DTDprolog();
outputEntityDecl(name, value);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void attributeDecl(
String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
final java.io.Writer writer = m_writer;
DTDprolog();
writer.write("<!ATTLIST ");
writer.write(eName);
writer.write(' ');
writer.write(aName);
writer.write(' ');
writer.write(type);
if (valueDefault != null)
{
writer.write(' ');
writer.write(valueDefault);
}
//writer.write(" ");
//writer.write(value);
writer.write('>');
writer.write(m_lineSep, 0, m_lineSepLen);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void externalEntityDecl(
String name,
String publicId,
String systemId)
throws SAXException
{
try {
DTDprolog();
m_writer.write("<!ENTITY ");
m_writer.write(name);
if (publicId != null) {
m_writer.write(" PUBLIC \"");
m_writer.write(publicId);
}
else {
m_writer.write(" SYSTEM \"");
m_writer.write(systemId);
}
m_writer.write("\" >");
m_writer.write(m_lineSep, 0, m_lineSepLen);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// in src/org/apache/xml/serializer/ToStream.java
void writeNormalizedChars(
char ch[],
int start,
int length,
boolean isCData,
boolean useSystemLineSeparator)
throws IOException, org.xml.sax.SAXException
{
final java.io.Writer writer = m_writer;
int end = start + length;
for (int i = start; i < end; i++)
{
char c = ch[i];
if (CharInfo.S_LINEFEED == c && useSystemLineSeparator)
{
writer.write(m_lineSep, 0, m_lineSepLen);
}
else if (isCData && (!escapingNotNeeded(c)))
{
// if (i != 0)
if (m_cdataTagOpen)
closeCDATA();
// This needs to go into a function...
if (Encodings.isHighUTF16Surrogate(c))
{
writeUTF16Surrogate(c, ch, i, end);
i++ ; // process two input characters
}
else
{
writer.write("&#");
String intStr = Integer.toString((int) c);
writer.write(intStr);
writer.write(';');
}
// if ((i != 0) && (i < (end - 1)))
// if (!m_cdataTagOpen && (i < (end - 1)))
// {
// writer.write(CDATA_DELIMITER_OPEN);
// m_cdataTagOpen = true;
// }
}
else if (
isCData
&& ((i < (end - 2))
&& (']' == c)
&& (']' == ch[i + 1])
&& ('>' == ch[i + 2])))
{
writer.write(CDATA_CONTINUE);
i += 2;
}
else
{
if (escapingNotNeeded(c))
{
if (isCData && !m_cdataTagOpen)
{
writer.write(CDATA_DELIMITER_OPEN);
m_cdataTagOpen = true;
}
writer.write(c);
}
// This needs to go into a function...
else if (Encodings.isHighUTF16Surrogate(c))
{
if (m_cdataTagOpen)
closeCDATA();
writeUTF16Surrogate(c, ch, i, end);
i++; // process two input characters
}
else
{
if (m_cdataTagOpen)
closeCDATA();
writer.write("&#");
String intStr = Integer.toString((int) c);
writer.write(intStr);
writer.write(';');
}
}
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void endNonEscaping() throws org.xml.sax.SAXException
{
m_disableOutputEscapingStates.pop();
}
// in src/org/apache/xml/serializer/ToStream.java
public void startNonEscaping() throws org.xml.sax.SAXException
{
m_disableOutputEscapingStates.push(true);
}
// in src/org/apache/xml/serializer/ToStream.java
protected void cdata(char ch[], int start, final int length)
throws org.xml.sax.SAXException
{
try
{
final int old_start = start;
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
m_ispreserve = true;
if (shouldIndent())
indent();
boolean writeCDataBrackets =
(((length >= 1) && escapingNotNeeded(ch[start])));
/* Write out the CDATA opening delimiter only if
* we are supposed to, and if we are not already in
* the middle of a CDATA section
*/
if (writeCDataBrackets && !m_cdataTagOpen)
{
m_writer.write(CDATA_DELIMITER_OPEN);
m_cdataTagOpen = true;
}
// writer.write(ch, start, length);
if (isEscapingDisabled())
{
charactersRaw(ch, start, length);
}
else
writeNormalizedChars(ch, start, length, true, m_lineSepUse);
/* used to always write out CDATA closing delimiter here,
* but now we delay, so that we can merge CDATA sections on output.
* need to write closing delimiter later
*/
if (writeCDataBrackets)
{
/* if the CDATA section ends with ] don't leave it open
* as there is a chance that an adjacent CDATA sections
* starts with ]>.
* We don't want to merge ]] with > , or ] with ]>
*/
if (ch[start + length - 1] == ']')
closeCDATA();
}
// time to fire off CDATA event
if (m_tracer != null)
super.fireCDATAEvent(ch, old_start, length);
}
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(
Utils.messages.createMessage(
MsgKey.ER_OIERROR,
null),
ioe);
//"IO error", ioe);
}
}
// in src/org/apache/xml/serializer/ToStream.java
protected void charactersRaw(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if (m_inEntityRef)
return;
try
{
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
m_ispreserve = true;
m_writer.write(ch, start, length);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void characters(final char chars[], final int start, final int length)
throws org.xml.sax.SAXException
{
// It does not make sense to continue with rest of the method if the number of
// characters to read from array is 0.
// Section 7.6.1 of XSLT 1.0 (http://www.w3.org/TR/xslt#value-of) suggest no text node
// is created if string is empty.
if (length == 0 || (m_inEntityRef && !m_expandDTDEntities))
return;
m_docIsEmpty = false;
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
else if (m_needToCallStartDocument)
{
startDocumentInternal();
}
if (m_cdataStartCalled || m_elemContext.m_isCdataSection)
{
/* either due to startCDATA() being called or due to
* cdata-section-elements atribute, we need this as cdata
*/
cdata(chars, start, length);
return;
}
if (m_cdataTagOpen)
closeCDATA();
if (m_disableOutputEscapingStates.peekOrFalse() || (!m_escaping))
{
charactersRaw(chars, start, length);
// time to fire off characters generation event
if (m_tracer != null)
super.fireCharEvent(chars, start, length);
return;
}
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
try
{
int i;
int startClean;
// skip any leading whitspace
// don't go off the end and use a hand inlined version
// of isWhitespace(ch)
final int end = start + length;
int lastDirtyCharProcessed = start - 1; // last non-clean character that was processed
// that was processed
final Writer writer = m_writer;
boolean isAllWhitespace = true;
// process any leading whitspace
i = start;
while (i < end && isAllWhitespace) {
char ch1 = chars[i];
if (m_charInfo.shouldMapTextChar(ch1)) {
// The character is supposed to be replaced by a String
// so write out the clean whitespace characters accumulated
// so far
// then the String.
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
String outputStringForChar = m_charInfo
.getOutputStringForChar(ch1);
writer.write(outputStringForChar);
// We can't say that everything we are writing out is
// all whitespace, we just wrote out a String.
isAllWhitespace = false;
lastDirtyCharProcessed = i; // mark the last non-clean
// character processed
i++;
} else {
// The character is clean, but is it a whitespace ?
switch (ch1) {
// TODO: Any other whitespace to consider?
case CharInfo.S_SPACE:
// Just accumulate the clean whitespace
i++;
break;
case CharInfo.S_LINEFEED:
lastDirtyCharProcessed = processLineFeed(chars, i,
lastDirtyCharProcessed, writer);
i++;
break;
case CharInfo.S_CARRIAGERETURN:
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write(" ");
lastDirtyCharProcessed = i;
i++;
break;
case CharInfo.S_HORIZONAL_TAB:
// Just accumulate the clean whitespace
i++;
break;
default:
// The character was clean, but not a whitespace
// so break the loop to continue with this character
// (we don't increment index i !!)
isAllWhitespace = false;
break;
}
}
}
/* If there is some non-whitespace, mark that we may need
* to preserve this. This is only important if we have indentation on.
*/
if (i < end || !isAllWhitespace)
m_ispreserve = true;
for (; i < end; i++)
{
char ch = chars[i];
if (m_charInfo.shouldMapTextChar(ch)) {
// The character is supposed to be replaced by a String
// e.g. '&' --> "&"
// e.g. '<' --> "<"
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
String outputStringForChar = m_charInfo.getOutputStringForChar(ch);
writer.write(outputStringForChar);
lastDirtyCharProcessed = i;
}
else {
if (ch <= 0x1F) {
// Range 0x00 through 0x1F inclusive
//
// This covers the non-whitespace control characters
// in the range 0x1 to 0x1F inclusive.
// It also covers the whitespace control characters in the same way:
// 0x9 TAB
// 0xA NEW LINE
// 0xD CARRIAGE RETURN
//
// We also cover 0x0 ... It isn't valid
// but we will output "�"
// The default will handle this just fine, but this
// is a little performance boost to handle the more
// common TAB, NEW-LINE, CARRIAGE-RETURN
switch (ch) {
case CharInfo.S_HORIZONAL_TAB:
// Leave whitespace TAB as a real character
break;
case CharInfo.S_LINEFEED:
lastDirtyCharProcessed = processLineFeed(chars, i, lastDirtyCharProcessed, writer);
break;
case CharInfo.S_CARRIAGERETURN:
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write(" ");
lastDirtyCharProcessed = i;
// Leave whitespace carriage return as a real character
break;
default:
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write("&#");
writer.write(Integer.toString(ch));
writer.write(';');
lastDirtyCharProcessed = i;
break;
}
}
else if (ch < 0x7F) {
// Range 0x20 through 0x7E inclusive
// Normal ASCII chars, do nothing, just add it to
// the clean characters
}
else if (ch <= 0x9F){
// Range 0x7F through 0x9F inclusive
// More control characters, including NEL (0x85)
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write("&#");
writer.write(Integer.toString(ch));
writer.write(';');
lastDirtyCharProcessed = i;
}
else if (ch == CharInfo.S_LINE_SEPARATOR) {
// LINE SEPARATOR
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write("
");
lastDirtyCharProcessed = i;
}
else if (m_encodingInfo.isInEncoding(ch)) {
// If the character is in the encoding, and
// not in the normal ASCII range, we also
// just leave it get added on to the clean characters
}
else {
// This is a fallback plan, we should never get here
// but if the character wasn't previously handled
// (i.e. isn't in the encoding, etc.) then what
// should we do? We choose to write out an entity
writeOutCleanChars(chars, i, lastDirtyCharProcessed);
writer.write("&#");
writer.write(Integer.toString(ch));
writer.write(';');
lastDirtyCharProcessed = i;
}
}
}
// we've reached the end. Any clean characters at the
// end of the array than need to be written out?
startClean = lastDirtyCharProcessed + 1;
if (i > startClean)
{
int lengthClean = i - startClean;
m_writer.write(chars, startClean, lengthClean);
}
// For indentation purposes, mark that we've just writen text out
m_isprevtext = true;
}
catch (IOException e)
{
throw new SAXException(e);
}
// time to fire off characters generation event
if (m_tracer != null)
super.fireCharEvent(chars, start, length);
}
// in src/org/apache/xml/serializer/ToStream.java
public void characters(String s) throws org.xml.sax.SAXException
{
if (m_inEntityRef && !m_expandDTDEntities)
return;
final int length = s.length();
if (length > m_charsBuff.length)
{
m_charsBuff = new char[length * 2 + 1];
}
s.getChars(0, length, m_charsBuff, 0);
characters(m_charsBuff, 0, length);
}
// in src/org/apache/xml/serializer/ToStream.java
public void startElement(
String namespaceURI,
String localName,
String name,
Attributes atts)
throws org.xml.sax.SAXException
{
if (m_inEntityRef)
return;
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
m_docIsEmpty = false;
}
else if (m_cdataTagOpen)
closeCDATA();
try
{
if (m_needToOutputDocTypeDecl) {
if(null != getDoctypeSystem()) {
outputDocTypeDecl(name, true);
}
m_needToOutputDocTypeDecl = false;
}
/* before we over-write the current elementLocalName etc.
* lets close out the old one (if we still need to)
*/
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
if (namespaceURI != null)
ensurePrefixIsDeclared(namespaceURI, name);
m_ispreserve = false;
if (shouldIndent() && m_startNewLine)
{
indent();
}
m_startNewLine = true;
final java.io.Writer writer = m_writer;
writer.write('<');
writer.write(name);
}
catch (IOException e)
{
throw new SAXException(e);
}
// process the attributes now, because after this SAX call they might be gone
if (atts != null)
addAttributes(atts);
m_elemContext = m_elemContext.push(namespaceURI,localName,name);
m_isprevtext = false;
if (m_tracer != null)
firePseudoAttributes();
}
// in src/org/apache/xml/serializer/ToStream.java
public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName)
throws SAXException
{
startElement(elementNamespaceURI, elementLocalName, elementName, null);
}
// in src/org/apache/xml/serializer/ToStream.java
public void startElement(String elementName) throws SAXException
{
startElement(null, null, elementName, null);
}
// in src/org/apache/xml/serializer/ToStream.java
void outputDocTypeDecl(String name, boolean closeDecl) throws SAXException
{
if (m_cdataTagOpen)
closeCDATA();
try
{
final java.io.Writer writer = m_writer;
writer.write("<!DOCTYPE ");
writer.write(name);
String doctypePublic = getDoctypePublic();
if (null != doctypePublic)
{
writer.write(" PUBLIC \"");
writer.write(doctypePublic);
writer.write('\"');
}
String doctypeSystem = getDoctypeSystem();
if (null != doctypeSystem)
{
if (null == doctypePublic)
writer.write(" SYSTEM \"");
else
writer.write(" \"");
writer.write(doctypeSystem);
if (closeDecl)
{
writer.write("\">");
writer.write(m_lineSep, 0, m_lineSepLen);
closeDecl = false; // done closing
}
else
writer.write('\"');
}
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void processAttributes(java.io.Writer writer, int nAttrs) throws IOException, SAXException
{
/* real SAX attributes are not passed in, so process the
* attributes that were collected after the startElement call.
* _attribVector is a "cheap" list for Stream serializer output
* accumulated over a series of calls to attribute(name,value)
*/
String encoding = getEncoding();
for (int i = 0; i < nAttrs; i++)
{
// elementAt is JDK 1.1.8
final String name = m_attributes.getQName(i);
final String value = m_attributes.getValue(i);
writer.write(' ');
writer.write(name);
writer.write("=\"");
writeAttrString(writer, value, encoding);
writer.write('\"');
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void endElement(String namespaceURI, String localName, String name)
throws org.xml.sax.SAXException
{
if (m_inEntityRef)
return;
// namespaces declared at the current depth are no longer valid
// so get rid of them
m_prefixMap.popNamespaces(m_elemContext.m_currentElemDepth, null);
try
{
final java.io.Writer writer = m_writer;
if (m_elemContext.m_startTagOpen)
{
if (m_tracer != null)
super.fireStartElem(m_elemContext.m_elementName);
int nAttrs = m_attributes.getLength();
if (nAttrs > 0)
{
processAttributes(m_writer, nAttrs);
// clear attributes object for re-use with next element
m_attributes.clear();
}
if (m_spaceBeforeClose)
writer.write(" />");
else
writer.write("/>");
/* don't need to pop cdataSectionState because
* this element ended so quickly that we didn't get
* to push the state.
*/
}
else
{
if (m_cdataTagOpen)
closeCDATA();
if (shouldIndent())
indent(m_elemContext.m_currentElemDepth - 1);
writer.write('<');
writer.write('/');
writer.write(name);
writer.write('>');
}
}
catch (IOException e)
{
throw new SAXException(e);
}
if (!m_elemContext.m_startTagOpen && m_doIndent)
{
m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop();
}
m_isprevtext = false;
// fire off the end element event
if (m_tracer != null)
super.fireEndElem(name);
m_elemContext = m_elemContext.m_prev;
}
// in src/org/apache/xml/serializer/ToStream.java
public void endElement(String name) throws org.xml.sax.SAXException
{
endElement(null, null, name);
}
// in src/org/apache/xml/serializer/ToStream.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// the "true" causes the flush of any open tags
startPrefixMapping(prefix, uri, true);
}
// in src/org/apache/xml/serializer/ToStream.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws org.xml.sax.SAXException
{
/* Remember the mapping, and at what depth it was declared
* This is one greater than the current depth because these
* mappings will apply to the next depth. This is in
* consideration that startElement() will soon be called
*/
boolean pushed;
int pushDepth;
if (shouldFlush)
{
flushPending();
// the prefix mapping applies to the child element (one deeper)
pushDepth = m_elemContext.m_currentElemDepth + 1;
}
else
{
// the prefix mapping applies to the current element
pushDepth = m_elemContext.m_currentElemDepth;
}
pushed = m_prefixMap.pushNamespace(prefix, uri, pushDepth);
if (pushed)
{
/* Brian M.: don't know if we really needto do this. The
* callers of this object should have injected both
* startPrefixMapping and the attributes. We are
* just covering our butt here.
*/
String name;
if (EMPTYSTRING.equals(prefix))
{
name = "xmlns";
addAttributeAlways(XMLNS_URI, name, name, "CDATA", uri, false);
}
else
{
if (!EMPTYSTRING.equals(uri))
// hack for XSLTC attribset16 test
{ // that maps ns1 prefix to "" URI
name = "xmlns:" + prefix;
/* for something like xmlns:abc="w3.pretend.org"
* the uri is the value, that is why we pass it in the
* value, or 5th slot of addAttributeAlways()
*/
addAttributeAlways(XMLNS_URI, prefix, name, "CDATA", uri, false);
}
}
}
return pushed;
}
// in src/org/apache/xml/serializer/ToStream.java
public void comment(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
int start_old = start;
if (m_inEntityRef)
return;
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
else if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
try
{
final int limit = start + length;
boolean wasDash = false;
if (m_cdataTagOpen)
closeCDATA();
if (shouldIndent())
indent();
final java.io.Writer writer = m_writer;
writer.write(COMMENT_BEGIN);
// Detect occurrences of two consecutive dashes, handle as necessary.
for (int i = start; i < limit; i++)
{
if (wasDash && ch[i] == '-')
{
writer.write(ch, start, i - start);
writer.write(" -");
start = i + 1;
}
wasDash = (ch[i] == '-');
}
// if we have some chars in the comment
if (length > 0)
{
// Output the remaining characters (if any)
final int remainingChars = (limit - start);
if (remainingChars > 0)
writer.write(ch, start, remainingChars);
// Protect comment end from a single trailing dash
if (ch[limit - 1] == '-')
writer.write(' ');
}
writer.write(COMMENT_END);
}
catch (IOException e)
{
throw new SAXException(e);
}
/*
* Don't write out any indentation whitespace now,
* because there may be non-whitespace text after this.
*
* Simply mark that at this point if we do decide
* to indent that we should
* add a newline on the end of the current line before
* the indentation at the start of the next line.
*/
m_startNewLine = true;
// time to generate comment event
if (m_tracer != null)
super.fireCommentEvent(ch, start_old,length);
}
// in src/org/apache/xml/serializer/ToStream.java
public void endCDATA() throws org.xml.sax.SAXException
{
if (m_cdataTagOpen)
closeCDATA();
m_cdataStartCalled = false;
}
// in src/org/apache/xml/serializer/ToStream.java
public void endDTD() throws org.xml.sax.SAXException
{
try
{
if (m_needToOutputDocTypeDecl)
{
outputDocTypeDecl(m_elemContext.m_elementName, false);
m_needToOutputDocTypeDecl = false;
}
final java.io.Writer writer = m_writer;
if (!m_inDoctype)
writer.write("]>");
else
{
writer.write('>');
}
writer.write(m_lineSep, 0, m_lineSepLen);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException
{ // do nothing
}
// in src/org/apache/xml/serializer/ToStream.java
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if (0 == length)
return;
characters(ch, start, length);
}
// in src/org/apache/xml/serializer/ToStream.java
public void skippedEntity(String name) throws org.xml.sax.SAXException
{ // TODO: Should handle
}
// in src/org/apache/xml/serializer/ToStream.java
public void startCDATA() throws org.xml.sax.SAXException
{
m_cdataStartCalled = true;
}
// in src/org/apache/xml/serializer/ToStream.java
public void startEntity(String name) throws org.xml.sax.SAXException
{
if (name.equals("[dtd]"))
m_inExternalDTD = true;
if (!m_expandDTDEntities && !m_inExternalDTD) {
/* Only leave the entity as-is if
* we've been told not to expand them
* and this is not the magic [dtd] name.
*/
startNonEscaping();
characters("&" + name + ';');
endNonEscaping();
}
m_inEntityRef = true;
}
// in src/org/apache/xml/serializer/ToStream.java
protected void closeStartTag() throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
try
{
if (m_tracer != null)
super.fireStartElem(m_elemContext.m_elementName);
int nAttrs = m_attributes.getLength();
if (nAttrs > 0)
{
processAttributes(m_writer, nAttrs);
// clear attributes object for re-use with next element
m_attributes.clear();
}
m_writer.write('>');
}
catch (IOException e)
{
throw new SAXException(e);
}
/* whether Xalan or XSLTC, we have the prefix mappings now, so
* lets determine if the current element is specified in the cdata-
* section-elements list.
*/
if (m_CdataElems != null)
m_elemContext.m_isCdataSection = isCdataSection();
if (m_doIndent)
{
m_isprevtext = false;
m_preserves.push(m_ispreserve);
}
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void startDTD(String name, String publicId, String systemId)
throws org.xml.sax.SAXException
{
setDoctypeSystem(systemId);
setDoctypePublic(publicId);
m_elemContext.m_elementName = name;
m_inDoctype = true;
}
// in src/org/apache/xml/serializer/ToStream.java
protected String ensureAttributesNamespaceIsDeclared(
String ns,
String localName,
String rawName)
throws org.xml.sax.SAXException
{
if (ns != null && ns.length() > 0)
{
// extract the prefix in front of the raw name
int index = 0;
String prefixFromRawName =
(index = rawName.indexOf(":")) < 0
? ""
: rawName.substring(0, index);
if (index > 0)
{
// we have a prefix, lets see if it maps to a namespace
String uri = m_prefixMap.lookupNamespace(prefixFromRawName);
if (uri != null && uri.equals(ns))
{
// the prefix in the raw name is already maps to the given namespace uri
// so we don't need to do anything
return null;
}
else
{
// The uri does not map to the prefix in the raw name,
// so lets make the mapping.
this.startPrefixMapping(prefixFromRawName, ns, false);
this.addAttribute(
"http://www.w3.org/2000/xmlns/",
prefixFromRawName,
"xmlns:" + prefixFromRawName,
"CDATA",
ns, false);
return prefixFromRawName;
}
}
else
{
// we don't have a prefix in the raw name.
// Does the URI map to a prefix already?
String prefix = m_prefixMap.lookupPrefix(ns);
if (prefix == null)
{
// uri is not associated with a prefix,
// so lets generate a new prefix to use
prefix = m_prefixMap.generateNextPrefix();
this.startPrefixMapping(prefix, ns, false);
this.addAttribute(
"http://www.w3.org/2000/xmlns/",
prefix,
"xmlns:" + prefix,
"CDATA",
ns, false);
}
return prefix;
}
}
return null;
}
// in src/org/apache/xml/serializer/ToStream.java
void ensurePrefixIsDeclared(String ns, String rawName)
throws org.xml.sax.SAXException
{
if (ns != null && ns.length() > 0)
{
int index;
final boolean no_prefix = ((index = rawName.indexOf(":")) < 0);
String prefix = (no_prefix) ? "" : rawName.substring(0, index);
if (null != prefix)
{
String foundURI = m_prefixMap.lookupNamespace(prefix);
if ((null == foundURI) || !foundURI.equals(ns))
{
this.startPrefixMapping(prefix, ns);
// Bugzilla1133: Generate attribute as well as namespace event.
// SAX does expect both.
this.addAttributeAlways(
"http://www.w3.org/2000/xmlns/",
no_prefix ? "xmlns" : prefix, // local name
no_prefix ? "xmlns" : ("xmlns:"+ prefix), // qname
"CDATA",
ns,
false);
}
}
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void flushPending() throws SAXException
{
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
if (m_cdataTagOpen)
{
closeCDATA();
m_cdataTagOpen = false;
}
if (m_writer != null) {
try {
m_writer.flush();
}
catch(IOException e) {
// what? me worry?
}
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void notationDecl(String name, String pubID, String sysID) throws SAXException {
// TODO Auto-generated method stub
try {
DTDprolog();
m_writer.write("<!NOTATION ");
m_writer.write(name);
if (pubID != null) {
m_writer.write(" PUBLIC \"");
m_writer.write(pubID);
}
else {
m_writer.write(" SYSTEM \"");
m_writer.write(sysID);
}
m_writer.write("\" >");
m_writer.write(m_lineSep, 0, m_lineSepLen);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// in src/org/apache/xml/serializer/ToStream.java
public void unparsedEntityDecl(String name, String pubID, String sysID, String notationName) throws SAXException {
// TODO Auto-generated method stub
try {
DTDprolog();
m_writer.write("<!ENTITY ");
m_writer.write(name);
if (pubID != null) {
m_writer.write(" PUBLIC \"");
m_writer.write(pubID);
}
else {
m_writer.write(" SYSTEM \"");
m_writer.write(sysID);
}
m_writer.write("\" NDATA ");
m_writer.write(notationName);
m_writer.write(" >");
m_writer.write(m_lineSep, 0, m_lineSepLen);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// in src/org/apache/xml/serializer/ToStream.java
private void DTDprolog() throws SAXException, IOException {
final java.io.Writer writer = m_writer;
if (m_needToOutputDocTypeDecl)
{
outputDocTypeDecl(m_elemContext.m_elementName, false);
m_needToOutputDocTypeDecl = false;
}
if (m_inDoctype)
{
writer.write(" [");
writer.write(m_lineSep, 0, m_lineSepLen);
m_inDoctype = false;
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
protected void startDocumentInternal() throws SAXException
{
if (m_needToCallStartDocument)
{
super.startDocumentInternal();
m_saxHandler.startDocument();
m_needToCallStartDocument = false;
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void startDTD(String arg0, String arg1, String arg2)
throws SAXException
{
// do nothing for now
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void characters(String characters) throws SAXException
{
final int len = characters.length();
if (len > m_charsBuff.length)
{
m_charsBuff = new char[len*2 + 1];
}
characters.getChars(0,len, m_charsBuff, 0);
characters(m_charsBuff, 0, len);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void comment(String comment) throws SAXException
{
flushPending();
// Ignore if a lexical handler has not been set
if (m_lexHandler != null)
{
final int len = comment.length();
if (len > m_charsBuff.length)
{
m_charsBuff = new char[len*2 + 1];
}
comment.getChars(0,len, m_charsBuff, 0);
m_lexHandler.comment(m_charsBuff, 0, len);
// time to fire off comment event
if (m_tracer != null)
super.fireCommentEvent(m_charsBuff, 0, len);
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void processingInstruction(String target, String data)
throws SAXException
{
// Redefined in SAXXMLOutput
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
protected void closeStartTag() throws SAXException
{
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
protected void closeCDATA() throws SAXException
{
// Redefined in SAXXMLOutput
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void startElement(
String arg0,
String arg1,
String arg2,
Attributes arg3)
throws SAXException
{
if (m_state != null) {
m_state.resetState(getTransformer());
}
// fire off the start element event
if (m_tracer != null)
super.fireStartElem(arg2);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void flushPending() throws SAXException
{
if (m_needToCallStartDocument)
{
startDocumentInternal();
m_needToCallStartDocument = false;
}
if (m_elemContext.m_startTagOpen)
{
closeStartTag();
m_elemContext.m_startTagOpen = false;
}
if (m_cdataTagOpen)
{
closeCDATA();
m_cdataTagOpen = false;
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void startElement(String uri, String localName, String qName)
throws SAXException {
if (m_state != null) {
m_state.resetState(getTransformer());
}
// fire off the start element event
if (m_tracer != null)
super.fireStartElem(qName);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void startElement(String qName) throws SAXException {
if (m_state != null) {
m_state.resetState(getTransformer());
}
// fire off the start element event
if (m_tracer != null)
super.fireStartElem(qName);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void characters(org.w3c.dom.Node node)
throws org.xml.sax.SAXException
{
// remember the current node
if (m_state != null)
{
m_state.setCurrentNode(node);
}
// Get the node's value as a String and use that String as if
// it were an input character notification.
String data = node.getNodeValue();
if (data != null) {
this.characters(data);
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void fatalError(SAXParseException exc) throws SAXException {
super.fatalError(exc);
m_needToCallStartDocument = false;
if (m_saxHandler instanceof ErrorHandler) {
((ErrorHandler)m_saxHandler).fatalError(exc);
}
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void error(SAXParseException exc) throws SAXException {
super.error(exc);
if (m_saxHandler instanceof ErrorHandler)
((ErrorHandler)m_saxHandler).error(exc);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void warning(SAXParseException exc) throws SAXException {
super.warning(exc);
if (m_saxHandler instanceof ErrorHandler)
((ErrorHandler)m_saxHandler).warning(exc);
}
// in src/org/apache/xml/serializer/ToSAXHandler.java
public void addUniqueAttribute(String qName, String value, int flags)
throws SAXException
{
addAttribute(qName, value);
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
public void traverse(Node pos) throws org.xml.sax.SAXException {
this.fSerializer.startDocument();
// Determine if the Node is a DOM Level 3 Core Node.
if (pos.getNodeType() != Node.DOCUMENT_NODE) {
Document ownerDoc = pos.getOwnerDocument();
if (ownerDoc != null
&& ownerDoc.getImplementation().hasFeature("Core", "3.0")) {
fIsLevel3DOM = true;
}
} else {
if (((Document) pos)
.getImplementation()
.hasFeature("Core", "3.0")) {
fIsLevel3DOM = true;
}
}
if (fSerializer instanceof LexicalHandler) {
fLexicalHandler = ((LexicalHandler) this.fSerializer);
}
if (fFilter != null)
fWhatToShowFilter = fFilter.getWhatToShow();
Node top = pos;
while (null != pos) {
startNode(pos);
Node nextNode = null;
nextNode = pos.getFirstChild();
while (null == nextNode) {
endNode(pos);
if (top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode) {
pos = pos.getParentNode();
if ((null == pos) || (top.equals(pos))) {
if (null != pos)
endNode(pos);
nextNode = null;
break;
}
}
}
pos = nextNode;
}
this.fSerializer.endDocument();
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
public void traverse(Node pos, Node top) throws org.xml.sax.SAXException {
this.fSerializer.startDocument();
// Determine if the Node is a DOM Level 3 Core Node.
if (pos.getNodeType() != Node.DOCUMENT_NODE) {
Document ownerDoc = pos.getOwnerDocument();
if (ownerDoc != null
&& ownerDoc.getImplementation().hasFeature("Core", "3.0")) {
fIsLevel3DOM = true;
}
} else {
if (((Document) pos)
.getImplementation()
.hasFeature("Core", "3.0")) {
fIsLevel3DOM = true;
}
}
if (fSerializer instanceof LexicalHandler) {
fLexicalHandler = ((LexicalHandler) this.fSerializer);
}
if (fFilter != null)
fWhatToShowFilter = fFilter.getWhatToShow();
while (null != pos) {
startNode(pos);
Node nextNode = null;
nextNode = pos.getFirstChild();
while (null == nextNode) {
endNode(pos);
if ((null != top) && top.equals(pos))
break;
nextNode = pos.getNextSibling();
if (null == nextNode) {
pos = pos.getParentNode();
if ((null == pos) || ((null != top) && top.equals(pos))) {
nextNode = null;
break;
}
}
}
pos = nextNode;
}
this.fSerializer.endDocument();
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
private final void dispatachChars(Node node)
throws org.xml.sax.SAXException {
if (fSerializer != null) {
this.fSerializer.characters(node);
} else {
String data = ((Text) node).getData();
this.fSerializer.characters(data.toCharArray(), 0, data.length());
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void startNode(Node node) throws org.xml.sax.SAXException {
if (node instanceof Locator) {
Locator loc = (Locator) node;
fLocator.setColumnNumber(loc.getColumnNumber());
fLocator.setLineNumber(loc.getLineNumber());
fLocator.setPublicId(loc.getPublicId());
fLocator.setSystemId(loc.getSystemId());
} else {
fLocator.setColumnNumber(0);
fLocator.setLineNumber(0);
}
switch (node.getNodeType()) {
case Node.DOCUMENT_TYPE_NODE :
serializeDocType((DocumentType) node, true);
break;
case Node.COMMENT_NODE :
serializeComment((Comment) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE :
// Children are traversed
break;
case Node.DOCUMENT_NODE :
break;
case Node.ELEMENT_NODE :
serializeElement((Element) node, true);
break;
case Node.PROCESSING_INSTRUCTION_NODE :
serializePI((ProcessingInstruction) node);
break;
case Node.CDATA_SECTION_NODE :
serializeCDATASection((CDATASection) node);
break;
case Node.TEXT_NODE :
serializeText((Text) node);
break;
case Node.ENTITY_REFERENCE_NODE :
serializeEntityReference((EntityReference) node, true);
break;
default :
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void endNode(Node node) throws org.xml.sax.SAXException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE :
break;
case Node.DOCUMENT_TYPE_NODE :
serializeDocType((DocumentType) node, false);
break;
case Node.ELEMENT_NODE :
serializeElement((Element) node, false);
break;
case Node.CDATA_SECTION_NODE :
break;
case Node.ENTITY_REFERENCE_NODE :
serializeEntityReference((EntityReference) node, false);
break;
default :
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeDocType(DocumentType node, boolean bStart)
throws SAXException {
// The DocType and internalSubset can not be modified in DOM and is
// considered to be well-formed as the outcome of successful parsing.
String docTypeName = node.getNodeName();
String publicId = node.getPublicId();
String systemId = node.getSystemId();
String internalSubset = node.getInternalSubset();
//DocumentType nodes are never passed to the filter
if (internalSubset != null && !"".equals(internalSubset)) {
if (bStart) {
try {
// The Serializer does not provide a way to write out the
// DOCTYPE internal subset via an event call, so we write it
// out here.
Writer writer = fSerializer.getWriter();
StringBuffer dtd = new StringBuffer();
dtd.append("<!DOCTYPE ");
dtd.append(docTypeName);
if (null != publicId) {
dtd.append(" PUBLIC \"");
dtd.append(publicId);
dtd.append('\"');
}
if (null != systemId) {
if (null == publicId) {
dtd.append(" SYSTEM \"");
} else {
dtd.append(" \"");
}
dtd.append(systemId);
dtd.append('\"');
}
dtd.append(" [ ");
dtd.append(fNewLine);
dtd.append(internalSubset);
dtd.append("]>");
dtd.append(fNewLine);
writer.write(dtd.toString());
writer.flush();
} catch (IOException e) {
throw new SAXException(Utils.messages.createMessage(
MsgKey.ER_WRITING_INTERNAL_SUBSET, null), e);
}
} // else if !bStart do nothing
} else {
if (bStart) {
if (fLexicalHandler != null) {
fLexicalHandler.startDTD(docTypeName, publicId, systemId);
}
} else {
if (fLexicalHandler != null) {
fLexicalHandler.endDTD();
}
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeComment(Comment node) throws SAXException {
// comments=true
if ((fFeatures & COMMENTS) != 0) {
String data = node.getData();
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isCommentWellFormed(data);
}
if (fLexicalHandler != null) {
// apply the LSSerializer filter after the operations requested by the
// DOMConfiguration parameters have been applied
if (!applyFilter(node, NodeFilter.SHOW_COMMENT)) {
return;
}
fLexicalHandler.comment(data.toCharArray(), 0, data.length());
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeElement(Element node, boolean bStart)
throws SAXException {
if (bStart) {
fElementDepth++;
// We use the Xalan specific startElement and starPrefixMapping calls
// (and addAttribute and namespaceAfterStartElement) as opposed to
// SAX specific, for performance reasons as they reduce the overhead
// of creating an AttList object upfront.
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isElementWellFormed(node);
}
// REVISIT: We apply the LSSerializer filter for elements before
// namesapce fixup
if (!applyFilter(node, NodeFilter.SHOW_ELEMENT)) {
return;
}
// namespaces=true, record and fixup namspaced element
if ((fFeatures & NAMESPACES) != 0) {
fNSBinder.pushContext();
fLocalNSBinder.reset();
recordLocalNSDecl(node);
fixupElementNS(node);
}
// Namespace normalization
fSerializer.startElement(
node.getNamespaceURI(),
node.getLocalName(),
node.getNodeName());
serializeAttList(node);
} else {
fElementDepth--;
// apply the LSSerializer filter
if (!applyFilter(node, NodeFilter.SHOW_ELEMENT)) {
return;
}
this.fSerializer.endElement(
node.getNamespaceURI(),
node.getLocalName(),
node.getNodeName());
// since endPrefixMapping was not used by SerializationHandler it was removed
// for performance reasons.
if ((fFeatures & NAMESPACES) != 0 ) {
fNSBinder.popContext();
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeAttList(Element node) throws SAXException {
NamedNodeMap atts = node.getAttributes();
int nAttrs = atts.getLength();
for (int i = 0; i < nAttrs; i++) {
Node attr = atts.item(i);
String localName = attr.getLocalName();
String attrName = attr.getNodeName();
String attrPrefix = attr.getPrefix() == null ? "" : attr.getPrefix();
String attrValue = attr.getNodeValue();
// Determine the Attr's type.
String type = null;
if (fIsLevel3DOM) {
type = ((Attr) attr).getSchemaTypeInfo().getTypeName();
}
type = type == null ? "CDATA" : type;
String attrNS = attr.getNamespaceURI();
if (attrNS !=null && attrNS.length() == 0) {
attrNS=null;
// we must remove prefix for this attribute
attrName=attr.getLocalName();
}
boolean isSpecified = ((Attr) attr).getSpecified();
boolean addAttr = true;
boolean applyFilter = false;
boolean xmlnsAttr =
attrName.equals("xmlns") || attrName.startsWith("xmlns:");
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isAttributeWellFormed(attr);
}
//-----------------------------------------------------------------
// start Attribute namespace fixup
//-----------------------------------------------------------------
// namespaces=true, normalize all non-namespace attributes
// Step 3. Attribute
if ((fFeatures & NAMESPACES) != 0 && !xmlnsAttr) {
// If the Attr has a namespace URI
if (attrNS != null) {
attrPrefix = attrPrefix == null ? "" : attrPrefix;
String declAttrPrefix = fNSBinder.getPrefix(attrNS);
String declAttrNS = fNSBinder.getURI(attrPrefix);
// attribute has no prefix (default namespace decl does not apply to
// attributes)
// OR
// attribute prefix is not declared
// OR
// conflict: attribute has a prefix that conflicts with a binding
if ("".equals(attrPrefix) || "".equals(declAttrPrefix)
|| !attrPrefix.equals(declAttrPrefix)) {
// namespaceURI matches an in scope declaration of one or
// more prefixes
if (declAttrPrefix != null && !"".equals(declAttrPrefix)) {
// pick the prefix that was found and change attribute's
// prefix and nodeName.
attrPrefix = declAttrPrefix;
if (declAttrPrefix.length() > 0 ) {
attrName = declAttrPrefix + ":" + localName;
} else {
attrName = localName;
}
} else {
// The current prefix is not null and it has no in scope
// declaration
if (attrPrefix != null && !"".equals(attrPrefix)
&& declAttrNS == null) {
// declare this prefix
if ((fFeatures & NAMESPACEDECLS) != 0) {
fSerializer.addAttribute(XMLNS_URI, attrPrefix,
XMLNS_PREFIX + ":" + attrPrefix, "CDATA",
attrNS);
fNSBinder.declarePrefix(attrPrefix, attrNS);
fLocalNSBinder.declarePrefix(attrPrefix, attrNS);
}
} else {
// find a prefix following the pattern "NS" +index
// (starting at 1)
// make sure this prefix is not declared in the current
// scope.
int counter = 1;
attrPrefix = "NS" + counter++;
while (fLocalNSBinder.getURI(attrPrefix) != null) {
attrPrefix = "NS" + counter++;
}
// change attribute's prefix and Name
attrName = attrPrefix + ":" + localName;
// create a local namespace declaration attribute
// Add the xmlns declaration attribute
if ((fFeatures & NAMESPACEDECLS) != 0) {
fSerializer.addAttribute(XMLNS_URI, attrPrefix,
XMLNS_PREFIX + ":" + attrPrefix, "CDATA",
attrNS);
fNSBinder.declarePrefix(attrPrefix, attrNS);
fLocalNSBinder.declarePrefix(attrPrefix, attrNS);
}
}
}
}
} else { // if the Attr has no namespace URI
// Attr has no localName
if (localName == null) {
// DOM Level 1 node!
String msg = Utils.messages.createMessage(
MsgKey.ER_NULL_LOCAL_ELEMENT_NAME,
new Object[] { attrName });
if (fErrorHandler != null) {
fErrorHandler
.handleError(new DOMErrorImpl(
DOMError.SEVERITY_ERROR, msg,
MsgKey.ER_NULL_LOCAL_ELEMENT_NAME, null,
null, null));
}
} else { // uri=null and no colon
// attr has no namespace URI and no prefix
// no action is required, since attrs don't use default
}
}
}
// discard-default-content=true
// Default attr's are not passed to the filter and this contraint
// is applied only when discard-default-content=true
// What about default xmlns attributes???? check for xmlnsAttr
if ((((fFeatures & DISCARDDEFAULT) != 0) && isSpecified)
|| ((fFeatures & DISCARDDEFAULT) == 0)) {
applyFilter = true;
} else {
addAttr = false;
}
if (applyFilter) {
// apply the filter for Attributes that are not default attributes
// or namespace decl attributes
if (fFilter != null
&& (fFilter.getWhatToShow() & NodeFilter.SHOW_ATTRIBUTE)
!= 0) {
if (!xmlnsAttr) {
short code = fFilter.acceptNode(attr);
switch (code) {
case NodeFilter.FILTER_REJECT :
case NodeFilter.FILTER_SKIP :
addAttr = false;
break;
default : //fall through..
}
}
}
}
// if the node is a namespace node
if (addAttr && xmlnsAttr) {
// If namespace-declarations=true, add the node , else don't add it
if ((fFeatures & NAMESPACEDECLS) != 0) {
// The namespace may have been fixed up, in that case don't add it.
if (localName != null && !"".equals(localName)) {
fSerializer.addAttribute(attrNS, localName, attrName, type, attrValue);
}
}
} else if (
addAttr && !xmlnsAttr) { // if the node is not a namespace node
// If namespace-declarations=true, add the node with the Attr nodes namespaceURI
// else add the node setting it's namespace to null or else the serializer will later
// attempt to add a xmlns attr for the prefixed attribute
if (((fFeatures & NAMESPACEDECLS) != 0) && (attrNS != null)) {
fSerializer.addAttribute(
attrNS,
localName,
attrName,
type,
attrValue);
} else {
fSerializer.addAttribute(
"",
localName,
attrName,
type,
attrValue);
}
}
//
if (xmlnsAttr && ((fFeatures & NAMESPACEDECLS) != 0)) {
int index;
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
String prefix =
(index = attrName.indexOf(":")) < 0
? ""
: attrName.substring(index + 1);
if (!"".equals(prefix)) {
fSerializer.namespaceAfterStartElement(prefix, attrValue);
}
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializePI(ProcessingInstruction node)
throws SAXException {
ProcessingInstruction pi = node;
String name = pi.getNodeName();
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isPIWellFormed(node);
}
// apply the LSSerializer filter
if (!applyFilter(node, NodeFilter.SHOW_PROCESSING_INSTRUCTION)) {
return;
}
// String data = pi.getData();
if (name.equals("xslt-next-is-raw")) {
fNextIsRaw = true;
} else {
this.fSerializer.processingInstruction(name, pi.getData());
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeCDATASection(CDATASection node)
throws SAXException {
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isCDATASectionWellFormed(node);
}
// cdata-sections = true
if ((fFeatures & CDATA) != 0) {
// split-cdata-sections = true
// Assumption: This parameter has an effect only when
// cdata-sections=true
// ToStream, by default splits cdata-sections. Hence the check
// below.
String nodeValue = node.getNodeValue();
int endIndex = nodeValue.indexOf("]]>");
if ((fFeatures & SPLITCDATA) != 0) {
if (endIndex >= 0) {
// The first node split will contain the ]] markers
String relatedData = nodeValue.substring(0, endIndex + 2);
String msg =
Utils.messages.createMessage(
MsgKey.ER_CDATA_SECTIONS_SPLIT,
null);
if (fErrorHandler != null) {
fErrorHandler.handleError(
new DOMErrorImpl(
DOMError.SEVERITY_WARNING,
msg,
MsgKey.ER_CDATA_SECTIONS_SPLIT,
null,
relatedData,
null));
}
}
} else {
if (endIndex >= 0) {
// The first node split will contain the ]] markers
String relatedData = nodeValue.substring(0, endIndex + 2);
String msg =
Utils.messages.createMessage(
MsgKey.ER_CDATA_SECTIONS_SPLIT,
null);
if (fErrorHandler != null) {
fErrorHandler.handleError(
new DOMErrorImpl(
DOMError.SEVERITY_ERROR,
msg,
MsgKey.ER_CDATA_SECTIONS_SPLIT));
}
// Report an error and return. What error???
return;
}
}
// apply the LSSerializer filter
if (!applyFilter(node, NodeFilter.SHOW_CDATA_SECTION)) {
return;
}
// splits the cdata-section
if (fLexicalHandler != null) {
fLexicalHandler.startCDATA();
}
dispatachChars(node);
if (fLexicalHandler != null) {
fLexicalHandler.endCDATA();
}
} else {
dispatachChars(node);
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeText(Text node) throws SAXException {
if (fNextIsRaw) {
fNextIsRaw = false;
fSerializer.processingInstruction(
javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING,
"");
dispatachChars(node);
fSerializer.processingInstruction(
javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING,
"");
} else {
// keep track of dispatch or not to avoid duplicaiton of filter code
boolean bDispatch = false;
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isTextWellFormed(node);
}
// if the node is whitespace
// Determine the Attr's type.
boolean isElementContentWhitespace = false;
if (fIsLevel3DOM) {
isElementContentWhitespace =
node.isElementContentWhitespace();
}
if (isElementContentWhitespace) {
// element-content-whitespace=true
if ((fFeatures & ELEM_CONTENT_WHITESPACE) != 0) {
bDispatch = true;
}
} else {
bDispatch = true;
}
// apply the LSSerializer filter
if (!applyFilter(node, NodeFilter.SHOW_TEXT)) {
return;
}
if (bDispatch) {
dispatachChars(node);
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void serializeEntityReference(
EntityReference node,
boolean bStart)
throws SAXException {
if (bStart) {
EntityReference eref = node;
// entities=true
if ((fFeatures & ENTITIES) != 0) {
// perform well-formedness and other checking only if
// entities = true
// well-formed=true
if ((fFeatures & WELLFORMED) != 0) {
isEntityReferneceWellFormed(node);
}
// check "unbound-prefix-in-entity-reference" [fatal]
// Raised if the configuration parameter "namespaces" is set to true
if ((fFeatures & NAMESPACES) != 0) {
checkUnboundPrefixInEntRef(node);
}
// The filter should not apply in this case, since the
// EntityReference is not being expanded.
// should we pass entity reference nodes to the filter???
}
if (fLexicalHandler != null) {
// startEntity outputs only Text but not Element, Attr, Comment
// and PI child nodes. It does so by setting the m_inEntityRef
// in ToStream and using this to decide if a node is to be
// serialized or not.
fLexicalHandler.startEntity(eref.getNodeName());
}
} else {
EntityReference eref = node;
// entities=true or false,
if (fLexicalHandler != null) {
fLexicalHandler.endEntity(eref.getNodeName());
}
}
}
// in src/org/apache/xml/serializer/dom3/DOM3TreeWalker.java
protected void fixupElementNS(Node node) throws SAXException {
String namespaceURI = ((Element) node).getNamespaceURI();
String prefix = ((Element) node).getPrefix();
String localName = ((Element) node).getLocalName();
if (namespaceURI != null) {
//if ( Element's prefix/namespace pair (or default namespace,
// if no prefix) are within the scope of a binding )
prefix = prefix == null ? "" : prefix;
String inScopeNamespaceURI = fNSBinder.getURI(prefix);
if ((inScopeNamespaceURI != null
&& inScopeNamespaceURI.equals(namespaceURI))) {
// do nothing, declaration in scope is inherited
} else {
// Create a local namespace declaration attr for this namespace,
// with Element's current prefix (or a default namespace, if
// no prefix). If there's a conflicting local declaration
// already present, change its value to use this namespace.
// Add the xmlns declaration attribute
//fNSBinder.pushNamespace(prefix, namespaceURI, fElementDepth);
if ((fFeatures & NAMESPACEDECLS) != 0) {
if ("".equals(prefix) || "".equals(namespaceURI)) {
((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX, namespaceURI);
} else {
((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX + ":" + prefix, namespaceURI);
}
}
fLocalNSBinder.declarePrefix(prefix, namespaceURI);
fNSBinder.declarePrefix(prefix, namespaceURI);
}
} else {
// Element has no namespace
// DOM Level 1
if (localName == null || "".equals(localName)) {
// DOM Level 1 node!
String msg =
Utils.messages.createMessage(
MsgKey.ER_NULL_LOCAL_ELEMENT_NAME,
new Object[] { node.getNodeName()});
if (fErrorHandler != null) {
fErrorHandler.handleError(
new DOMErrorImpl(
DOMError.SEVERITY_ERROR,
msg,
MsgKey.ER_NULL_LOCAL_ELEMENT_NAME,
null,
null,
null));
}
} else {
namespaceURI = fNSBinder.getURI("");
if (namespaceURI !=null && namespaceURI.length() > 0) {
((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX, "");
fLocalNSBinder.declarePrefix("", "");
fNSBinder.declarePrefix("", "");
}
}
}
}
// in src/org/apache/xml/serializer/EmptySerializer.java
protected void couldThrowSAXException() throws SAXException
{
return; // don't do anything.
}
// in src/org/apache/xml/serializer/EmptySerializer.java
protected void couldThrowSAXException(char[] chars, int off, int len) throws SAXException
{
return; // don't do anything.
}
// in src/org/apache/xml/serializer/EmptySerializer.java
protected void couldThrowSAXException(String elemQName) throws SAXException
{
return; // don't do anything.
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public boolean setEscaping(boolean escape) throws SAXException
{
couldThrowSAXException();
return false;
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void flushPending() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void addAttribute(
String uri,
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void addAttributes(Attributes atts) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void characters(String chars) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endElement(String elemName) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startDocument() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startElement(String uri, String localName, String qName)
throws SAXException
{
couldThrowSAXException(qName);
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startElement(String qName) throws SAXException
{
couldThrowSAXException(qName);
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void namespaceAfterStartElement(String uri, String prefix)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public boolean startPrefixMapping(
String prefix,
String uri,
boolean shouldFlush)
throws SAXException
{
couldThrowSAXException();
return false;
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void entityReference(String entityName) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endDocument() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startPrefixMapping(String arg0, String arg1)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endPrefixMapping(String arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startElement(
String arg0,
String arg1,
String arg2,
Attributes arg3)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endElement(String arg0, String arg1, String arg2)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void characters(char[] arg0, int arg1, int arg2) throws SAXException
{
couldThrowSAXException(arg0, arg1, arg2);
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void processingInstruction(String arg0, String arg1)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void skippedEntity(String arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void comment(String comment) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startDTD(String arg0, String arg1, String arg2)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endDTD() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startEntity(String arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endEntity(String arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void startCDATA() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void endCDATA() throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void comment(char[] arg0, int arg1, int arg2) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void elementDecl(String arg0, String arg1) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void attributeDecl(
String arg0,
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void internalEntityDecl(String arg0, String arg1)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void externalEntityDecl(String arg0, String arg1, String arg2)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void warning(SAXParseException arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void error(SAXParseException arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void fatalError(SAXParseException arg0) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void addUniqueAttribute(String name, String value, int flags)
throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void characters(Node node) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void notationDecl(String arg0, String arg1, String arg2) throws SAXException
{
couldThrowSAXException();
}
// in src/org/apache/xml/serializer/EmptySerializer.java
public void unparsedEntityDecl(
String arg0,
String arg1,
String arg2,
String arg3)
throws SAXException {
couldThrowSAXException();
}
// in src/org/apache/xalan/xsltc/runtime/StringValueHandler.java
public void characters(char[] ch, int off, int len)
throws SAXException
{
if (_nestedLevel > 0)
return;
if (_str != null) {
_buffer.append(_str);
_str = null;
}
_buffer.append(ch, off, len);
}
// in src/org/apache/xalan/xsltc/runtime/StringValueHandler.java
public void characters(String characters) throws SAXException {
if (_nestedLevel > 0)
return;
if (_str == null && _buffer.length() == 0) {
_str = characters;
}
else {
if (_str != null) {
_buffer.append(_str);
_str = null;
}
_buffer.append(characters);
}
}
// in src/org/apache/xalan/xsltc/runtime/StringValueHandler.java
public void startElement(String qname) throws SAXException {
_nestedLevel++;
}
// in src/org/apache/xalan/xsltc/runtime/StringValueHandler.java
public void endElement(String qname) throws SAXException {
_nestedLevel--;
}
// in src/org/apache/xalan/xsltc/compiler/Parser.java
public void startElement(String uri, String localname,
String qname, Attributes attributes)
throws SAXException {
final int col = qname.lastIndexOf(':');
final String prefix = (col == -1) ? null : qname.substring(0, col);
SyntaxTreeNode element = makeInstance(uri, prefix,
localname, attributes);
if (element == null) {
ErrorMsg err = new ErrorMsg(ErrorMsg.ELEMENT_PARSE_ERR,
prefix+':'+localname);
throw new SAXException(err.toString());
}
// If this is the root element of the XML document we need to make sure
// that it contains a definition of the XSL namespace URI
if (_root == null) {
if ((_prefixMapping == null) ||
(_prefixMapping.containsValue(Constants.XSLT_URI) == false))
_rootNamespaceDef = false;
else
_rootNamespaceDef = true;
_root = element;
}
else {
SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
parent.addElement(element);
element.setParent(parent);
}
element.setAttributes(new AttributeList(attributes));
element.setPrefixMapping(_prefixMapping);
if (element instanceof Stylesheet) {
// Extension elements and excluded elements have to be
// handled at this point in order to correctly generate
// Fallback elements from <xsl:fallback>s.
getSymbolTable().setCurrentNode(element);
((Stylesheet)element).declareExtensionPrefixes(this);
}
_prefixMapping = null;
_parentStack.push(element);
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void startDocument() throws SAXException
{
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void endDocument() throws SAXException
{
// Set the String value when the document is built.
if (_size == 1)
_text = _textArray[0];
else {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < _size; i++) {
buffer.append(_textArray[i]);
}
_text = buffer.toString();
}
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void characters(String str) throws SAXException
{
// Resize the text array if necessary
if (_size >= _textArray.length) {
String[] newTextArray = new String[_textArray.length * 2];
System.arraycopy(_textArray, 0, newTextArray, 0, _textArray.length);
_textArray = newTextArray;
}
// If the escape setting is false, set the corresponding bit in
// the _dontEscape BitArray.
if (!_escaping) {
// The _dontEscape array is only created when needed.
if (_dontEscape == null) {
_dontEscape = new BitArray(8);
}
// Resize the _dontEscape array if necessary
if (_size >= _dontEscape.size())
_dontEscape.resize(_dontEscape.size() * 2);
_dontEscape.setBit(_size);
}
_textArray[_size++] = str;
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void characters(char[] ch, int offset, int length)
throws SAXException
{
if (_size >= _textArray.length) {
String[] newTextArray = new String[_textArray.length * 2];
System.arraycopy(_textArray, 0, newTextArray, 0, _textArray.length);
_textArray = newTextArray;
}
if (!_escaping) {
if (_dontEscape == null) {
_dontEscape = new BitArray(8);
}
if (_size >= _dontEscape.size())
_dontEscape.resize(_dontEscape.size() * 2);
_dontEscape.setBit(_size);
}
_textArray[_size++] = new String(ch, offset, length);
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public boolean setEscaping(boolean escape) throws SAXException
{
final boolean temp = _escaping;
_escaping = escape;
return temp;
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void dispatchCharactersEvents(
int nodeHandle,
org.xml.sax.ContentHandler ch,
boolean normalize)
throws org.xml.sax.SAXException
{
}
// in src/org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.java
public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
private void maybeEmitStartElement() throws SAXException
{
if (_openElementName != null) {
int index;
if ((index =_openElementName.indexOf(":")) < 0)
_dom.startElement(null, _openElementName, _openElementName, _attributes);
else
_dom.startElement(null, _openElementName.substring(index+1), _openElementName, _attributes);
_openElementName = null;
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
private void prepareNewDOM() throws SAXException
{
_dom = (SAXImpl)_dtmManager.getDTM(null, true, _wsfilter,
true, false, false,
_initSize, _buildIdIndex);
_dom.startDocument();
// Flush pending Text nodes to SAXImpl
for (int i = 0; i < _size; i++) {
String str = _textArray[i];
_dom.characters(str.toCharArray(), 0, str.length());
}
_size = 0;
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void startDocument() throws SAXException
{
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void endDocument() throws SAXException
{
if (_dom != null) {
_dom.endDocument();
}
else {
super.endDocument();
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void characters(String str) throws SAXException
{
if (_dom != null) {
characters(str.toCharArray(), 0, str.length());
}
else {
super.characters(str);
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void characters(char[] ch, int offset, int length)
throws SAXException
{
if (_dom != null) {
maybeEmitStartElement();
_dom.characters(ch, offset, length);
}
else {
super.characters(ch, offset, length);
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public boolean setEscaping(boolean escape) throws SAXException
{
if (_dom != null) {
return _dom.setEscaping(escape);
}
else {
return super.setEscaping(escape);
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void startElement(String elementName) throws SAXException
{
if (_dom == null) {
prepareNewDOM();
}
maybeEmitStartElement();
_openElementName = elementName;
_attributes.clear();
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void startElement(String uri, String localName, String qName)
throws SAXException
{
startElement(qName);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
startElement(qName);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void endElement(String elementName) throws SAXException
{
maybeEmitStartElement();
_dom.endElement(null, null, elementName);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
endElement(qName);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void addUniqueAttribute(String qName, String value, int flags)
throws SAXException
{
addAttribute(qName, value);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void namespaceAfterStartElement(String prefix, String uri)
throws SAXException
{
if (_dom == null) {
prepareNewDOM();
}
_dom.startPrefixMapping(prefix, uri);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void comment(String comment) throws SAXException
{
if (_dom == null) {
prepareNewDOM();
}
maybeEmitStartElement();
char[] chars = comment.toCharArray();
_dom.comment(chars, 0, chars.length);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void comment(char[] chars, int offset, int length)
throws SAXException
{
if (_dom == null) {
prepareNewDOM();
}
maybeEmitStartElement();
_dom.comment(chars, offset, length);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void processingInstruction(String target, String data)
throws SAXException
{
if (_dom == null) {
prepareNewDOM();
}
maybeEmitStartElement();
_dom.processingInstruction(target, data);
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void dispatchCharactersEvents(int nodeHandle, org.xml.sax.ContentHandler ch,
boolean normalize)
throws org.xml.sax.SAXException
{
if (_dom != null) {
_dom.dispatchCharactersEvents(nodeHandle, ch, normalize);
}
else {
super.dispatchCharactersEvents(nodeHandle, ch, normalize);
}
}
// in src/org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.java
public void dispatchToEvents(int nodeHandle, org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
if (_dom != null) {
_dom.dispatchToEvents(nodeHandle, ch);
}
else {
super.dispatchToEvents(nodeHandle, ch);
}
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void characters(char[] ch, int start, int length) throws SAXException
{
super.characters(ch, start, length);
_disableEscaping = !_escaping;
_textNodeToProcess = getNumberOfNodes();
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void startDocument() throws SAXException
{
super.startDocument();
_nsIndex.put(new Integer(0), new Integer(_uriCount++));
definePrefixAndUri(XML_PREFIX, XML_URI);
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void endDocument() throws SAXException
{
super.endDocument();
handleTextEscaping();
_namesSize = m_expandedNameTable.getSize();
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void startElement(String uri, String localName,
String qname, Attributes attributes,
Node node)
throws SAXException
{
this.startElement(uri, localName, qname, attributes);
if (m_buildIdIndex) {
_node2Ids.put(node, new Integer(m_parents.peek()));
}
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void startElement(String uri, String localName,
String qname, Attributes attributes)
throws SAXException
{
super.startElement(uri, localName, qname, attributes);
handleTextEscaping();
if (m_wsfilter != null) {
// Look for any xml:space attributes
// Depending on the implementation of attributes, this
// might be faster than looping through all attributes. ILENE
final int index = attributes.getIndex(XMLSPACE_STRING);
if (index >= 0) {
xmlSpaceDefine(attributes.getValue(index), m_parents.peek());
}
}
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void endElement(String namespaceURI, String localName, String qname)
throws SAXException
{
super.endElement(namespaceURI, localName, qname);
handleTextEscaping();
// Revert to strip/preserve-space setting from before this element
if (m_wsfilter != null) {
xmlSpaceRevert(m_previous);
}
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void processingInstruction(String target, String data)
throws SAXException
{
super.processingInstruction(target, data);
handleTextEscaping();
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
super.ignorableWhitespace(ch, start, length);
_textNodeToProcess = getNumberOfNodes();
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
super.startPrefixMapping(prefix, uri);
handleTextEscaping();
definePrefixAndUri(prefix, uri);
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
private void definePrefixAndUri(String prefix, String uri)
throws SAXException
{
// Check if the URI already exists before pushing on stack
Integer eType = new Integer(getIdForNamespace(uri));
if ((Integer)_nsIndex.get(eType) == null) {
_nsIndex.put(eType, new Integer(_uriCount++));
}
}
// in src/org/apache/xalan/xsltc/dom/SAXImpl.java
public void comment(char[] ch, int start, int length)
throws SAXException
{
super.comment(ch, start, length);
handleTextEscaping();
}
// in src/org/apache/xalan/xsltc/trax/DOM2TO.java
public void parse(InputSource unused) throws IOException, SAXException {
parse(_dom);
}
// in src/org/apache/xalan/xsltc/trax/DOM2TO.java
public void parse() throws IOException, SAXException {
if (_dom != null) {
boolean isIncomplete =
(_dom.getNodeType() != org.w3c.dom.Node.DOCUMENT_NODE);
if (isIncomplete) {
_handler.startDocument();
parse(_dom);
_handler.endDocument();
}
else {
parse(_dom);
}
}
}
// in src/org/apache/xalan/xsltc/trax/DOM2TO.java
private void parse(Node node)
throws IOException, SAXException
{
if (node == null) return;
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
case Node.DOCUMENT_TYPE_NODE :
case Node.ENTITY_NODE :
case Node.ENTITY_REFERENCE_NODE:
case Node.NOTATION_NODE :
// These node types are ignored!!!
break;
case Node.CDATA_SECTION_NODE:
_handler.startCDATA();
_handler.characters(node.getNodeValue());
_handler.endCDATA();
break;
case Node.COMMENT_NODE: // should be handled!!!
_handler.comment(node.getNodeValue());
break;
case Node.DOCUMENT_NODE:
_handler.startDocument();
Node next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
_handler.endDocument();
break;
case Node.DOCUMENT_FRAGMENT_NODE:
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
break;
case Node.ELEMENT_NODE:
// Generate SAX event to start element
final String qname = node.getNodeName();
_handler.startElement(null, null, qname);
int colon;
String prefix;
final NamedNodeMap map = node.getAttributes();
final int length = map.getLength();
// Process all namespace attributes first
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Is this a namespace declaration?
if (qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNodeValue();
colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(colon + 1)
: EMPTYSTRING;
_handler.namespaceAfterStartElement(prefix, uriAttr);
}
}
// Process all non-namespace attributes next
NamespaceMappings nm = new NamespaceMappings();
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Is this a regular attribute?
if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNamespaceURI();
// Uri may be implicitly declared
if (uriAttr != null && !uriAttr.equals(EMPTYSTRING) ) {
colon = qnameAttr.lastIndexOf(':');
// Fix for bug 26319
// For attributes not given an prefix explictly
// but having a namespace uri we need
// to explicitly generate the prefix
String newPrefix = nm.lookupPrefix(uriAttr);
if (newPrefix == null)
newPrefix = nm.generateNextPrefix();
prefix = (colon > 0) ? qnameAttr.substring(0, colon)
: newPrefix;
_handler.namespaceAfterStartElement(prefix, uriAttr);
_handler.addAttribute((prefix + ":" + qnameAttr),
attr.getNodeValue());
} else {
_handler.addAttribute(qnameAttr, attr.getNodeValue());
}
}
}
// Now element namespace and children
final String uri = node.getNamespaceURI();
final String localName = node.getLocalName();
// Uri may be implicitly declared
if (uri != null) {
colon = qname.lastIndexOf(':');
prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
_handler.namespaceAfterStartElement(prefix, uri);
}else {
// Fix for bug 26319
// If an element foo is created using
// createElementNS(null,locName)
// then the element should be serialized
// <foo xmlns=" "/>
if (uri == null && localName != null) {
prefix = EMPTYSTRING;
_handler.namespaceAfterStartElement(prefix, EMPTYSTRING);
}
}
// Traverse all child nodes of the element (if any)
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
// Generate SAX event to close element
_handler.endElement(qname);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
_handler.processingInstruction(node.getNodeName(),
node.getNodeValue());
break;
case Node.TEXT_NODE:
_handler.characters(node.getNodeValue());
break;
}
}
// in src/org/apache/xalan/xsltc/trax/DOM2TO.java
public void parse(String sysId) throws IOException, SAXException {
throw new IOException("This method is not yet implemented.");
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
private boolean startPrefixMapping(String prefix, String uri)
throws SAXException
{
boolean pushed = true;
Stack uriStack = (Stack) _nsPrefixes.get(prefix);
if (uriStack != null) {
if (uriStack.isEmpty()) {
_sax.startPrefixMapping(prefix, uri);
uriStack.push(uri);
}
else {
final String lastUri = (String) uriStack.peek();
if (!lastUri.equals(uri)) {
_sax.startPrefixMapping(prefix, uri);
uriStack.push(uri);
}
else {
pushed = false;
}
}
}
else {
_sax.startPrefixMapping(prefix, uri);
_nsPrefixes.put(prefix, uriStack = new Stack());
uriStack.push(uri);
}
return pushed;
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
private void endPrefixMapping(String prefix)
throws SAXException
{
final Stack uriStack = (Stack) _nsPrefixes.get(prefix);
if (uriStack != null) {
_sax.endPrefixMapping(prefix);
uriStack.pop();
}
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
public void parse(InputSource unused) throws IOException, SAXException {
parse(_dom);
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
public void parse() throws IOException, SAXException {
if (_dom != null) {
boolean isIncomplete =
(_dom.getNodeType() != org.w3c.dom.Node.DOCUMENT_NODE);
if (isIncomplete) {
_sax.startDocument();
parse(_dom);
_sax.endDocument();
}
else {
parse(_dom);
}
}
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
private void parse(Node node) throws IOException, SAXException {
Node first = null;
if (node == null) return;
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.DOCUMENT_TYPE_NODE :
case Node.ENTITY_NODE :
case Node.ENTITY_REFERENCE_NODE:
case Node.NOTATION_NODE :
// These node types are ignored!!!
break;
case Node.CDATA_SECTION_NODE:
final String cdata = node.getNodeValue();
if (_lex != null) {
_lex.startCDATA();
_sax.characters(cdata.toCharArray(), 0, cdata.length());
_lex.endCDATA();
}
else {
// in the case where there is no lex handler, we still
// want the text of the cdate to make its way through.
_sax.characters(cdata.toCharArray(), 0, cdata.length());
}
break;
case Node.COMMENT_NODE: // should be handled!!!
if (_lex != null) {
final String value = node.getNodeValue();
_lex.comment(value.toCharArray(), 0, value.length());
}
break;
case Node.DOCUMENT_NODE:
_sax.setDocumentLocator(this);
_sax.startDocument();
Node next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
_sax.endDocument();
break;
case Node.ELEMENT_NODE:
String prefix;
List pushedPrefixes = new ArrayList();
final AttributesImpl attrs = new AttributesImpl();
final NamedNodeMap map = node.getAttributes();
final int length = map.getLength();
// Process all namespace declarations
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore everything but NS declarations here
if (qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNodeValue();
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.add(prefix);
}
}
}
// Process all other attributes
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore NS declarations here
if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNamespaceURI();
final String localNameAttr = getLocalName(attr);
// Uri may be implicitly declared
if (uriAttr != null) {
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.add(prefix);
}
}
// Add attribute to list
attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr),
qnameAttr, "CDATA", attr.getNodeValue());
}
}
// Now process the element itself
final String qname = node.getNodeName();
final String uri = node.getNamespaceURI();
final String localName = getLocalName(node);
// Uri may be implicitly declared
if (uri != null) {
final int colon = qname.lastIndexOf(':');
prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uri)) {
pushedPrefixes.add(prefix);
}
}
// Generate SAX event to start element
if (_saxImpl != null) {
_saxImpl.startElement(uri, localName, qname, attrs, node);
}
else {
_sax.startElement(uri, localName, qname, attrs);
}
// Traverse all child nodes of the element (if any)
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
// Generate SAX event to close element
_sax.endElement(uri, localName, qname);
// Generate endPrefixMapping() for all pushed prefixes
final int nPushedPrefixes = pushedPrefixes.size();
for (int i = 0; i < nPushedPrefixes; i++) {
endPrefixMapping((String) pushedPrefixes.get(i));
}
break;
case Node.PROCESSING_INSTRUCTION_NODE:
_sax.processingInstruction(node.getNodeName(),
node.getNodeValue());
break;
case Node.TEXT_NODE:
final String data = node.getNodeValue();
_sax.characters(data.toCharArray(), 0, data.length());
break;
}
}
// in src/org/apache/xalan/xsltc/trax/DOM2SAX.java
public void parse(String sysId) throws IOException, SAXException {
throw new IOException("This method is not yet implemented.");
}
// in src/org/apache/xalan/xsltc/trax/TemplatesHandlerImpl.java
public void endDocument() throws SAXException {
_parser.endDocument();
// create the templates
try {
XSLTC xsltc = _parser.getXSLTC();
// Set the translet class name if not already set
String transletName;
if (_systemId != null) {
transletName = Util.baseName(_systemId);
}
else {
transletName = (String)_tfactory.getAttribute("translet-name");
}
xsltc.setClassName(transletName);
// Get java-legal class name from XSLTC module
transletName = xsltc.getClassName();
Stylesheet stylesheet = null;
SyntaxTreeNode root = _parser.getDocumentRoot();
// Compile the translet - this is where the work is done!
if (!_parser.errorsFound() && root != null) {
// Create a Stylesheet element from the root node
stylesheet = _parser.makeStylesheet(root);
stylesheet.setSystemId(_systemId);
stylesheet.setParentStylesheet(null);
if (xsltc.getTemplateInlining())
stylesheet.setTemplateInlining(true);
else
stylesheet.setTemplateInlining(false);
// Set a document loader (for xsl:include/import) if defined
if (_uriResolver != null) {
stylesheet.setSourceLoader(this);
}
_parser.setCurrentStylesheet(stylesheet);
// Set it as top-level in the XSLTC object
xsltc.setStylesheet(stylesheet);
// Create AST under the Stylesheet element
_parser.createAST(stylesheet);
}
// Generate the bytecodes and output the translet class(es)
if (!_parser.errorsFound() && stylesheet != null) {
stylesheet.setMultiDocument(xsltc.isMultiDocument());
stylesheet.setHasIdCall(xsltc.hasIdCall());
// Class synchronization is needed for BCEL
synchronized (xsltc.getClass()) {
stylesheet.translate();
}
}
if (!_parser.errorsFound()) {
// Check that the transformation went well before returning
final byte[][] bytecodes = xsltc.getBytecodes();
if (bytecodes != null) {
_templates =
new TemplatesImpl(xsltc.getBytecodes(), transletName,
_parser.getOutputProperties(), _indentNumber, _tfactory);
// Set URIResolver on templates object
if (_uriResolver != null) {
_templates.setURIResolver(_uriResolver);
}
}
}
else {
StringBuffer errorMessage = new StringBuffer();
Vector errors = _parser.getErrors();
final int count = errors.size();
for (int i = 0; i < count; i++) {
if (errorMessage.length() > 0)
errorMessage.append('\n');
errorMessage.append(errors.elementAt(i).toString());
}
throw new SAXException(ErrorMsg.JAXP_COMPILE_ERR, new TransformerException(errorMessage.toString()));
}
}
// in src/org/apache/xalan/xsltc/trax/TemplatesHandlerImpl.java
public void startElement(String uri, String localname, String qname,
Attributes attributes) throws SAXException
{
_parser.startElement(uri, localname, qname, attributes);
}
// in src/org/apache/xalan/xsltc/trax/XSLTCSource.java
protected DOM getDOM(XSLTCDTMManager dtmManager, AbstractTranslet translet)
throws SAXException
{
SAXImpl idom = (SAXImpl)_dom.get();
if (idom != null) {
if (dtmManager != null) {
idom.migrateTo(dtmManager);
}
}
else {
Source source = _source;
if (source == null) {
if (_systemId != null && _systemId.length() > 0) {
source = new StreamSource(_systemId);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.XSLTC_SOURCE_ERR);
throw new SAXException(err.toString());
}
}
DOMWSFilter wsfilter = null;
if (translet != null && translet instanceof StripFilter) {
wsfilter = new DOMWSFilter(translet);
}
boolean hasIdCall = (translet != null) ? translet.hasIdCall() : false;
if (dtmManager == null) {
dtmManager = XSLTCDTMManager.newInstance();
}
idom = (SAXImpl)dtmManager.getDTM(source, true, wsfilter, false, false, hasIdCall);
String systemId = getSystemId();
if (systemId != null) {
idom.setDocumentURI(systemId);
}
_dom.set(idom);
}
return idom;
}
// in src/org/apache/xalan/xsltc/trax/TrAXFilter.java
private void createParent() throws SAXException {
XMLReader parent = null;
try {
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true);
if (_transformer.isSecureProcessing()) {
try {
pfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (SAXException e) {}
}
SAXParser saxparser = pfactory.newSAXParser();
parent = saxparser.getXMLReader();
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
catch (FactoryConfigurationError e) {
throw new SAXException(e.toString());
}
if (parent == null) {
parent = XMLReaderFactory.createXMLReader();
}
// make this XMLReader the parent of this filter
setParent(parent);
}
// in src/org/apache/xalan/xsltc/trax/TrAXFilter.java
public void parse (InputSource input) throws SAXException, IOException
{
XMLReader managedReader = null;
try {
if (getParent() == null) {
try {
managedReader = XMLReaderManager.getInstance()
.getXMLReader();
setParent(managedReader);
} catch (SAXException e) {
throw new SAXException(e.toString());
}
}
// call parse on the parent
getParent().parse(input);
} finally {
if (managedReader != null) {
XMLReaderManager.getInstance().releaseXMLReader(managedReader);
}
}
}
// in src/org/apache/xalan/xsltc/trax/TrAXFilter.java
public void parse (String systemId) throws SAXException, IOException
{
parse(new InputSource(systemId));
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void characters(char[] ch, int start, int length)
throws SAXException
{
_handler.characters(ch, start, length);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startDocument() throws SAXException {
// Make sure setResult() was called before the first SAX event
if (_result == null) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_SET_RESULT_ERR);
throw new SAXException(err.toString());
}
if (!_isIdentity) {
boolean hasIdCall = (_translet != null) ? _translet.hasIdCall() : false;
XSLTCDTMManager dtmManager = null;
// Create an internal DOM (not W3C) and get SAX2 input handler
try {
dtmManager =
(XSLTCDTMManager)_transformer.getTransformerFactory()
.getDTMManagerClass()
.newInstance();
} catch (Exception e) {
throw new SAXException(e);
}
DTMWSFilter wsFilter;
if (_translet != null && _translet instanceof StripFilter) {
wsFilter = new DOMWSFilter(_translet);
} else {
wsFilter = null;
}
// Construct the DTM using the SAX events that come through
_dom = (SAXImpl)dtmManager.getDTM(null, false, wsFilter, true,
false, hasIdCall);
_handler = _dom.getBuilder();
_lexHandler = (LexicalHandler) _handler;
_dtdHandler = (DTDHandler) _handler;
_declHandler = (DeclHandler) _handler;
// Set document URI
_dom.setDocumentURI(_systemId);
if (_locator != null) {
_handler.setDocumentLocator(_locator);
}
}
// Proxy call
_handler.startDocument();
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endDocument() throws SAXException {
// Signal to the DOMBuilder that the document is complete
_handler.endDocument();
if (!_isIdentity) {
// Run the transformation now if we have a reference to a Result object
if (_result != null) {
try {
_transformer.setDOM(_dom);
_transformer.transform(null, _result);
}
catch (TransformerException e) {
throw new SAXException(e);
}
}
// Signal that the internal DOM is built (see 'setResult()').
_done = true;
// Set this DOM as the transformer's DOM
_transformer.setDOM(_dom);
}
if (_isIdentity && _result instanceof DOMResult) {
((DOMResult)_result).setNode(_transformer.getTransletOutputHandlerFactory().getNode());
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startElement(String uri, String localName,
String qname, Attributes attributes)
throws SAXException
{
_handler.startElement(uri, localName, qname, attributes);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endElement(String namespaceURI, String localName, String qname)
throws SAXException
{
_handler.endElement(namespaceURI, localName, qname);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void processingInstruction(String target, String data)
throws SAXException
{
_handler.processingInstruction(target, data);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startCDATA() throws SAXException {
if (_lexHandler != null) {
_lexHandler.startCDATA();
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endCDATA() throws SAXException {
if (_lexHandler != null) {
_lexHandler.endCDATA();
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void comment(char[] ch, int start, int length)
throws SAXException
{
if (_lexHandler != null) {
_lexHandler.comment(ch, start, length);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
_handler.ignorableWhitespace(ch, start, length);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void skippedEntity(String name) throws SAXException {
_handler.skippedEntity(name);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
_handler.startPrefixMapping(prefix, uri);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endPrefixMapping(String prefix) throws SAXException {
_handler.endPrefixMapping(prefix);
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
if (_lexHandler != null) {
_lexHandler.startDTD(name, publicId, systemId);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endDTD() throws SAXException {
if (_lexHandler != null) {
_lexHandler.endDTD();
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void startEntity(String name) throws SAXException {
if (_lexHandler != null) {
_lexHandler.startEntity(name);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void endEntity(String name) throws SAXException {
if (_lexHandler != null) {
_lexHandler.endEntity(name);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notationName) throws SAXException
{
if (_dtdHandler != null) {
_dtdHandler.unparsedEntityDecl(name, publicId, systemId,
notationName);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void notationDecl(String name, String publicId, String systemId)
throws SAXException
{
if (_dtdHandler != null) {
_dtdHandler.notationDecl(name, publicId, systemId);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void attributeDecl(String eName, String aName, String type,
String valueDefault, String value) throws SAXException
{
if (_declHandler != null) {
_declHandler.attributeDecl(eName, aName, type, valueDefault, value);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void elementDecl(String name, String model)
throws SAXException
{
if (_declHandler != null) {
_declHandler.elementDecl(name, model);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void externalEntityDecl(String name, String publicId, String systemId)
throws SAXException
{
if (_declHandler != null) {
_declHandler.externalEntityDecl(name, publicId, systemId);
}
}
// in src/org/apache/xalan/xsltc/trax/TransformerHandlerImpl.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
if (_declHandler != null) {
_declHandler.internalEntityDecl(name, value);
}
}
// in src/org/apache/xalan/xsltc/trax/SAX2DOM.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException { }
// in src/org/apache/xalan/processor/ProcessorOutputElem.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
// Hmmm... for the moment I don't think I'll have default properties set for this. -sb
m_outputProperties = new OutputProperties();
m_outputProperties.setDOMBackPointer(handler.getOriginatingNode());
m_outputProperties.setLocaterInfo(handler.getLocator());
m_outputProperties.setUid(handler.nextUid());
setPropertiesFromAttributes(handler, rawName, attributes, this);
// Access this only from the Hashtable level... we don't want to
// get default properties.
String entitiesFileName =
(String) m_outputProperties.getProperties().get(OutputPropertiesFactory.S_KEY_ENTITIES);
if (null != entitiesFileName)
{
try
{
String absURL = SystemIDResolver.getAbsoluteURI(entitiesFileName,
handler.getBaseIdentifier());
m_outputProperties.getProperties().put(OutputPropertiesFactory.S_KEY_ENTITIES, absURL);
}
catch(TransformerException te)
{
handler.error(te.getMessage(), te);
}
}
handler.getStylesheet().setOutput(m_outputProperties);
ElemTemplateElement parent = handler.getElemTemplateElement();
parent.appendChild(m_outputProperties);
m_outputProperties = null;
}
// in src/org/apache/xalan/processor/ProcessorCharacters.java
public void startNonText(StylesheetHandler handler) throws org.xml.sax.SAXException
{
if (this == handler.getCurrentProcessor())
{
handler.popProcessor();
}
int nChars = m_accumulator.length();
if ((nChars > 0)
&& ((null != m_xslTextElement)
||!XMLCharacterRecognizer.isWhiteSpace(m_accumulator))
|| handler.isSpacePreserve())
{
ElemTextLiteral elem = new ElemTextLiteral();
elem.setDOMBackPointer(m_firstBackPointer);
elem.setLocaterInfo(handler.getLocator());
try
{
elem.setPrefixes(handler.getNamespaceSupport());
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
boolean doe = (null != m_xslTextElement)
? m_xslTextElement.getDisableOutputEscaping() : false;
elem.setDisableOutputEscaping(doe);
elem.setPreserveSpace(true);
char[] chars = new char[nChars];
m_accumulator.getChars(0, nChars, chars, 0);
elem.setChars(chars);
ElemTemplateElement parent = handler.getElemTemplateElement();
parent.appendChild(elem);
}
m_accumulator.setLength(0);
m_firstBackPointer = null;
}
// in src/org/apache/xalan/processor/ProcessorCharacters.java
public void characters(
StylesheetHandler handler, char ch[], int start, int length)
throws org.xml.sax.SAXException
{
m_accumulator.append(ch, start, length);
if(null == m_firstBackPointer)
m_firstBackPointer = handler.getOriginatingNode();
// Catch all events until a non-character event.
if (this != handler.getCurrentProcessor())
handler.pushProcessor(this);
}
// in src/org/apache/xalan/processor/ProcessorCharacters.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
// Since this has been installed as the current processor, we
// may get and end element event, in which case, we pop and clear
// and then call the real element processor.
startNonText(handler);
handler.getCurrentProcessor().endElement(handler, uri, localName,
rawName);
handler.popProcessor();
}
// in src/org/apache/xalan/processor/ProcessorExsltFuncResult.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws SAXException
{
String msg = "";
super.startElement(handler, uri, localName, rawName, attributes);
ElemTemplateElement ancestor = handler.getElemTemplateElement().getParentElem();
while (ancestor != null && !(ancestor instanceof ElemExsltFunction))
{
if (ancestor instanceof ElemVariable
|| ancestor instanceof ElemParam
|| ancestor instanceof ElemExsltFuncResult)
{
msg = "func:result cannot appear within a variable, parameter, or another func:result.";
handler.error(msg, new SAXException(msg));
}
ancestor = ancestor.getParentElem();
}
if (ancestor == null)
{
msg = "func:result must appear in a func:function element";
handler.error(msg, new SAXException(msg));
}
}
// in src/org/apache/xalan/processor/ProcessorTemplateElem.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
super.startElement(handler, uri, localName, rawName, attributes);
try
{
// ElemTemplateElement parent = handler.getElemTemplateElement();
XSLTElementDef def = getElemDef();
Class classObject = def.getClassObject();
ElemTemplateElement elem = null;
try
{
elem = (ElemTemplateElement) classObject.newInstance();
elem.setDOMBackPointer(handler.getOriginatingNode());
elem.setLocaterInfo(handler.getLocator());
elem.setPrefixes(handler.getNamespaceSupport());
}
catch (InstantiationException ie)
{
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMTMPL, null, ie);//"Failed creating ElemTemplateElement instance!", ie);
}
catch (IllegalAccessException iae)
{
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMTMPL, null, iae);//"Failed creating ElemTemplateElement instance!", iae);
}
setPropertiesFromAttributes(handler, rawName, attributes, elem);
appendAndPush(handler, elem);
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/ProcessorTemplateElem.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
ElemTemplateElement parent = handler.getElemTemplateElement();
if(null != parent) // defensive, for better multiple error reporting. -sb
{
parent.appendChild(elem);
handler.pushElemTemplateElement(elem);
}
}
// in src/org/apache/xalan/processor/ProcessorTemplateElem.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
super.endElement(handler, uri, localName, rawName);
handler.popElemTemplateElement().setEndLocaterInfo(handler.getLocator());
}
// in src/org/apache/xalan/processor/ProcessorPreserveSpace.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName,
Attributes attributes)
throws org.xml.sax.SAXException
{
Stylesheet thisSheet = handler.getStylesheet();
WhitespaceInfoPaths paths = new WhitespaceInfoPaths(thisSheet);
setPropertiesFromAttributes(handler, rawName, attributes, paths);
Vector xpaths = paths.getElements();
for (int i = 0; i < xpaths.size(); i++)
{
WhiteSpaceInfo wsi = new WhiteSpaceInfo((XPath) xpaths.elementAt(i), false, thisSheet);
wsi.setUid(handler.nextUid());
thisSheet.setPreserveSpaces(wsi);
}
paths.clearElements();
}
// in src/org/apache/xalan/processor/ProcessorDecimalFormat.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
DecimalFormatProperties dfp = new DecimalFormatProperties(handler.nextUid());
dfp.setDOMBackPointer(handler.getOriginatingNode());
dfp.setLocaterInfo(handler.getLocator());
setPropertiesFromAttributes(handler, rawName, attributes, dfp);
handler.getStylesheet().setDecimalFormat(dfp);
handler.getStylesheet().appendChild(dfp);
}
// in src/org/apache/xalan/processor/ProcessorNamespaceAlias.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
final String resultNS;
NamespaceAlias na = new NamespaceAlias(handler.nextUid());
setPropertiesFromAttributes(handler, rawName, attributes, na);
String prefix = na.getStylesheetPrefix();
if(prefix.equals("#default"))
{
prefix = "";
na.setStylesheetPrefix(prefix);
}
String stylesheetNS = handler.getNamespaceForPrefix(prefix);
na.setStylesheetNamespace(stylesheetNS);
prefix = na.getResultPrefix();
if(prefix.equals("#default"))
{
prefix = "";
na.setResultPrefix(prefix);
resultNS = handler.getNamespaceForPrefix(prefix);
if(null == resultNS)
handler.error(XSLTErrorResources.ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT, null, null);
}
else
{
resultNS = handler.getNamespaceForPrefix(prefix);
if(null == resultNS)
handler.error(XSLTErrorResources.ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX, new Object[] {prefix}, null);
}
na.setResultNamespace(resultNS);
handler.getStylesheet().setNamespaceAlias(na);
handler.getStylesheet().appendChild(na);
}
// in src/org/apache/xalan/processor/ProcessorLRE.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
try
{
ElemTemplateElement p = handler.getElemTemplateElement();
boolean excludeXSLDecl = false;
boolean isLREAsStyleSheet = false;
if (null == p)
{
// Literal Result Template as stylesheet.
XSLTElementProcessor lreProcessor = handler.popProcessor();
XSLTElementProcessor stylesheetProcessor =
handler.getProcessorFor(Constants.S_XSLNAMESPACEURL, "stylesheet",
"xsl:stylesheet");
handler.pushProcessor(lreProcessor);
Stylesheet stylesheet;
try
{
stylesheet = getStylesheetRoot(handler);
}
catch(TransformerConfigurationException tfe)
{
throw new TransformerException(tfe);
}
// stylesheet.setDOMBackPointer(handler.getOriginatingNode());
// ***** Note that we're assigning an empty locator. Is this necessary?
SAXSourceLocator slocator = new SAXSourceLocator();
Locator locator = handler.getLocator();
if(null != locator)
{
slocator.setLineNumber(locator.getLineNumber());
slocator.setColumnNumber(locator.getColumnNumber());
slocator.setPublicId(locator.getPublicId());
slocator.setSystemId(locator.getSystemId());
}
stylesheet.setLocaterInfo(slocator);
stylesheet.setPrefixes(handler.getNamespaceSupport());
handler.pushStylesheet(stylesheet);
isLREAsStyleSheet = true;
AttributesImpl stylesheetAttrs = new AttributesImpl();
AttributesImpl lreAttrs = new AttributesImpl();
int n = attributes.getLength();
for (int i = 0; i < n; i++)
{
String attrLocalName = attributes.getLocalName(i);
String attrUri = attributes.getURI(i);
String value = attributes.getValue(i);
if ((null != attrUri) && attrUri.equals(Constants.S_XSLNAMESPACEURL))
{
stylesheetAttrs.addAttribute(null, attrLocalName, attrLocalName,
attributes.getType(i),
attributes.getValue(i));
}
else if ((attrLocalName.startsWith("xmlns:") || attrLocalName.equals(
"xmlns")) && value.equals(Constants.S_XSLNAMESPACEURL))
{
// ignore
}
else
{
lreAttrs.addAttribute(attrUri, attrLocalName,
attributes.getQName(i),
attributes.getType(i),
attributes.getValue(i));
}
}
attributes = lreAttrs;
// Set properties from the attributes, but don't throw
// an error if there is an attribute defined that is not
// allowed on a stylesheet.
try{
stylesheetProcessor.setPropertiesFromAttributes(handler, "stylesheet",
stylesheetAttrs, stylesheet);
}
catch (Exception e)
{
// This is pretty ugly, but it will have to do for now.
// This is just trying to append some text specifying that
// this error came from a missing or invalid XSLT namespace
// declaration.
// If someone comes up with a better solution, please feel
// free to contribute it. -mm
if (stylesheet.getDeclaredPrefixes() == null ||
!declaredXSLNS(stylesheet))
{
throw new org.xml.sax.SAXException(XSLMessages.createWarning(XSLTErrorResources.WG_OLD_XSLT_NS, null));
}
else
{
throw new org.xml.sax.SAXException(e);
}
}
handler.pushElemTemplateElement(stylesheet);
ElemTemplate template = new ElemTemplate();
if (slocator != null)
template.setLocaterInfo(slocator);
appendAndPush(handler, template);
XPath rootMatch = new XPath("/", stylesheet, stylesheet, XPath.MATCH,
handler.getStylesheetProcessor().getErrorListener());
template.setMatch(rootMatch);
// template.setDOMBackPointer(handler.getOriginatingNode());
stylesheet.setTemplate(template);
p = handler.getElemTemplateElement();
excludeXSLDecl = true;
}
XSLTElementDef def = getElemDef();
Class classObject = def.getClassObject();
boolean isExtension = false;
boolean isComponentDecl = false;
boolean isUnknownTopLevel = false;
while (null != p)
{
// System.out.println("Checking: "+p);
if (p instanceof ElemLiteralResult)
{
ElemLiteralResult parentElem = (ElemLiteralResult) p;
isExtension = parentElem.containsExtensionElementURI(uri);
}
else if (p instanceof Stylesheet)
{
Stylesheet parentElem = (Stylesheet) p;
isExtension = parentElem.containsExtensionElementURI(uri);
if ((false == isExtension) && (null != uri)
&& (uri.equals(Constants.S_BUILTIN_EXTENSIONS_URL)
|| uri.equals(Constants.S_BUILTIN_OLD_EXTENSIONS_URL)))
{
isComponentDecl = true;
}
else
{
isUnknownTopLevel = true;
}
}
if (isExtension)
break;
p = p.getParentElem();
}
ElemTemplateElement elem = null;
try
{
if (isExtension)
{
// System.out.println("Creating extension(1): "+uri);
elem = new ElemExtensionCall();
}
else if (isComponentDecl)
{
elem = (ElemTemplateElement) classObject.newInstance();
}
else if (isUnknownTopLevel)
{
// TBD: Investigate, not sure about this. -sb
elem = (ElemTemplateElement) classObject.newInstance();
}
else
{
elem = (ElemTemplateElement) classObject.newInstance();
}
elem.setDOMBackPointer(handler.getOriginatingNode());
elem.setLocaterInfo(handler.getLocator());
elem.setPrefixes(handler.getNamespaceSupport(), excludeXSLDecl);
if (elem instanceof ElemLiteralResult)
{
((ElemLiteralResult) elem).setNamespace(uri);
((ElemLiteralResult) elem).setLocalName(localName);
((ElemLiteralResult) elem).setRawName(rawName);
((ElemLiteralResult) elem).setIsLiteralResultAsStylesheet(
isLREAsStyleSheet);
}
}
catch (InstantiationException ie)
{
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, ie);//"Failed creating ElemLiteralResult instance!", ie);
}
catch (IllegalAccessException iae)
{
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, iae);//"Failed creating ElemLiteralResult instance!", iae);
}
setPropertiesFromAttributes(handler, rawName, attributes, elem);
// bit of a hack here...
if (!isExtension && (elem instanceof ElemLiteralResult))
{
isExtension =
((ElemLiteralResult) elem).containsExtensionElementURI(uri);
if (isExtension)
{
// System.out.println("Creating extension(2): "+uri);
elem = new ElemExtensionCall();
elem.setLocaterInfo(handler.getLocator());
elem.setPrefixes(handler.getNamespaceSupport());
((ElemLiteralResult) elem).setNamespace(uri);
((ElemLiteralResult) elem).setLocalName(localName);
((ElemLiteralResult) elem).setRawName(rawName);
setPropertiesFromAttributes(handler, rawName, attributes, elem);
}
}
appendAndPush(handler, elem);
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/ProcessorLRE.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
ElemTemplateElement elem = handler.getElemTemplateElement();
if (elem instanceof ElemLiteralResult)
{
if (((ElemLiteralResult) elem).getIsLiteralResultAsStylesheet())
{
handler.popStylesheet();
}
}
super.endElement(handler, uri, localName, rawName);
}
// in src/org/apache/xalan/processor/ProcessorTemplate.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
super.appendAndPush(handler, elem);
elem.setDOMBackPointer(handler.getOriginatingNode());
handler.getStylesheet().setTemplate((ElemTemplate) elem);
}
// in src/org/apache/xalan/processor/ProcessorStripSpace.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
Stylesheet thisSheet = handler.getStylesheet();
WhitespaceInfoPaths paths = new WhitespaceInfoPaths(thisSheet);
setPropertiesFromAttributes(handler, rawName, attributes, paths);
Vector xpaths = paths.getElements();
for (int i = 0; i < xpaths.size(); i++)
{
WhiteSpaceInfo wsi = new WhiteSpaceInfo((XPath) xpaths.elementAt(i), true, thisSheet);
wsi.setUid(handler.nextUid());
thisSheet.setStripSpaces(wsi);
}
paths.clearElements();
}
// in src/org/apache/xalan/processor/ProcessorText.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
// Don't push this element onto the element stack.
ProcessorCharacters charProcessor =
(ProcessorCharacters) handler.getProcessorFor(null, "text()", "text");
charProcessor.setXslTextElement((ElemText) elem);
ElemTemplateElement parent = handler.getElemTemplateElement();
parent.appendChild(elem);
elem.setDOMBackPointer(handler.getOriginatingNode());
}
// in src/org/apache/xalan/processor/ProcessorText.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
ProcessorCharacters charProcessor
= (ProcessorCharacters) handler.getProcessorFor(null, "text()", "text");
charProcessor.setXslTextElement(null);
}
// in src/org/apache/xalan/processor/ProcessorAttributeSet.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
ElemAttributeSet eat = new ElemAttributeSet();
eat.setLocaterInfo(handler.getLocator());
try
{
eat.setPrefixes(handler.getNamespaceSupport());
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
eat.setDOMBackPointer(handler.getOriginatingNode());
setPropertiesFromAttributes(handler, rawName, attributes, eat);
handler.getStylesheet().setAttributeSet(eat);
// handler.pushElemTemplateElement(eat);
ElemTemplateElement parent = handler.getElemTemplateElement();
parent.appendChild(eat);
handler.pushElemTemplateElement(eat);
}
// in src/org/apache/xalan/processor/ProcessorAttributeSet.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
handler.popElemTemplateElement();
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
AVT processAVT(
StylesheetHandler handler, String uri, String name, String rawName, String value,
ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processCDATA(StylesheetHandler handler, String uri, String name,
String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT()) {
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} else {
return value;
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processCHAR(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT()) {
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
// If an AVT wasn't used, validate the value
if ((avt.isSimple()) && (value.length() != 1)) {
handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null);
return null;
}
return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} else {
if (value.length() != 1)
{
handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null);
return null;
}
return new Character(value.charAt(0));
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processENUM(StylesheetHandler handler, String uri, String name,
String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
AVT avt = null;
if (getSupportsAVT()) {
try
{
avt = new AVT(handler, uri, name, rawName, value, owner);
// If this attribute used an avt, then we can't validate at this time.
if (!avt.isSimple()) return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
int retVal = this.getEnum(value);
if (retVal == StringToIntTable.INVALID_KEY)
{
StringBuffer enumNamesList = getListOfEnums();
handleError(handler, XSLTErrorResources.INVALID_ENUM,new Object[]{name, value, enumNamesList.toString() },null);
return null;
}
if (getSupportsAVT()) return avt;
else return new Integer(retVal);
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processENUM_OR_PQNAME(StylesheetHandler handler, String uri, String name,
String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
Object objToReturn = null;
if (getSupportsAVT()) {
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
if (!avt.isSimple()) return avt;
else objToReturn = avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// An avt wasn't used.
int key = this.getEnum(value);
if (key != StringToIntTable.INVALID_KEY)
{
if (objToReturn == null) objToReturn = new Integer(key);
}
// enum not used. Validate qname-but-not-ncname.
else
{
try
{
QName qname = new QName(value, handler, true);
if (objToReturn == null) objToReturn = qname;
if (qname.getPrefix() == null) {
StringBuffer enumNamesList = getListOfEnums();
enumNamesList.append(" <qname-but-not-ncname>");
handleError(handler,XSLTErrorResources.INVALID_ENUM,new Object[]{name, value, enumNamesList.toString() },null);
return null;
}
}
catch (IllegalArgumentException ie)
{
StringBuffer enumNamesList = getListOfEnums();
enumNamesList.append(" <qname-but-not-ncname>");
handleError(handler,XSLTErrorResources.INVALID_ENUM,new Object[]{name, value, enumNamesList.toString() },ie);
return null;
}
catch (RuntimeException re)
{
StringBuffer enumNamesList = getListOfEnums();
enumNamesList.append(" <qname-but-not-ncname>");
handleError(handler,XSLTErrorResources.INVALID_ENUM,new Object[]{name, value, enumNamesList.toString() },re);
return null;
}
}
return objToReturn;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processEXPR(
StylesheetHandler handler, String uri, String name, String rawName, String value,
ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
XPath expr = handler.createXPath(value, owner);
return expr;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processNMTOKEN(StylesheetHandler handler, String uri, String name,
String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT()) {
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
// If an AVT wasn't used, validate the value
if ((avt.isSimple()) && (!XML11Char.isXML11ValidNmtoken(value))) {
handleError(handler,XSLTErrorResources.INVALID_NMTOKEN, new Object[] {name,value},null);
return null;
}
return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} else {
if (!XML11Char.isXML11ValidNmtoken(value)) {
handleError(handler,XSLTErrorResources.INVALID_NMTOKEN, new Object[] {name,value},null);
return null;
}
}
return value;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processPATTERN(
StylesheetHandler handler, String uri, String name, String rawName, String value,
ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
XPath pattern = handler.createMatchPatternXPath(value, owner);
return pattern;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processNUMBER(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT())
{
Double val;
AVT avt = null;
try
{
avt = new AVT(handler, uri, name, rawName, value, owner);
// If this attribute used an avt, then we can't validate at this time.
if (avt.isSimple())
{
val = Double.valueOf(value);
}
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
catch (NumberFormatException nfe)
{
handleError(handler,XSLTErrorResources.INVALID_NUMBER, new Object[] {name, value}, nfe);
return null;
}
return avt;
}
else
{
try
{
return Double.valueOf(value);
}
catch (NumberFormatException nfe)
{
handleError(handler,XSLTErrorResources.INVALID_NUMBER, new Object[] {name, value}, nfe);
return null;
}
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processQNAME(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
QName qname = new QName(value, handler, true);
return qname;
}
catch (IllegalArgumentException ie)
{
// thrown by QName constructor
handleError(handler,XSLTErrorResources.INVALID_QNAME, new Object[] {name, value},ie);
return null;
}
catch (RuntimeException re) {
// thrown by QName constructor
handleError(handler,XSLTErrorResources.INVALID_QNAME, new Object[] {name, value},re);
return null;
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processAVT_QNAME(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
AVT avt = null;
try
{
avt = new AVT(handler, uri, name, rawName, value, owner);
// If an AVT wasn't used, validate the value
if (avt.isSimple())
{
int indexOfNSSep = value.indexOf(':');
if (indexOfNSSep >= 0)
{
String prefix = value.substring(0, indexOfNSSep);
if (!XML11Char.isXML11ValidNCName(prefix))
{
handleError(handler,XSLTErrorResources.INVALID_QNAME,new Object[]{name,value },null);
return null;
}
}
String localName = (indexOfNSSep < 0)
? value : value.substring(indexOfNSSep + 1);
if ((localName == null) || (localName.length() == 0) ||
(!XML11Char.isXML11ValidNCName(localName)))
{
handleError(handler,XSLTErrorResources.INVALID_QNAME,new Object[]{name,value },null );
return null;
}
}
}
catch (TransformerException te)
{
// thrown by AVT constructor
throw new org.xml.sax.SAXException(te);
}
return avt;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processNCNAME(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT())
{
AVT avt = null;
try
{
avt = new AVT(handler, uri, name, rawName, value, owner);
// If an AVT wasn't used, validate the value
if ((avt.isSimple()) && (!XML11Char.isXML11ValidNCName(value)))
{
handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null);
return null;
}
return avt;
}
catch (TransformerException te)
{
// thrown by AVT constructor
throw new org.xml.sax.SAXException(te);
}
} else {
if (!XML11Char.isXML11ValidNCName(value))
{
handleError(handler,XSLTErrorResources.INVALID_NCNAME,new Object[] {name,value},null);
return null;
}
return value;
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Vector processQNAMES(
StylesheetHandler handler, String uri, String name, String rawName, String value)
throws org.xml.sax.SAXException
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nQNames = tokenizer.countTokens();
Vector qnames = new Vector(nQNames);
for (int i = 0; i < nQNames; i++)
{
// Fix from Alexander Rudnev
qnames.addElement(new QName(tokenizer.nextToken(), handler));
}
return qnames;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
final Vector processQNAMESRNU(StylesheetHandler handler, String uri,
String name, String rawName, String value)
throws org.xml.sax.SAXException
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nQNames = tokenizer.countTokens();
Vector qnames = new Vector(nQNames);
String defaultURI = handler.getNamespaceForPrefix("");
for (int i = 0; i < nQNames; i++)
{
String tok = tokenizer.nextToken();
if (tok.indexOf(':') == -1) {
qnames.addElement(new QName(defaultURI,tok));
} else {
qnames.addElement(new QName(tok, handler));
}
}
return qnames;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Vector processSIMPLEPATTERNLIST(
StylesheetHandler handler, String uri, String name, String rawName, String value,
ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nPatterns = tokenizer.countTokens();
Vector patterns = new Vector(nPatterns);
for (int i = 0; i < nPatterns; i++)
{
XPath pattern =
handler.createMatchPatternXPath(tokenizer.nextToken(), owner);
patterns.addElement(pattern);
}
return patterns;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
StringVector processPREFIX_URLLIST(
StylesheetHandler handler, String uri, String name, String rawName, String value)
throws org.xml.sax.SAXException
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nStrings = tokenizer.countTokens();
StringVector strings = new StringVector(nStrings);
for (int i = 0; i < nStrings; i++)
{
String prefix = tokenizer.nextToken();
String url = handler.getNamespaceForPrefix(prefix);
if (url != null)
strings.addElement(url);
else
throw new org.xml.sax.SAXException(XSLMessages.createMessage(XSLTErrorResources.ER_CANT_RESOLVE_NSPREFIX, new Object[] {prefix}));
}
return strings;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
StringVector processPREFIX_LIST(
StylesheetHandler handler, String uri, String name,
String rawName, String value) throws org.xml.sax.SAXException
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nStrings = tokenizer.countTokens();
StringVector strings = new StringVector(nStrings);
for (int i = 0; i < nStrings; i++)
{
String prefix = tokenizer.nextToken();
String url = handler.getNamespaceForPrefix(prefix);
if (prefix.equals(Constants.ATTRVAL_DEFAULT_PREFIX) || url != null)
strings.addElement(prefix);
else
throw new org.xml.sax.SAXException(
XSLMessages.createMessage(
XSLTErrorResources.ER_CANT_RESOLVE_NSPREFIX,
new Object[] {prefix}));
}
return strings;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processURL(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
if (getSupportsAVT()) {
try
{
AVT avt = new AVT(handler, uri, name, rawName, value, owner);
// If an AVT wasn't used, validate the value
// if (avt.getSimpleString() != null) {
// TODO: syntax check URL value.
// return SystemIDResolver.getAbsoluteURI(value,
// handler.getBaseIdentifier());
//}
return avt;
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} else {
// TODO: syntax check URL value.
// return SystemIDResolver.getAbsoluteURI(value,
// handler.getBaseIdentifier());
return value;
}
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
private Boolean processYESNO(
StylesheetHandler handler, String uri, String name, String rawName, String value)
throws org.xml.sax.SAXException
{
// Is this already checked somewhere else? -sb
if (!(value.equals("yes") || value.equals("no")))
{
handleError(handler, XSLTErrorResources.INVALID_BOOLEAN, new Object[] {name,value}, null);
return null;
}
return new Boolean(value.equals("yes") ? true : false);
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
Object processValue(
StylesheetHandler handler, String uri, String name, String rawName, String value,
ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
int type = getType();
Object processedValue = null;
switch (type)
{
case T_AVT :
processedValue = processAVT(handler, uri, name, rawName, value, owner);
break;
case T_CDATA :
processedValue = processCDATA(handler, uri, name, rawName, value, owner);
break;
case T_CHAR :
processedValue = processCHAR(handler, uri, name, rawName, value, owner);
break;
case T_ENUM :
processedValue = processENUM(handler, uri, name, rawName, value, owner);
break;
case T_EXPR :
processedValue = processEXPR(handler, uri, name, rawName, value, owner);
break;
case T_NMTOKEN :
processedValue = processNMTOKEN(handler, uri, name, rawName, value, owner);
break;
case T_PATTERN :
processedValue = processPATTERN(handler, uri, name, rawName, value, owner);
break;
case T_NUMBER :
processedValue = processNUMBER(handler, uri, name, rawName, value, owner);
break;
case T_QNAME :
processedValue = processQNAME(handler, uri, name, rawName, value, owner);
break;
case T_QNAMES :
processedValue = processQNAMES(handler, uri, name, rawName, value);
break;
case T_QNAMES_RESOLVE_NULL:
processedValue = processQNAMESRNU(handler, uri, name, rawName, value);
break;
case T_SIMPLEPATTERNLIST :
processedValue = processSIMPLEPATTERNLIST(handler, uri, name, rawName,
value, owner);
break;
case T_URL :
processedValue = processURL(handler, uri, name, rawName, value, owner);
break;
case T_YESNO :
processedValue = processYESNO(handler, uri, name, rawName, value);
break;
case T_STRINGLIST :
processedValue = processSTRINGLIST(handler, uri, name, rawName, value);
break;
case T_PREFIX_URLLIST :
processedValue = processPREFIX_URLLIST(handler, uri, name, rawName,
value);
break;
case T_ENUM_OR_PQNAME :
processedValue = processENUM_OR_PQNAME(handler, uri, name, rawName, value, owner);
break;
case T_NCNAME :
processedValue = processNCNAME(handler, uri, name, rawName, value, owner);
break;
case T_AVT_QNAME :
processedValue = processAVT_QNAME(handler, uri, name, rawName, value, owner);
break;
case T_PREFIXLIST :
processedValue = processPREFIX_LIST(handler, uri, name, rawName,
value);
break;
default :
}
return processedValue;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
void setDefAttrValue(StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
setAttrValue(handler, this.getNamespace(), this.getName(),
this.getName(), this.getDefault(), elem);
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
boolean setAttrValue(
StylesheetHandler handler, String attrUri, String attrLocalName,
String attrRawName, String attrValue, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
if(attrRawName.equals("xmlns") || attrRawName.startsWith("xmlns:"))
return true;
String setterString = getSetterMethodName();
// If this is null, then it is a foreign namespace and we
// do not process it.
if (null != setterString)
{
try
{
Method meth;
Object[] args;
if(setterString.equals(S_FOREIGNATTR_SETTER))
{
// workaround for possible crimson bug
if( attrUri==null) attrUri="";
// First try to match with the primative value.
Class sclass = attrUri.getClass();
Class[] argTypes = new Class[]{ sclass, sclass,
sclass, sclass };
meth = elem.getClass().getMethod(setterString, argTypes);
args = new Object[]{ attrUri, attrLocalName,
attrRawName, attrValue };
}
else
{
Object value = processValue(handler, attrUri, attrLocalName,
attrRawName, attrValue, elem);
// If a warning was issued because the value for this attribute was
// invalid, then the value will be null. Just return
if (null == value) return false;
// First try to match with the primative value.
Class[] argTypes = new Class[]{ getPrimativeClass(value) };
try
{
meth = elem.getClass().getMethod(setterString, argTypes);
}
catch (NoSuchMethodException nsme)
{
Class cl = ((Object) value).getClass();
// If this doesn't work, try it with the non-primative value;
argTypes[0] = cl;
meth = elem.getClass().getMethod(setterString, argTypes);
}
args = new Object[]{ value };
}
meth.invoke(elem, args);
}
catch (NoSuchMethodException nsme)
{
if (!setterString.equals(S_FOREIGNATTR_SETTER))
{
handler.error(XSLTErrorResources.ER_FAILED_CALLING_METHOD, new Object[]{setterString}, nsme);//"Failed calling " + setterString + " method!", nsme);
return false;
}
}
catch (IllegalAccessException iae)
{
handler.error(XSLTErrorResources.ER_FAILED_CALLING_METHOD, new Object[]{setterString}, iae);//"Failed calling " + setterString + " method!", iae);
return false;
}
catch (InvocationTargetException nsme)
{
handleError(handler, XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_VALUE,
new Object[]{ Constants.ATTRNAME_NAME, getName()}, nsme);
return false;
}
}
return true;
}
// in src/org/apache/xalan/processor/XSLTAttributeDef.java
private void handleError(StylesheetHandler handler, String msg, Object [] args, Exception exc) throws org.xml.sax.SAXException
{
switch (getErrorType())
{
case (FATAL):
case (ERROR):
handler.error(msg, args, exc);
break;
case (WARNING):
handler.warn(msg, args);
default: break;
}
}
// in src/org/apache/xalan/processor/ProcessorInclude.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
setPropertiesFromAttributes(handler, rawName, attributes, this);
try
{
// Get the Source from the user's URIResolver (if any).
Source sourceFromURIResolver = getSourceFromUriResolver(handler);
// Get the system ID of the included/imported stylesheet module
String hrefUrl = getBaseURIOfIncludedStylesheet(handler, sourceFromURIResolver);
if (handler.importStackContains(hrefUrl))
{
throw new org.xml.sax.SAXException(
XSLMessages.createMessage(
getStylesheetInclErr(), new Object[]{ hrefUrl })); //"(StylesheetHandler) "+hrefUrl+" is directly or indirectly importing itself!");
}
// Push the system ID and corresponding Source
// on some stacks for later retrieval during parse() time.
handler.pushImportURL(hrefUrl);
handler.pushImportSource(sourceFromURIResolver);
int savedStylesheetType = handler.getStylesheetType();
handler.setStylesheetType(this.getStylesheetType());
handler.pushNewNamespaceSupport();
try
{
parse(handler, uri, localName, rawName, attributes);
}
finally
{
handler.setStylesheetType(savedStylesheetType);
handler.popImportURL();
handler.popImportSource();
handler.popNamespaceSupport();
}
}
catch(TransformerException te)
{
handler.error(te.getMessage(), te);
}
}
// in src/org/apache/xalan/processor/ProcessorInclude.java
protected void parse(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
TransformerFactoryImpl processor = handler.getStylesheetProcessor();
URIResolver uriresolver = processor.getURIResolver();
try
{
Source source = null;
// The base identifier, an aboslute URI
// that is associated with the included/imported
// stylesheet module is known in this method,
// so this method does the pushing of the
// base ID onto the stack.
if (null != uriresolver)
{
// There is a user provided URI resolver.
// At the startElement() call we would
// have tried to obtain a Source from it
// which we now retrieve
source = handler.peekSourceFromURIResolver();
if (null != source && source instanceof DOMSource)
{
Node node = ((DOMSource)source).getNode();
// There is a user provided URI resolver.
// At the startElement() call we would
// have already pushed the system ID, obtained
// from either the source.getSystemId(), if non-null
// or from SystemIDResolver.getAbsoluteURI() as a backup
// which we now retrieve.
String systemId = handler.peekImportURL();
// Push the absolute URI of the included/imported
// stylesheet module onto the stack.
if (systemId != null)
handler.pushBaseIndentifier(systemId);
TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), systemId);
try
{
walker.traverse(node);
}
catch(org.xml.sax.SAXException se)
{
throw new TransformerException(se);
}
if (systemId != null)
handler.popBaseIndentifier();
return;
}
}
if(null == source)
{
String absURL = SystemIDResolver.getAbsoluteURI(getHref(),
handler.getBaseIdentifier());
source = new StreamSource(absURL);
}
// possible callback to a class that over-rides this method.
source = processSource(handler, source);
XMLReader reader = null;
if(source instanceof SAXSource)
{
SAXSource saxSource = (SAXSource)source;
reader = saxSource.getXMLReader(); // may be null
}
InputSource inputSource = SAXSource.sourceToInputSource(source);
if (null == reader)
{
// Use JAXP1.1 ( if possible )
try {
javax.xml.parsers.SAXParserFactory factory=
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware( true );
if (handler.getStylesheetProcessor().isSecureProcessing())
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser=
factory.newSAXParser();
reader=jaxpParser.getXMLReader();
} catch( javax.xml.parsers.ParserConfigurationException ex ) {
throw new org.xml.sax.SAXException( ex );
} catch( javax.xml.parsers.FactoryConfigurationError ex1 ) {
throw new org.xml.sax.SAXException( ex1.toString() );
}
catch( NoSuchMethodError ex2 )
{
}
catch (AbstractMethodError ame){}
}
if (null == reader)
reader = XMLReaderFactory.createXMLReader();
if (null != reader)
{
reader.setContentHandler(handler);
// Push the absolute URI of the included/imported
// stylesheet module onto the stack.
handler.pushBaseIndentifier(inputSource.getSystemId());
try
{
reader.parse(inputSource);
}
finally
{
handler.popBaseIndentifier();
}
}
}
catch (IOException ioe)
{
handler.error(XSLTErrorResources.ER_IOEXCEPTION,
new Object[]{ getHref() }, ioe);
}
catch(TransformerException te)
{
handler.error(te.getMessage(), te);
}
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public InputSource resolveEntity(
StylesheetHandler handler, String publicId, String systemId)
throws org.xml.sax.SAXException
{
return null;
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void startNonText(StylesheetHandler handler) throws org.xml.sax.SAXException
{
// no op
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
if (m_savedLastOrder == null)
m_savedLastOrder = new IntStack();
m_savedLastOrder.push(getElemDef().getLastOrder());
getElemDef().setLastOrder(-1);
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
if (m_savedLastOrder != null && !m_savedLastOrder.empty())
getElemDef().setLastOrder(m_savedLastOrder.pop());
if (!getElemDef().getRequiredFound())
handler.error(XSLTErrorResources.ER_REQUIRED_ELEM_NOT_FOUND, new Object[]{getElemDef().getRequiredElem()}, null);
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void characters(
StylesheetHandler handler, char ch[], int start, int length)
throws org.xml.sax.SAXException
{
handler.error(XSLTErrorResources.ER_CHARS_NOT_ALLOWED, null, null);//"Characters are not allowed at this point in the document!",
//null);
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void ignorableWhitespace(
StylesheetHandler handler, char ch[], int start, int length)
throws org.xml.sax.SAXException
{
// no op
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void processingInstruction(
StylesheetHandler handler, String target, String data)
throws org.xml.sax.SAXException
{
// no op
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
public void skippedEntity(StylesheetHandler handler, String name)
throws org.xml.sax.SAXException
{
// no op
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
void setPropertiesFromAttributes(
StylesheetHandler handler, String rawName, Attributes attributes,
ElemTemplateElement target)
throws org.xml.sax.SAXException
{
setPropertiesFromAttributes(handler, rawName, attributes, target, true);
}
// in src/org/apache/xalan/processor/XSLTElementProcessor.java
Attributes setPropertiesFromAttributes(
StylesheetHandler handler, String rawName, Attributes attributes,
ElemTemplateElement target, boolean throwError)
throws org.xml.sax.SAXException
{
XSLTElementDef def = getElemDef();
AttributesImpl undefines = null;
boolean isCompatibleMode = ((null != handler.getStylesheet()
&& handler.getStylesheet().getCompatibleMode())
|| !throwError);
if (isCompatibleMode)
undefines = new AttributesImpl();
// Keep track of which XSLTAttributeDefs have been processed, so
// I can see which default values need to be set.
List processedDefs = new ArrayList();
// Keep track of XSLTAttributeDefs that were invalid
List errorDefs = new ArrayList();
int nAttrs = attributes.getLength();
for (int i = 0; i < nAttrs; i++)
{
String attrUri = attributes.getURI(i);
// Hack for Crimson. -sb
if((null != attrUri) && (attrUri.length() == 0)
&& (attributes.getQName(i).startsWith("xmlns:") ||
attributes.getQName(i).equals("xmlns")))
{
attrUri = org.apache.xalan.templates.Constants.S_XMLNAMESPACEURI;
}
String attrLocalName = attributes.getLocalName(i);
XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName);
if (null == attrDef)
{
if (!isCompatibleMode)
{
// Then barf, because this element does not allow this attribute.
handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//"\""+attributes.getQName(i)+"\""
//+ " attribute is not allowed on the " + rawName
// + " element!", null);
}
else
{
undefines.addAttribute(attrUri, attrLocalName,
attributes.getQName(i),
attributes.getType(i),
attributes.getValue(i));
}
}
else
{
// Can we switch the order here:
boolean success = attrDef.setAttrValue(handler, attrUri, attrLocalName,
attributes.getQName(i), attributes.getValue(i),
target);
// Now we only add the element if it passed a validation check
if (success)
processedDefs.add(attrDef);
else
errorDefs.add(attrDef);
}
}
XSLTAttributeDef[] attrDefs = def.getAttributes();
int nAttrDefs = attrDefs.length;
for (int i = 0; i < nAttrDefs; i++)
{
XSLTAttributeDef attrDef = attrDefs[i];
String defVal = attrDef.getDefault();
if (null != defVal)
{
if (!processedDefs.contains(attrDef))
{
attrDef.setDefAttrValue(handler, target);
}
}
if (attrDef.getRequired())
{
if ((!processedDefs.contains(attrDef)) && (!errorDefs.contains(attrDef)))
handler.error(
XSLMessages.createMessage(
XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName,
attrDef.getName() }), null);
}
}
return undefines;
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public InputSource resolveEntity(String publicId, String systemId)
throws org.xml.sax.SAXException
{
return getCurrentProcessor().resolveEntity(this, publicId, systemId);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
XSLTElementProcessor getProcessorFor(
String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
XSLTElementProcessor currentProcessor = getCurrentProcessor();
XSLTElementDef def = currentProcessor.getElemDef();
XSLTElementProcessor elemProcessor = def.getProcessorFor(uri, localName);
if (null == elemProcessor
&& !(currentProcessor instanceof ProcessorStylesheetDoc)
&& ((null == getStylesheet()
|| Double.valueOf(getStylesheet().getVersion()).doubleValue()
> Constants.XSLTVERSUPPORTED)
||(!uri.equals(Constants.S_XSLNAMESPACEURL) &&
currentProcessor instanceof ProcessorStylesheetElement)
|| getElemVersion() > Constants.XSLTVERSUPPORTED
))
{
elemProcessor = def.getProcessorForUnknown(uri, localName);
}
if (null == elemProcessor)
error(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_ALLOWED_IN_POSITION, new Object[]{rawName}),null);//rawName + " is not allowed in this position in the stylesheet!",
return elemProcessor;
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void startDocument() throws org.xml.sax.SAXException
{
m_stylesheetLevel++;
pushSpaceHandling(false);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void endDocument() throws org.xml.sax.SAXException
{
try
{
if (null != getStylesheetRoot())
{
if (0 == m_stylesheetLevel)
getStylesheetRoot().recompose();
}
else
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEETROOT, null)); //"Did not find the stylesheet root!");
XSLTElementProcessor elemProcessor = getCurrentProcessor();
if (null != elemProcessor)
elemProcessor.startNonText(this);
m_stylesheetLevel--;
popSpaceHandling();
// WARNING: This test works only as long as stylesheets are parsed
// more or less recursively. If we switch to an iterative "work-list"
// model, this will become true prematurely. In that case,
// isStylesheetParsingComplete() will have to be adjusted to be aware
// of the worklist.
m_parsingComplete = (m_stylesheetLevel < 0);
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException
{
// m_nsSupport.pushContext();
// this.getNamespaceSupport().declarePrefix(prefix, uri);
//m_prefixMappings.add(prefix); // JDK 1.2+ only -sc
//m_prefixMappings.add(uri); // JDK 1.2+ only -sc
m_prefixMappings.addElement(prefix); // JDK 1.1.x compat -sc
m_prefixMappings.addElement(uri); // JDK 1.1.x compat -sc
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException
{
// m_nsSupport.popContext();
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
private void flushCharacters() throws org.xml.sax.SAXException
{
XSLTElementProcessor elemProcessor = getCurrentProcessor();
if (null != elemProcessor)
elemProcessor.startNonText(this);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void startElement(
String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
NamespaceSupport nssupport = this.getNamespaceSupport();
nssupport.pushContext();
int n = m_prefixMappings.size();
for (int i = 0; i < n; i++)
{
String prefix = (String)m_prefixMappings.elementAt(i++);
String nsURI = (String)m_prefixMappings.elementAt(i);
nssupport.declarePrefix(prefix, nsURI);
}
//m_prefixMappings.clear(); // JDK 1.2+ only -sc
m_prefixMappings.removeAllElements(); // JDK 1.1.x compat -sc
m_elementID++;
// This check is currently done for all elements. We should possibly consider
// limiting this check to xsl:stylesheet elements only since that is all it really
// applies to. Also, it could be bypassed if m_shouldProcess is already true.
// In other words, the next two statements could instead look something like this:
// if (!m_shouldProcess)
// {
// if (localName.equals(Constants.ELEMNAME_STYLESHEET_STRING) &&
// url.equals(Constants.S_XSLNAMESPACEURL))
// {
// checkForFragmentID(attributes);
// if (!m_shouldProcess)
// return;
// }
// else
// return;
// }
// I didn't include this code statement at this time because in practice
// it is a small performance hit and I was waiting to see if its absence
// caused a problem. - GLP
checkForFragmentID(attributes);
if (!m_shouldProcess)
return;
flushCharacters();
pushSpaceHandling(attributes);
XSLTElementProcessor elemProcessor = getProcessorFor(uri, localName,
rawName);
if(null != elemProcessor) // defensive, for better multiple error reporting. -sb
{
this.pushProcessor(elemProcessor);
elemProcessor.startElement(this, uri, localName, rawName, attributes);
}
else
{
m_shouldProcess = false;
popSpaceHandling();
}
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void endElement(String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
m_elementID--;
if (!m_shouldProcess)
return;
if ((m_elementID + 1) == m_fragmentID)
m_shouldProcess = false;
flushCharacters();
popSpaceHandling();
XSLTElementProcessor p = getCurrentProcessor();
p.endElement(this, uri, localName, rawName);
this.popProcessor();
this.getNamespaceSupport().popContext();
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void characters(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if (!m_shouldProcess)
return;
XSLTElementProcessor elemProcessor = getCurrentProcessor();
XSLTElementDef def = elemProcessor.getElemDef();
if (def.getType() != XSLTElementDef.T_PCDATA)
elemProcessor = def.getProcessorFor(null, "text()");
if (null == elemProcessor)
{
// If it's whitespace, just ignore it, otherwise flag an error.
if (!XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
error(
XSLMessages.createMessage(XSLTErrorResources.ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION, null),null);//"Non-whitespace text is not allowed in this position in the stylesheet!",
}
else
elemProcessor.characters(this, ch, start, length);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException
{
if (!m_shouldProcess)
return;
getCurrentProcessor().ignorableWhitespace(this, ch, start, length);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
if (!m_shouldProcess)
return;
// Recreating Scott's kluge:
// A xsl:for-each or xsl:apply-templates may have a special
// PI that tells us not to cache the document. This PI
// should really be namespaced.
// String localName = getLocalName(target);
// String ns = m_stylesheet.getNamespaceFromStack(target);
//
// %REVIEW%: We need a better PI architecture
String prefix="",ns="", localName=target;
int colon=target.indexOf(':');
if(colon>=0)
{
ns=getNamespaceForPrefix(prefix=target.substring(0,colon));
localName=target.substring(colon+1);
}
try
{
// A xsl:for-each or xsl:apply-templates may have a special
// PI that tells us not to cache the document. This PI
// should really be namespaced... but since the XML Namespaces
// spec never defined namespaces as applying to PI's, and since
// the testcase we're trying to support is inconsistant in whether
// it binds the prefix, I'm going to make this sloppy for
// testing purposes.
if(
"xalan-doc-cache-off".equals(target) ||
"xalan:doc-cache-off".equals(target) ||
("doc-cache-off".equals(localName) &&
ns.equals("org.apache.xalan.xslt.extensions.Redirect") )
)
{
if(!(m_elems.peek() instanceof ElemForEach))
throw new TransformerException
("xalan:doc-cache-off not allowed here!",
getLocator());
ElemForEach elem = (ElemForEach)m_elems.peek();
elem.m_doc_cache_off = true;
//System.out.println("JJK***** Recognized <? {"+ns+"}"+prefix+":"+localName+" "+data+"?>");
}
}
catch(Exception e)
{
// JJK: Officially, unknown PIs can just be ignored.
// Do we want to issue a warning?
}
flushCharacters();
getCurrentProcessor().processingInstruction(this, target, data);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void skippedEntity(String name) throws org.xml.sax.SAXException
{
if (!m_shouldProcess)
return;
getCurrentProcessor().skippedEntity(this, name);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void warn(String msg, Object args[]) throws org.xml.sax.SAXException
{
String formattedMsg = XSLMessages.createWarning(msg, args);
SAXSourceLocator locator = getLocator();
ErrorListener handler = m_stylesheetProcessor.getErrorListener();
try
{
if (null != handler)
handler.warning(new TransformerException(formattedMsg, locator));
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
protected void error(String msg, Exception e)
throws org.xml.sax.SAXException
{
SAXSourceLocator locator = getLocator();
ErrorListener handler = m_stylesheetProcessor.getErrorListener();
TransformerException pe;
if (!(e instanceof TransformerException))
{
pe = (null == e)
? new TransformerException(msg, locator)
: new TransformerException(msg, locator, e);
}
else
pe = (TransformerException) e;
if (null != handler)
{
try
{
handler.error(pe);
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
else
throw new org.xml.sax.SAXException(pe);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
protected void error(String msg, Object args[], Exception e)
throws org.xml.sax.SAXException
{
String formattedMsg = XSLMessages.createMessage(msg, args);
error(formattedMsg, e);
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void warning(org.xml.sax.SAXParseException e)
throws org.xml.sax.SAXException
{
String formattedMsg = e.getMessage();
SAXSourceLocator locator = getLocator();
ErrorListener handler = m_stylesheetProcessor.getErrorListener();
try
{
handler.warning(new TransformerException(formattedMsg, locator));
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void error(org.xml.sax.SAXParseException e)
throws org.xml.sax.SAXException
{
String formattedMsg = e.getMessage();
SAXSourceLocator locator = getLocator();
ErrorListener handler = m_stylesheetProcessor.getErrorListener();
try
{
handler.error(new TransformerException(formattedMsg, locator));
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/StylesheetHandler.java
public void fatalError(org.xml.sax.SAXParseException e)
throws org.xml.sax.SAXException
{
String formattedMsg = e.getMessage();
SAXSourceLocator locator = getLocator();
ErrorListener handler = m_stylesheetProcessor.getErrorListener();
try
{
handler.fatalError(new TransformerException(formattedMsg, locator));
}
catch (TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/ProcessorGlobalParamDecl.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
// Just push, but don't append.
handler.pushElemTemplateElement(elem);
}
// in src/org/apache/xalan/processor/ProcessorGlobalParamDecl.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
ElemParam v = (ElemParam) handler.getElemTemplateElement();
handler.getStylesheet().appendChild(v);
handler.getStylesheet().setParam(v);
super.endElement(handler, uri, localName, rawName);
}
// in src/org/apache/xalan/processor/ProcessorGlobalVariableDecl.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
// Just push, but don't append.
handler.pushElemTemplateElement(elem);
}
// in src/org/apache/xalan/processor/ProcessorGlobalVariableDecl.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
ElemVariable v = (ElemVariable) handler.getElemTemplateElement();
handler.getStylesheet().appendChild(v);
handler.getStylesheet().setVariable(v);
super.endElement(handler, uri, localName, rawName);
}
// in src/org/apache/xalan/processor/ProcessorStylesheetElement.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
super.startElement(handler, uri, localName, rawName, attributes);
try
{
int stylesheetType = handler.getStylesheetType();
Stylesheet stylesheet;
if (stylesheetType == StylesheetHandler.STYPE_ROOT)
{
try
{
stylesheet = getStylesheetRoot(handler);
}
catch(TransformerConfigurationException tfe)
{
throw new TransformerException(tfe);
}
}
else
{
Stylesheet parent = handler.getStylesheet();
if (stylesheetType == StylesheetHandler.STYPE_IMPORT)
{
StylesheetComposed sc = new StylesheetComposed(parent);
parent.setImport(sc);
stylesheet = sc;
}
else
{
stylesheet = new Stylesheet(parent);
parent.setInclude(stylesheet);
}
}
stylesheet.setDOMBackPointer(handler.getOriginatingNode());
stylesheet.setLocaterInfo(handler.getLocator());
stylesheet.setPrefixes(handler.getNamespaceSupport());
handler.pushStylesheet(stylesheet);
setPropertiesFromAttributes(handler, rawName, attributes,
handler.getStylesheet());
handler.pushElemTemplateElement(handler.getStylesheet());
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/processor/ProcessorStylesheetElement.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
super.endElement(handler, uri, localName, rawName);
handler.popElemTemplateElement();
handler.popStylesheet();
}
// in src/org/apache/xalan/processor/ProcessorExsltFunction.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws SAXException
{
//System.out.println("ProcessorFunction.startElement()");
String msg = "";
if (!(handler.getElemTemplateElement() instanceof Stylesheet))
{
msg = "func:function element must be top level.";
handler.error(msg, new SAXException(msg));
}
super.startElement(handler, uri, localName, rawName, attributes);
String val = attributes.getValue("name");
int indexOfColon = val.indexOf(":");
if (indexOfColon > 0)
{
//String prefix = val.substring(0, indexOfColon);
//String localVal = val.substring(indexOfColon + 1);
//String ns = handler.getNamespaceSupport().getURI(prefix);
//if (ns.length() > 0)
// System.out.println("fullfuncname " + ns + localVal);
}
else
{
msg = "func:function name must have namespace";
handler.error(msg, new SAXException(msg));
}
}
// in src/org/apache/xalan/processor/ProcessorExsltFunction.java
protected void appendAndPush(
StylesheetHandler handler, ElemTemplateElement elem)
throws SAXException
{
//System.out.println("ProcessorFunction appendAndPush()" + elem);
super.appendAndPush(handler, elem);
//System.out.println("originating node " + handler.getOriginatingNode());
elem.setDOMBackPointer(handler.getOriginatingNode());
handler.getStylesheet().setTemplate((ElemTemplate) elem);
}
// in src/org/apache/xalan/processor/ProcessorExsltFunction.java
public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws SAXException
{
ElemTemplateElement function = handler.getElemTemplateElement();
validate(function, handler); // may throw exception
super.endElement(handler, uri, localName, rawName);
}
// in src/org/apache/xalan/processor/ProcessorExsltFunction.java
public void validate(ElemTemplateElement elem, StylesheetHandler handler)
throws SAXException
{
String msg = "";
while (elem != null)
{
//System.out.println("elem " + elem);
if (elem instanceof ElemExsltFuncResult
&& elem.getNextSiblingElem() != null
&& !(elem.getNextSiblingElem() instanceof ElemFallback))
{
msg = "func:result has an illegal following sibling (only xsl:fallback allowed)";
handler.error(msg, new SAXException(msg));
}
if((elem instanceof ElemApplyImport
|| elem instanceof ElemApplyTemplates
|| elem instanceof ElemAttribute
|| elem instanceof ElemCallTemplate
|| elem instanceof ElemComment
|| elem instanceof ElemCopy
|| elem instanceof ElemCopyOf
|| elem instanceof ElemElement
|| elem instanceof ElemLiteralResult
|| elem instanceof ElemNumber
|| elem instanceof ElemPI
|| elem instanceof ElemText
|| elem instanceof ElemTextLiteral
|| elem instanceof ElemValueOf)
&& !(ancestorIsOk(elem)))
{
msg ="misplaced literal result in a func:function container.";
handler.error(msg, new SAXException(msg));
}
ElemTemplateElement nextElem = elem.getFirstChildElem();
while (nextElem == null)
{
nextElem = elem.getNextSiblingElem();
if (nextElem == null)
elem = elem.getParentElem();
if (elem == null || elem instanceof ElemExsltFunction)
return; // ok
}
elem = nextElem;
}
}
// in src/org/apache/xalan/processor/ProcessorKey.java
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
KeyDeclaration kd = new KeyDeclaration(handler.getStylesheet(), handler.nextUid());
kd.setDOMBackPointer(handler.getOriginatingNode());
kd.setLocaterInfo(handler.getLocator());
setPropertiesFromAttributes(handler, rawName, attributes, kd);
handler.getStylesheet().setKey(kd);
}
// in src/org/apache/xalan/processor/ProcessorKey.java
void setPropertiesFromAttributes(
StylesheetHandler handler, String rawName, Attributes attributes,
org.apache.xalan.templates.ElemTemplateElement target)
throws org.xml.sax.SAXException
{
XSLTElementDef def = getElemDef();
// Keep track of which XSLTAttributeDefs have been processed, so
// I can see which default values need to be set.
List processedDefs = new ArrayList();
int nAttrs = attributes.getLength();
for (int i = 0; i < nAttrs; i++)
{
String attrUri = attributes.getURI(i);
String attrLocalName = attributes.getLocalName(i);
XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName);
if (null == attrDef)
{
// Then barf, because this element does not allow this attribute.
handler.error(attributes.getQName(i)
+ "attribute is not allowed on the " + rawName
+ " element!", null);
}
else
{
String valueString = attributes.getValue(i);
if (valueString.indexOf(org.apache.xpath.compiler.Keywords.FUNC_KEY_STRING
+ "(") >= 0)
handler.error(
XSLMessages.createMessage(
XSLTErrorResources.ER_INVALID_KEY_CALL, null), null);
processedDefs.add(attrDef);
attrDef.setAttrValue(handler, attrUri, attrLocalName,
attributes.getQName(i), attributes.getValue(i),
target);
}
}
XSLTAttributeDef[] attrDefs = def.getAttributes();
int nAttrDefs = attrDefs.length;
for (int i = 0; i < nAttrDefs; i++)
{
XSLTAttributeDef attrDef = attrDefs[i];
String defVal = attrDef.getDefault();
if (null != defVal)
{
if (!processedDefs.contains(attrDef))
{
attrDef.setDefAttrValue(handler, target);
}
}
if (attrDef.getRequired())
{
if (!processedDefs.contains(attrDef))
handler.error(
XSLMessages.createMessage(
XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName,
attrDef.getName() }), null);
}
}
}
// in src/org/apache/xalan/transformer/TrAXFilter.java
public void parse (InputSource input)
throws org.xml.sax.SAXException, IOException
{
if(null == getParent())
{
XMLReader reader=null;
// Use JAXP1.1 ( if possible )
try {
javax.xml.parsers.SAXParserFactory factory=
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware( true );
if (m_transformer.getStylesheet().isSecureProcessing()) {
try {
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser=
factory.newSAXParser();
reader=jaxpParser.getXMLReader();
} catch( javax.xml.parsers.ParserConfigurationException ex ) {
throw new org.xml.sax.SAXException( ex );
} catch( javax.xml.parsers.FactoryConfigurationError ex1 ) {
throw new org.xml.sax.SAXException( ex1.toString() );
} catch( NoSuchMethodError ex2 ) {
}
catch (AbstractMethodError ame){}
XMLReader parent;
if( reader==null )
parent= XMLReaderFactory.createXMLReader();
else
parent=reader;
try
{
parent.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
}
catch (org.xml.sax.SAXException se){}
// setParent calls setupParse...
setParent(parent);
}
else
{
// Make sure everything is set up.
setupParse ();
}
if(null == m_transformer.getContentHandler())
{
throw new org.xml.sax.SAXException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_CALL_PARSE, null)); //"parse can not be called if the ContentHandler has not been set!");
}
getParent().parse(input);
Exception e = m_transformer.getExceptionThrown();
if(null != e)
{
if(e instanceof org.xml.sax.SAXException)
throw (org.xml.sax.SAXException)e;
else
throw new org.xml.sax.SAXException(e);
}
}
// in src/org/apache/xalan/transformer/TrAXFilter.java
public void parse (String systemId)
throws org.xml.sax.SAXException, IOException
{
parse(new InputSource(systemId));
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException
{
if (m_entityResolver != null)
{
return m_entityResolver.resolveEntity(publicId, systemId);
}
else
{
return null;
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void notationDecl(String name, String publicId, String systemId)
throws SAXException
{
if (m_dtdHandler != null)
{
m_dtdHandler.notationDecl(name, publicId, systemId);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void unparsedEntityDecl(
String name, String publicId, String systemId, String notationName)
throws SAXException
{
if (m_dtdHandler != null)
{
m_dtdHandler.unparsedEntityDecl(name, publicId, systemId, notationName);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startDocument() throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startDocument");
m_insideParse = true;
// Thread listener = new Thread(m_transformer);
if (m_contentHandler != null)
{
//m_transformer.setTransformThread(listener);
if(m_incremental)
{
m_transformer.setSourceTreeDocForThread(m_dtm.getDocument());
int cpriority = Thread.currentThread().getPriority();
// runTransformThread is equivalent with the 2.0.1 code,
// except that the Thread may come from a pool.
m_transformer.runTransformThread( cpriority );
}
// This is now done _last_, because IncrementalSAXSource_Filter
// will immediately go into a "wait until events are requested"
// pause. I believe that will close our timing window.
// %REVIEW%
m_contentHandler.startDocument();
}
//listener.setDaemon(false);
//listener.start();
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endDocument() throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endDocument");
m_insideParse = false;
if (m_contentHandler != null)
{
m_contentHandler.endDocument();
}
if(m_incremental)
{
m_transformer.waitTransformThread();
}
else
{
m_transformer.setSourceTreeDocForThread(m_dtm.getDocument());
m_transformer.run();
}
/* Thread transformThread = m_transformer.getTransformThread();
if (null != transformThread)
{
try
{
// This should wait until the transformThread is considered not alive.
transformThread.join();
if (!m_transformer.hasTransformThreadErrorCatcher())
{
Exception e = m_transformer.getExceptionThrown();
if (null != e)
throw new org.xml.sax.SAXException(e);
}
m_transformer.setTransformThread(null);
}
catch (InterruptedException ie){}
}*/
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startPrefixMapping: "
+ prefix + ", " + uri);
if (m_contentHandler != null)
{
m_contentHandler.startPrefixMapping(prefix, uri);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endPrefixMapping(String prefix) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endPrefixMapping: "
+ prefix);
if (m_contentHandler != null)
{
m_contentHandler.endPrefixMapping(prefix);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startElement(
String uri, String localName, String qName, Attributes atts)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startElement: " + qName);
if (m_contentHandler != null)
{
m_contentHandler.startElement(uri, localName, qName, atts);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endElement: " + qName);
if (m_contentHandler != null)
{
m_contentHandler.endElement(uri, localName, qName);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void characters(char ch[], int start, int length) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#characters: " + start + ", "
+ length);
if (m_contentHandler != null)
{
m_contentHandler.characters(ch, start, length);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#ignorableWhitespace: "
+ start + ", " + length);
if (m_contentHandler != null)
{
m_contentHandler.ignorableWhitespace(ch, start, length);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void processingInstruction(String target, String data)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#processingInstruction: "
+ target + ", " + data);
if (m_contentHandler != null)
{
m_contentHandler.processingInstruction(target, data);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void skippedEntity(String name) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#skippedEntity: " + name);
if (m_contentHandler != null)
{
m_contentHandler.skippedEntity(name);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void warning(SAXParseException e) throws SAXException
{
// This is not great, but we really would rather have the error
// handler be the error listener if it is a error handler. Coroutine's fatalError
// can't really be configured, so I think this is the best thing right now
// for error reporting. Possibly another JAXP 1.1 hole. -sb
javax.xml.transform.ErrorListener errorListener = m_transformer.getErrorListener();
if(errorListener instanceof ErrorHandler)
{
((ErrorHandler)errorListener).warning(e);
}
else
{
try
{
errorListener.warning(new javax.xml.transform.TransformerException(e));
}
catch(javax.xml.transform.TransformerException te)
{
throw e;
}
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void error(SAXParseException e) throws SAXException
{
// %REVIEW% I don't think this should be called. -sb
// clearCoRoutine(e);
// This is not great, but we really would rather have the error
// handler be the error listener if it is a error handler. Coroutine's fatalError
// can't really be configured, so I think this is the best thing right now
// for error reporting. Possibly another JAXP 1.1 hole. -sb
javax.xml.transform.ErrorListener errorListener = m_transformer.getErrorListener();
if(errorListener instanceof ErrorHandler)
{
((ErrorHandler)errorListener).error(e);
if(null != m_errorHandler)
m_errorHandler.error(e); // may not be called.
}
else
{
try
{
errorListener.error(new javax.xml.transform.TransformerException(e));
if(null != m_errorHandler)
m_errorHandler.error(e); // may not be called.
}
catch(javax.xml.transform.TransformerException te)
{
throw e;
}
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void fatalError(SAXParseException e) throws SAXException
{
if(null != m_errorHandler)
{
try
{
m_errorHandler.fatalError(e);
}
catch(SAXParseException se)
{
// ignore
}
// clearCoRoutine(e);
}
// This is not great, but we really would rather have the error
// handler be the error listener if it is a error handler. Coroutine's fatalError
// can't really be configured, so I think this is the best thing right now
// for error reporting. Possibly another JAXP 1.1 hole. -sb
javax.xml.transform.ErrorListener errorListener = m_transformer.getErrorListener();
if(errorListener instanceof ErrorHandler)
{
((ErrorHandler)errorListener).fatalError(e);
if(null != m_errorHandler)
m_errorHandler.fatalError(e); // may not be called.
}
else
{
try
{
errorListener.fatalError(new javax.xml.transform.TransformerException(e));
if(null != m_errorHandler)
m_errorHandler.fatalError(e); // may not be called.
}
catch(javax.xml.transform.TransformerException te)
{
throw e;
}
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startDTD: " + name + ", "
+ publicId + ", " + systemId);
if (null != m_lexicalHandler)
{
m_lexicalHandler.startDTD(name, publicId, systemId);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endDTD() throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endDTD");
if (null != m_lexicalHandler)
{
m_lexicalHandler.endDTD();
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startEntity(String name) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startEntity: " + name);
if (null != m_lexicalHandler)
{
m_lexicalHandler.startEntity(name);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endEntity(String name) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endEntity: " + name);
if (null != m_lexicalHandler)
{
m_lexicalHandler.endEntity(name);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void startCDATA() throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#startCDATA");
if (null != m_lexicalHandler)
{
m_lexicalHandler.startCDATA();
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void endCDATA() throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#endCDATA");
if (null != m_lexicalHandler)
{
m_lexicalHandler.endCDATA();
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void comment(char ch[], int start, int length) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#comment: " + start + ", "
+ length);
if (null != m_lexicalHandler)
{
m_lexicalHandler.comment(ch, start, length);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void elementDecl(String name, String model) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#elementDecl: " + name + ", "
+ model);
if (null != m_declHandler)
{
m_declHandler.elementDecl(name, model);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void attributeDecl(
String eName, String aName, String type, String valueDefault, String value)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#attributeDecl: " + eName
+ ", " + aName + ", etc...");
if (null != m_declHandler)
{
m_declHandler.attributeDecl(eName, aName, type, valueDefault, value);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void internalEntityDecl(String name, String value)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#internalEntityDecl: " + name
+ ", " + value);
if (null != m_declHandler)
{
m_declHandler.internalEntityDecl(name, value);
}
}
// in src/org/apache/xalan/transformer/TransformerHandlerImpl.java
public void externalEntityDecl(
String name, String publicId, String systemId) throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#externalEntityDecl: " + name
+ ", " + publicId + ", " + systemId);
if (null != m_declHandler)
{
m_declHandler.externalEntityDecl(name, publicId, systemId);
}
}
// in src/org/apache/xalan/transformer/TreeWalker2Result.java
public void traverse(int pos) throws org.xml.sax.SAXException
{
m_dtm = m_transformer.getXPathContext().getDTM(pos);
m_startNode = pos;
super.traverse(pos);
}
// in src/org/apache/xalan/transformer/TreeWalker2Result.java
protected void endNode(int node) throws org.xml.sax.SAXException
{
super.endNode(node);
if(DTM.ELEMENT_NODE == m_dtm.getNodeType(node))
{
m_transformer.getXPathContext().popCurrentNode();
}
}
// in src/org/apache/xalan/transformer/TreeWalker2Result.java
protected void startNode(int node) throws org.xml.sax.SAXException
{
XPathContext xcntxt = m_transformer.getXPathContext();
try
{
if (DTM.ELEMENT_NODE == m_dtm.getNodeType(node))
{
xcntxt.pushCurrentNode(node);
if(m_startNode != node)
{
super.startNode(node);
}
else
{
String elemName = m_dtm.getNodeName(node);
String localName = m_dtm.getLocalName(node);
String namespace = m_dtm.getNamespaceURI(node);
//xcntxt.pushCurrentNode(node);
// SAX-like call to allow adding attributes afterwards
m_handler.startElement(namespace, localName, elemName);
boolean hasNSDecls = false;
DTM dtm = m_dtm;
for (int ns = dtm.getFirstNamespaceNode(node, true);
DTM.NULL != ns; ns = dtm.getNextNamespaceNode(node, ns, true))
{
SerializerUtils.ensureNamespaceDeclDeclared(m_handler,dtm, ns);
}
for (int attr = dtm.getFirstAttribute(node);
DTM.NULL != attr; attr = dtm.getNextAttribute(attr))
{
SerializerUtils.addAttribute(m_handler, attr);
}
}
}
else
{
xcntxt.pushCurrentNode(node);
super.startNode(node);
xcntxt.popCurrentNode();
}
}
catch(javax.xml.transform.TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
}
// in src/org/apache/xalan/transformer/TransformerImpl.java
public void waitTransformThread() throws SAXException
{
// This is called to make sure the task is done.
// It is possible that the thread has been reused -
// but for a different transformation. ( what if we
// recycle the transformer ? Not a problem since this is
// still in use. )
Thread transformThread = this.getTransformThread();
if (null != transformThread)
{
try
{
ThreadControllerWrapper.waitThread(transformThread, this);
if (!this.hasTransformThreadErrorCatcher())
{
Exception e = this.getExceptionThrown();
if (null != e)
{
e.printStackTrace();
throw new org.xml.sax.SAXException(e);
}
}
this.setTransformThread(null);
}
catch (InterruptedException ie){}
}
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void notationDecl(String name, String publicId, String systemId)
throws SAXException
{
if (null != m_resultDTDHandler)
m_resultDTDHandler.notationDecl(name, publicId, systemId);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void unparsedEntityDecl(
String name, String publicId, String systemId, String notationName)
throws SAXException
{
if (null != m_resultDTDHandler)
m_resultDTDHandler.unparsedEntityDecl(name, publicId, systemId,
notationName);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startDocument() throws SAXException
{
try
{
if (null == m_resultContentHandler)
createResultContentHandler(m_result);
}
catch (TransformerException te)
{
throw new SAXException(te.getMessage(), te);
}
// Reset for multiple transforms with this transformer.
m_flushedStartDoc = false;
m_foundFirstElement = false;
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
protected final void flushStartDoc()
throws SAXException
{
if(!m_flushedStartDoc)
{
if (m_resultContentHandler == null)
{
try
{
createResultContentHandler(m_result);
}
catch(TransformerException te)
{
throw new SAXException(te);
}
}
m_resultContentHandler.startDocument();
m_flushedStartDoc = true;
}
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endDocument() throws SAXException
{
flushStartDoc();
m_resultContentHandler.endDocument();
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.startPrefixMapping(prefix, uri);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endPrefixMapping(String prefix) throws SAXException
{
flushStartDoc();
m_resultContentHandler.endPrefixMapping(prefix);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startElement(
String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
if (!m_foundFirstElement && null != m_serializer)
{
m_foundFirstElement = true;
Serializer newSerializer;
try
{
newSerializer = SerializerSwitcher.switchSerializerIfHTML(uri,
localName, m_outputFormat.getProperties(), m_serializer);
}
catch (TransformerException te)
{
throw new SAXException(te);
}
if (newSerializer != m_serializer)
{
try
{
m_resultContentHandler = newSerializer.asContentHandler();
}
catch (IOException ioe) // why?
{
throw new SAXException(ioe);
}
if (m_resultContentHandler instanceof DTDHandler)
m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
if (m_resultContentHandler instanceof LexicalHandler)
m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
m_serializer = newSerializer;
}
}
flushStartDoc();
m_resultContentHandler.startElement(uri, localName, qName, attributes);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endElement(String uri, String localName, String qName)
throws SAXException
{
m_resultContentHandler.endElement(uri, localName, qName);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void characters(char ch[], int start, int length) throws SAXException
{
flushStartDoc();
m_resultContentHandler.characters(ch, start, length);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException
{
m_resultContentHandler.ignorableWhitespace(ch, start, length);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void processingInstruction(String target, String data)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.processingInstruction(target, data);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void skippedEntity(String name) throws SAXException
{
flushStartDoc();
m_resultContentHandler.skippedEntity(name);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
flushStartDoc();
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startDTD(name, publicId, systemId);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endDTD() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endDTD();
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startEntity(String name) throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startEntity(name);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endEntity(String name) throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endEntity(name);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void startCDATA() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startCDATA();
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void endCDATA() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endCDATA();
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void comment(char ch[], int start, int length) throws SAXException
{
flushStartDoc();
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.comment(ch, start, length);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void elementDecl (String name, String model)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.elementDecl(name, model);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void attributeDecl (String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.attributeDecl(eName, aName, type, valueDefault, value);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void internalEntityDecl (String name, String value)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.internalEntityDecl(name, value);
}
// in src/org/apache/xalan/transformer/TransformerIdentityImpl.java
public void externalEntityDecl (String name, String publicId,
String systemId)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.externalEntityDecl(name, publicId, systemId);
}
// in src/org/apache/xalan/serialize/SerializerUtils.java
public static void outputResultTreeFragment(
SerializationHandler handler,
XObject obj,
XPathContext support)
throws org.xml.sax.SAXException
{
int doc = obj.rtf();
DTM dtm = support.getDTM(doc);
if (null != dtm)
{
for (int n = dtm.getFirstChild(doc);
DTM.NULL != n;
n = dtm.getNextSibling(n))
{
handler.flushPending();
// I think. . . . This used to have a (true) arg
// to flush prefixes, will that cause problems ???
if (dtm.getNodeType(n) == DTM.ELEMENT_NODE
&& dtm.getNamespaceURI(n) == null)
handler.startPrefixMapping("", "");
dtm.dispatchToEvents(n, handler);
}
}
}
// in src/org/apache/xalan/serialize/SerializerUtils.java
public static void ensureNamespaceDeclDeclared(
SerializationHandler handler,
DTM dtm,
int namespace)
throws org.xml.sax.SAXException
{
String uri = dtm.getNodeValue(namespace);
String prefix = dtm.getNodeNameX(namespace);
if ((uri != null && uri.length() > 0) && (null != prefix))
{
String foundURI;
NamespaceMappings ns = handler.getNamespaceMappings();
if (ns != null)
{
foundURI = ns.lookupNamespace(prefix);
if ((null == foundURI) || !foundURI.equals(uri))
{
handler.startPrefixMapping(prefix, uri, false);
}
}
}
}
// in src/org/apache/xalan/lib/PipeDocument.java
public void pipeDocument(XSLProcessorContext context, ElemExtensionCall elem)
throws TransformerException, TransformerConfigurationException,
SAXException, IOException, FileNotFoundException
{
SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
// XML doc to transform.
String source = elem.getAttribute("source",
context.getContextNode(),
context.getTransformer());
TransformerImpl transImpl = context.getTransformer();
//Base URI for input doc, so base for relative URI to XML doc to transform.
String baseURLOfSource = transImpl.getBaseURLOfSource();
// Absolute URI for XML doc to transform.
String absSourceURL = SystemIDResolver.getAbsoluteURI(source, baseURLOfSource);
// Transformation target
String target = elem.getAttribute("target",
context.getContextNode(),
context.getTransformer());
XPathContext xctxt = context.getTransformer().getXPathContext();
int xt = xctxt.getDTMHandleFromNode(context.getContextNode());
// Get System Id for stylesheet; to be used to resolve URIs to other stylesheets.
String sysId = elem.getSystemId();
NodeList ssNodes = null;
NodeList paramNodes = null;
Node ssNode = null;
Node paramNode = null;
if (elem.hasChildNodes())
{
ssNodes = elem.getChildNodes();
// Vector to contain TransformerHandler for each stylesheet.
Vector vTHandler = new Vector(ssNodes.getLength());
// The child nodes of an extension element node are instances of
// ElemLiteralResult, which requires does not fully support the standard
// Node interface. Accordingly, some special handling is required (see below)
// to get attribute values.
for (int i = 0; i < ssNodes.getLength(); i++)
{
ssNode = ssNodes.item(i);
if (ssNode.getNodeType() == Node.ELEMENT_NODE
&& ((Element)ssNode).getTagName().equals("stylesheet")
&& ssNode instanceof ElemLiteralResult)
{
AVT avt = ((ElemLiteralResult)ssNode).getLiteralResultAttribute("href");
String href = avt.evaluate(xctxt,xt, elem);
String absURI = SystemIDResolver.getAbsoluteURI(href, sysId);
Templates tmpl = saxTFactory.newTemplates(new StreamSource(absURI));
TransformerHandler tHandler = saxTFactory.newTransformerHandler(tmpl);
Transformer trans = tHandler.getTransformer();
// AddTransformerHandler to vector
vTHandler.addElement(tHandler);
paramNodes = ssNode.getChildNodes();
for (int j = 0; j < paramNodes.getLength(); j++)
{
paramNode = paramNodes.item(j);
if (paramNode.getNodeType() == Node.ELEMENT_NODE
&& ((Element)paramNode).getTagName().equals("param")
&& paramNode instanceof ElemLiteralResult)
{
avt = ((ElemLiteralResult)paramNode).getLiteralResultAttribute("name");
String pName = avt.evaluate(xctxt,xt, elem);
avt = ((ElemLiteralResult)paramNode).getLiteralResultAttribute("value");
String pValue = avt.evaluate(xctxt,xt, elem);
trans.setParameter(pName, pValue);
}
}
}
}
usePipe(vTHandler, absSourceURL, target);
}
}
// in src/org/apache/xalan/lib/PipeDocument.java
public void usePipe(Vector vTHandler, String source, String target)
throws TransformerException, TransformerConfigurationException,
FileNotFoundException, IOException, SAXException, SAXNotRecognizedException
{
XMLReader reader = XMLReaderFactory.createXMLReader();
TransformerHandler tHFirst = (TransformerHandler)vTHandler.firstElement();
reader.setContentHandler(tHFirst);
reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHFirst);
for (int i = 1; i < vTHandler.size(); i++)
{
TransformerHandler tHFrom = (TransformerHandler)vTHandler.elementAt(i-1);
TransformerHandler tHTo = (TransformerHandler)vTHandler.elementAt(i);
tHFrom.setResult(new SAXResult(tHTo));
}
TransformerHandler tHLast = (TransformerHandler)vTHandler.lastElement();
Transformer trans = tHLast.getTransformer();
Properties outputProps = trans.getOutputProperties();
Serializer serializer = SerializerFactory.getSerializer(outputProps);
FileOutputStream out = new FileOutputStream(target);
try
{
serializer.setOutputStream(out);
tHLast.setResult(new SAXResult(serializer.asContentHandler()));
reader.parse(source);
}
finally
{
// Always clean up the FileOutputStream,
// even if an exception was thrown in the try block
if (out != null)
out.close();
}
}
// in src/org/apache/xalan/lib/sql/DTMDocument.java
protected static void dispatchNodeData( Node node, ContentHandler ch, int depth )throws org.xml.sax.SAXException
{
switch (node.getNodeType())
{
case Node.DOCUMENT_FRAGMENT_NODE :
case Node.DOCUMENT_NODE :
case Node.ELEMENT_NODE :
{
for (Node child = node.getFirstChild(); null != child;
child = child.getNextSibling())
{
dispatchNodeData(child, ch, depth+1);
}
}
break;
case Node.PROCESSING_INSTRUCTION_NODE : // %REVIEW%
case Node.COMMENT_NODE :
if(0 != depth)
break;
// NOTE: Because this operation works in the DOM space, it does _not_ attempt
// to perform Text Coalition. That should only be done in DTM space.
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE :
case Node.ATTRIBUTE_NODE :
String str = node.getNodeValue();
if(ch instanceof CharacterNodeHandler)
{
((CharacterNodeHandler)ch).characters(node);
}
else
{
ch.characters(str.toCharArray(), 0, str.length());
}
break;
// /* case Node.PROCESSING_INSTRUCTION_NODE :
// // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
// break; */
default :
// ignore
break;
}
}
// in src/org/apache/xalan/lib/sql/DTMDocument.java
public void dispatchToEvents( int parm1, ContentHandler parm2 )throws org.xml.sax.SAXException
{
if (DEBUG)
{
System.out.println(
"dispathcToEvents(" +
parm1 + "," +
parm2 + ")");
}
return;
}
// in src/org/apache/xalan/lib/sql/DTMDocument.java
public void dispatchCharactersEvents( int nodeHandle, ContentHandler ch, boolean normalize )throws org.xml.sax.SAXException
{
if (DEBUG)
{
System.out.println("dispatchCharacterEvents(" +
nodeHandle + "," +
ch + "," +
normalize + ")");
}
if(normalize)
{
XMLString str = getStringValue(nodeHandle);
str = str.fixWhiteSpace(true, true, false);
str.dispatchCharactersEvents(ch);
}
else
{
Node node = getNode(nodeHandle);
dispatchNodeData(node, ch, 0);
}
}
// in src/org/apache/xpath/objects/XObject.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
xstr().dispatchCharactersEvents(ch);
}
// in src/org/apache/xpath/objects/XStringForFSB.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
fsb().sendSAXcharacters(ch, m_start, m_length);
}
// in src/org/apache/xpath/objects/XStringForFSB.java
public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
throws org.xml.sax.SAXException
{
fsb().sendSAXComment(lh, m_start, m_length);
}
// in src/org/apache/xpath/objects/XString.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
String str = str();
ch.characters(str.toCharArray(), 0, str.length());
}
// in src/org/apache/xpath/objects/XString.java
public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
throws org.xml.sax.SAXException
{
String str = str();
lh.comment(str.toCharArray(), 0, str.length());
}
// in src/org/apache/xpath/objects/XStringForChars.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
ch.characters((char[])m_obj, m_start, m_length);
}
// in src/org/apache/xpath/objects/XStringForChars.java
public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
throws org.xml.sax.SAXException
{
lh.comment((char[])m_obj, m_start, m_length);
}
// in src/org/apache/xpath/objects/XNodeSet.java
public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
int node = item(0);
if(node != DTM.NULL)
{
m_dtmMgr.getDTM(node).dispatchCharactersEvents(node, ch, false);
}
}
// in src/org/apache/xpath/functions/FuncNormalizeSpace.java
public void executeCharsToContentHandler(XPathContext xctxt,
ContentHandler handler)
throws javax.xml.transform.TransformerException,
org.xml.sax.SAXException
{
if(Arg0IsNodesetExpr())
{
int node = getArg0AsNode(xctxt);
if(DTM.NULL != node)
{
DTM dtm = xctxt.getDTM(node);
dtm.dispatchCharactersEvents(node, handler, true);
}
}
else
{
XObject obj = execute(xctxt);
obj.dispatchCharactersEvents(handler);
}
}
// in src/org/apache/xpath/axes/LocPathIterator.java
public void executeCharsToContentHandler(
XPathContext xctxt, org.xml.sax.ContentHandler handler)
throws javax.xml.transform.TransformerException,
org.xml.sax.SAXException
{
LocPathIterator clone = (LocPathIterator)m_clones.getInstance();
int current = xctxt.getCurrentNode();
clone.setRoot(current, xctxt);
int node = clone.nextNode();
DTM dtm = clone.getDTM(node);
clone.detach();
if(node != DTM.NULL)
{
dtm.dispatchCharactersEvents(node, handler, false);
}
}
// in src/org/apache/xpath/Expression.java
public void executeCharsToContentHandler(
XPathContext xctxt, ContentHandler handler)
throws javax.xml.transform.TransformerException,
org.xml.sax.SAXException
{
XObject obj = execute(xctxt);
obj.dispatchCharactersEvents(handler);
obj.detach();
}