/*--
$Id: SAXOutputter.java,v 1.2 2013-03-01 23:21:46 fbusquets Exp $
Copyright (C) 2000-2004 Jason Hunter & Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "JDOM" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact
* Most ContentHandler callbacks are supported. Both
*
* At this time, it is not possible to access notations and unparsed entity
* references in a DTD from JDOM. Therefore,
* The
* All XMLReaders are required to support setting to true and to false.
*
* SAXOutputter currently supports the following SAX core features:
* ignorableWhitespace()
and skippedEntity()
have not
* been implemented. The {@link JDOMLocator}
class returned by
* {@link #getLocator}
exposes the current node being operated
* upon.
* DTDHandler
callbacks
* have not been implemented yet.
* ErrorHandler
callbacks have not been implemented, since
* these are supposed to be invoked when the document is parsed and at this
* point the document exists in memory and is known to have no errors. ContentHandler
*/
private ContentHandler contentHandler;
/** registered ErrorHandler
*/
private ErrorHandler errorHandler;
/** registered DTDHandler
*/
private DTDHandler dtdHandler;
/** registered EntityResolver
*/
private EntityResolver entityResolver;
/** registered LexicalHandler
*/
private LexicalHandler lexicalHandler;
/** registered DeclHandler
*/
private DeclHandler declHandler;
/**
* Whether to report attribute namespace declarations as xmlns attributes.
* Defaults to false
as per SAX specifications.
*
* @see
* SAX namespace specifications
*/
private boolean declareNamespaces = false;
/**
* Whether to report DTD events to DeclHandlers and LexicalHandlers.
* Defaults to true
.
*/
private boolean reportDtdEvents = true;
/**
* A SAX Locator that points at the JDOM node currently being
* outputted.
*/
private JDOMLocator locator = null;
/**
* This will create a SAXOutputter
without any
* registered handler. The application is then responsible for
* registering them using the setXxxHandler()
methods.
*/
public SAXOutputter() {
}
/**
* This will create a SAXOutputter
with the
* specified ContentHandler
.
*
* @param contentHandler contains ContentHandler
* callback methods
*/
public SAXOutputter(ContentHandler contentHandler) {
this(contentHandler, null, null, null, null);
}
/**
* This will create a SAXOutputter
with the
* specified SAX2 handlers. At this time, only ContentHandler
* and EntityResolver
are supported.
*
* @param contentHandler contains ContentHandler
* callback methods
* @param errorHandler contains ErrorHandler
callback methods
* @param dtdHandler contains DTDHandler
callback methods
* @param entityResolver contains EntityResolver
* callback methods
*/
public SAXOutputter(ContentHandler contentHandler,
ErrorHandler errorHandler,
DTDHandler dtdHandler,
EntityResolver entityResolver) {
this(contentHandler, errorHandler, dtdHandler, entityResolver, null);
}
/**
* This will create a SAXOutputter
with the
* specified SAX2 handlers. At this time, only ContentHandler
* and EntityResolver
are supported.
*
* @param contentHandler contains ContentHandler
* callback methods
* @param errorHandler contains ErrorHandler
callback methods
* @param dtdHandler contains DTDHandler
callback methods
* @param entityResolver contains EntityResolver
* callback methods
* @param lexicalHandler contains LexicalHandler
callbacks.
*/
public SAXOutputter(ContentHandler contentHandler,
ErrorHandler errorHandler,
DTDHandler dtdHandler,
EntityResolver entityResolver,
LexicalHandler lexicalHandler) {
this.contentHandler = contentHandler;
this.errorHandler = errorHandler;
this.dtdHandler = dtdHandler;
this.entityResolver = entityResolver;
this.lexicalHandler = lexicalHandler;
}
/**
* This will set the ContentHandler
.
*
* @param contentHandler contains ContentHandler
* callback methods.
*/
public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = contentHandler;
}
/**
* Returns the registered ContentHandler
.
*
* @return the current ContentHandler
or
* null
if none was registered.
*/
public ContentHandler getContentHandler() {
return this.contentHandler;
}
/**
* This will set the ErrorHandler
.
*
* @param errorHandler contains ErrorHandler
callback methods.
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the registered ErrorHandler
.
*
* @return the current ErrorHandler
or
* null
if none was registered.
*/
public ErrorHandler getErrorHandler() {
return this.errorHandler;
}
/**
* This will set the DTDHandler
.
*
* @param dtdHandler contains DTDHandler
callback methods.
*/
public void setDTDHandler(DTDHandler dtdHandler) {
this.dtdHandler = dtdHandler;
}
/**
* Return the registered DTDHandler
.
*
* @return the current DTDHandler
or
* null
if none was registered.
*/
public DTDHandler getDTDHandler() {
return this.dtdHandler;
}
/**
* This will set the EntityResolver
.
*
* @param entityResolver contains EntityResolver callback methods.
*/
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
/**
* Return the registered EntityResolver
.
*
* @return the current EntityResolver
or
* null
if none was registered.
*/
public EntityResolver getEntityResolver() {
return this.entityResolver;
}
/**
* This will set the LexicalHandler
.
*
* @param lexicalHandler contains lexical callback methods.
*/
public void setLexicalHandler(LexicalHandler lexicalHandler) {
this.lexicalHandler = lexicalHandler;
}
/**
* Return the registered LexicalHandler
.
*
* @return the current LexicalHandler
or
* null
if none was registered.
*/
public LexicalHandler getLexicalHandler() {
return this.lexicalHandler;
}
/**
* This will set the DeclHandler
.
*
* @param declHandler contains declaration callback methods.
*/
public void setDeclHandler(DeclHandler declHandler) {
this.declHandler = declHandler;
}
/**
* Return the registered DeclHandler
.
*
* @return the current DeclHandler
or
* null
if none was registered.
*/
public DeclHandler getDeclHandler() {
return this.declHandler;
}
/**
* Returns whether attribute namespace declarations shall be reported as
* "xmlns" attributes.
*
* @return whether attribute namespace declarations shall be reported as
* "xmlns" attributes.
*/
public boolean getReportNamespaceDeclarations() {
return declareNamespaces;
}
/**
* This will define whether attribute namespace declarations shall be
* reported as "xmlns" attributes. This flag defaults to false
* and behaves as the "namespace-prefixes" SAX core feature.
*
* @param declareNamespaces whether attribute namespace declarations
* shall be reported as "xmlns" attributes.
*/
public void setReportNamespaceDeclarations(boolean declareNamespaces) {
this.declareNamespaces = declareNamespaces;
}
/**
* Returns whether DTD events will be reported.
*
* @return whether DTD events will be reported
*/
public boolean getReportDTDEvents() {
return reportDtdEvents;
}
/**
* This will define whether to report DTD events to SAX DeclHandlers
* and LexicalHandlers if these handlers are registered and the
* document to output includes a DocType declaration.
*
* @param reportDtdEvents whether to notify DTD events.
*/
public void setReportDTDEvents(boolean reportDtdEvents) {
this.reportDtdEvents = reportDtdEvents;
}
/**
* This will set the state of a SAX feature.
*
*
* http://xml.org/sax/features/namespaces
true
indicates
* namespace URIs and unprefixed local names for element and
* attribute names will be availabletrue
!http://xml.org/sax/features/namespace-prefixes
true
indicates
* XML 1.0 names (with prefixes) and attributes (including xmlns*
* attributes) will be availablehttp://xml.org/sax/features/validation
true
, the
* DocType internal subset will be parsed to fire DTD eventstrue
String
the feature name, which is a
* fully-qualified URI.
* @param value boolean
the requested state of the
* feature (true or false).
*
* @throws SAXNotRecognizedException when SAXOutputter does not
* recognize the feature name.
* @throws SAXNotSupportedException when SAXOutputter recognizes
* the feature name but cannot set the requested value.
*/
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (NS_PREFIXES_SAX_FEATURE.equals(name)) {
// Namespace prefix declarations.
this.setReportNamespaceDeclarations(value);
}
else {
if (NAMESPACES_SAX_FEATURE.equals(name)) {
if (value != true) {
// Namespaces feature always supported by SAXOutputter.
throw new SAXNotSupportedException(name);
}
// Else: true is OK!
}
else {
if (VALIDATION_SAX_FEATURE.equals(name)) {
// Report DTD events.
this.setReportDTDEvents(value);
}
else {
// Not a supported feature.
throw new SAXNotRecognizedException(name);
}
}
}
}
/**
* This will look up the value of a SAX feature.
*
* @param name String
the feature name, which is a
* fully-qualified URI.
* @return boolean
the current state of the feature
* (true or false).
*
* @throws SAXNotRecognizedException when SAXOutputter does not
* recognize the feature name.
* @throws SAXNotSupportedException when SAXOutputter recognizes
* the feature name but determine its value at this time.
*/
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (NS_PREFIXES_SAX_FEATURE.equals(name)) {
// Namespace prefix declarations.
return (this.declareNamespaces);
}
else {
if (NAMESPACES_SAX_FEATURE.equals(name)) {
// Namespaces feature always supported by SAXOutputter.
return (true);
}
else {
if (VALIDATION_SAX_FEATURE.equals(name)) {
// Report DTD events.
return (this.reportDtdEvents);
}
else {
// Not a supported feature.
throw new SAXNotRecognizedException(name);
}
}
}
}
/**
* This will set the value of a SAX property.
* This method is also the standard mechanism for setting extended
* handlers.
* * SAXOutputter currently supports the following SAX properties: *
http://xml.org/sax/properties/lexical-handler
org.xml.sax.ext.LexicalHandler
http://xml.org/sax/properties/declaration-handler
org.xml.sax.ext.DeclHandler
String
the property name, which is a
* fully-qualified URI.
* @param value Object
the requested value for the property.
*
* @throws SAXNotRecognizedException when SAXOutputter does not recognize
* the property name.
* @throws SAXNotSupportedException when SAXOutputter recognizes the
* property name but cannot set the requested value.
*/
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if ((LEXICAL_HANDLER_SAX_PROPERTY.equals(name)) ||
(LEXICAL_HANDLER_ALT_PROPERTY.equals(name))) {
this.setLexicalHandler((LexicalHandler)value);
}
else {
if ((DECL_HANDLER_SAX_PROPERTY.equals(name)) ||
(DECL_HANDLER_ALT_PROPERTY.equals(name))) {
this.setDeclHandler((DeclHandler)value);
}
else {
throw new SAXNotRecognizedException(name);
}
}
}
/**
* This will look up the value of a SAX property.
*
* @param name String
the property name, which is a
* fully-qualified URI.
* @return Object
the current value of the property.
*
* @throws SAXNotRecognizedException when SAXOutputter does not recognize
* the property name.
* @throws SAXNotSupportedException when SAXOutputter recognizes the
* property name but cannot determine its value at this time.
*/
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if ((LEXICAL_HANDLER_SAX_PROPERTY.equals(name)) ||
(LEXICAL_HANDLER_ALT_PROPERTY.equals(name))) {
return this.getLexicalHandler();
}
else {
if ((DECL_HANDLER_SAX_PROPERTY.equals(name)) ||
(DECL_HANDLER_ALT_PROPERTY.equals(name))) {
return this.getDeclHandler();
}
else {
throw new SAXNotRecognizedException(name);
}
}
}
/**
* This will output the JDOM Document
, firing off the
* SAX events that have been registered.
*
* @param document JDOM Document
to output.
*
* @throws JDOMException if any error occurred.
*/
public void output(Document document) throws JDOMException {
if (document == null) {
return;
}
// contentHandler.setDocumentLocator()
documentLocator(document);
// contentHandler.startDocument()
startDocument();
// Fire DTD events
if (this.reportDtdEvents) {
dtdEvents(document);
}
// Handle root element, as well as any root level
// processing instructions and comments
Iterator i = document.getContent().iterator();
while (i.hasNext()) {
Object obj = i.next();
// update locator
locator.setNode(obj);
if (obj instanceof Element) {
// process root element and its content
element(document.getRootElement(), new NamespaceStack());
}
else if (obj instanceof ProcessingInstruction) {
// contentHandler.processingInstruction()
processingInstruction((ProcessingInstruction) obj);
}
else if (obj instanceof Comment) {
// lexicalHandler.comment()
comment(((Comment) obj).getText());
}
}
// contentHandler.endDocument()
endDocument();
}
/**
* This will output a list of JDOM nodes as a document, firing
* off the SAX events that have been registered.
* * Warning: This method may output ill-formed XML * documents if the list contains top-level objects that are not * legal at the document level (e.g. Text or CDATA nodes, multiple * Element nodes, etc.). Thus, it should only be used to output * document portions towards ContentHandlers capable of accepting * such ill-formed documents (such as XSLT processors).
* * @param nodesList
of JDOM nodes to output.
*
* @throws JDOMException if any error occurred.
*
* @see #output(org.jdom.Document)
*/
public void output(List nodes) throws JDOMException {
if ((nodes == null) || (nodes.size() == 0)) {
return;
}
// contentHandler.setDocumentLocator()
documentLocator(null);
// contentHandler.startDocument()
startDocument();
// Process node list.
elementContent(nodes, new NamespaceStack());
// contentHandler.endDocument()
endDocument();
}
/**
* This will output a single JDOM element as a document, firing
* off the SAX events that have been registered.
*
* @param node the Element
node to output.
*
* @throws JDOMException if any error occurred.
*/
public void output(Element node) throws JDOMException {
if (node == null) {
return;
}
// contentHandler.setDocumentLocator()
documentLocator(null);
// contentHandler.startDocument()
startDocument();
// Output node.
elementContent(node, new NamespaceStack());
// contentHandler.endDocument()
endDocument();
}
/**
* This will output a list of JDOM nodes as a fragment of an XML
* document, firing off the SAX events that have been registered.
* * Warning: This method does not call the * {@link ContentHandler#setDocumentLocator}, * {@link ContentHandler#startDocument} and * {@link ContentHandler#endDocument} callbacks on the * {@link #setContentHandler ContentHandler}. The user shall * invoke these methods directly prior/after outputting the * document fragments.
* * @param nodesList
of JDOM nodes to output.
*
* @throws JDOMException if any error occurred.
*
* @see #outputFragment(org.jdom.Content)
*/
public void outputFragment(List nodes) throws JDOMException {
if ((nodes == null) || (nodes.size() == 0)) {
return;
}
// Output node list as a document fragment.
elementContent(nodes, new NamespaceStack());
}
/**
* This will output a single JDOM nodes as a fragment of an XML
* document, firing off the SAX events that have been registered.
* * Warning: This method does not call the * {@link ContentHandler#setDocumentLocator}, * {@link ContentHandler#startDocument} and * {@link ContentHandler#endDocument} callbacks on the * {@link #setContentHandler ContentHandler}. The user shall * invoke these methods directly prior/after outputting the * document fragments.
* * @param node theContent
node to output.
*
* @throws JDOMException if any error occurred.
*
* @see #outputFragment(java.util.List)
*/
public void outputFragment(Content node) throws JDOMException {
if (node == null) {
return;
}
// Output single node as a document fragment.
elementContent(node, new NamespaceStack());
}
/**
* This parses a DTD declaration to fire the related events towards
* the registered handlers.
*
* @param document JDOM Document
the DocType is to
* process.
*/
private void dtdEvents(Document document) throws JDOMException {
DocType docType = document.getDocType();
// Fire DTD-related events only if handlers have been registered.
if ((docType != null) &&
((dtdHandler != null) || (declHandler != null))) {
// Build a dummy XML document that only references the DTD...
String dtdDoc = new XMLOutputter().outputString(docType);
try {
// And parse it to fire DTD events.
createDTDParser().parse(new InputSource(
new StringReader(dtdDoc)));
// We should never reach this point as the document is
// ill-formed; it does not have any root element.
}
catch (SAXParseException e) {
// Expected exception: There's no root element in document.
}
catch (SAXException e) {
throw new JDOMException("DTD parsing error", e);
}
catch (IOException e) {
throw new JDOMException("DTD parsing error", e);
}
}
}
/**
* * This method tells you the line of the XML file being parsed. * For an in-memory document, it's meaningless. The location * is only valid for the current parsing lifecycle, but * the document has already been parsed. Therefore, it returns * -1 for both line and column numbers. *
* * @param document JDOMDocument
.
*/
private void documentLocator(Document document) {
locator = new JDOMLocator();
String publicID = null;
String systemID = null;
if (document != null) {
DocType docType = document.getDocType();
if (docType != null) {
publicID = docType.getPublicID();
systemID = docType.getSystemID();
}
}
locator.setPublicId(publicID);
locator.setSystemId(systemID);
locator.setLineNumber(-1);
locator.setColumnNumber(-1);
contentHandler.setDocumentLocator(locator);
}
/**
* * This method is always the second method of all callbacks in * all handlers to be invoked (setDocumentLocator is always first). *
*/ private void startDocument() throws JDOMException { try { contentHandler.startDocument(); } catch (SAXException se) { throw new JDOMException("Exception in startDocument", se); } } /** ** Always the last method of all callbacks in all handlers * to be invoked. *
*/ private void endDocument() throws JDOMException { try { contentHandler.endDocument(); // reset locator locator = null; } catch (SAXException se) { throw new JDOMException("Exception in endDocument", se); } } /** *
* This will invoke the ContentHandler.processingInstruction
* callback when a processing instruction is encountered.
*
ProcessingInstruction
containing target and data.
*/
private void processingInstruction(ProcessingInstruction pi)
throws JDOMException {
if (pi != null) {
String target = pi.getTarget();
String data = pi.getData();
try {
contentHandler.processingInstruction(target, data);
}
catch (SAXException se) {
throw new JDOMException(
"Exception in processingInstruction", se);
}
}
}
/**
* * This will recursively invoke all of the callbacks for a particular * element. *
* * @param elementElement
used in callbacks.
* @param namespaces List
stack of Namespaces in scope.
*/
private void element(Element element, NamespaceStack namespaces)
throws JDOMException {
// used to check endPrefixMapping
int previouslyDeclaredNamespaces = namespaces.size();
// contentHandler.startPrefixMapping()
Attributes nsAtts = startPrefixMapping(element, namespaces);
// contentHandler.startElement()
startElement(element, nsAtts);
// handle content in the element
elementContent(element.getContent(), namespaces);
// update locator
locator.setNode(element);
// contentHandler.endElement()
endElement(element);
// contentHandler.endPrefixMapping()
endPrefixMapping(namespaces, previouslyDeclaredNamespaces);
}
/**
*
* This will invoke the ContentHandler.startPrefixMapping
* callback
* when a new namespace is encountered in the Document
.
*
Element
used in callbacks.
* @param namespaces List
stack of Namespaces in scope.
*
* @return Attributes
declaring the namespaces local to
* element
or null
.
*/
private Attributes startPrefixMapping(Element element,
NamespaceStack namespaces)
throws JDOMException {
AttributesImpl nsAtts = null; // The namespaces as xmlns attributes
Namespace ns = element.getNamespace();
if (ns != Namespace.XML_NAMESPACE) {
String prefix = ns.getPrefix();
String uri = namespaces.getURI(prefix);
if (!ns.getURI().equals(uri)) {
namespaces.push(ns);
nsAtts = this.addNsAttribute(nsAtts, ns);
try {
contentHandler.startPrefixMapping(prefix, ns.getURI());
}
catch (SAXException se) {
throw new JDOMException(
"Exception in startPrefixMapping", se);
}
}
}
// Fire additional namespace declarations
List additionalNamespaces = element.getAdditionalNamespaces();
if (additionalNamespaces != null) {
Iterator itr = additionalNamespaces.iterator();
while (itr.hasNext()) {
ns = (Namespace)itr.next();
String prefix = ns.getPrefix();
String uri = namespaces.getURI(prefix);
if (!ns.getURI().equals(uri)) {
namespaces.push(ns);
nsAtts = this.addNsAttribute(nsAtts, ns);
try {
contentHandler.startPrefixMapping(prefix, ns.getURI());
}
catch (SAXException se) {
throw new JDOMException(
"Exception in startPrefixMapping", se);
}
}
}
}
return nsAtts;
}
/**
*
* This will invoke the endPrefixMapping
callback in the
* ContentHandler
when a namespace is goes out of scope
* in the Document
.
*
List
stack of Namespaces in scope.
* @param previouslyDeclaredNamespaces number of previously declared
* namespaces
*/
private void endPrefixMapping(NamespaceStack namespaces,
int previouslyDeclaredNamespaces)
throws JDOMException {
while (namespaces.size() > previouslyDeclaredNamespaces) {
String prefix = namespaces.pop();
try {
contentHandler.endPrefixMapping(prefix);
}
catch (SAXException se) {
throw new JDOMException("Exception in endPrefixMapping", se);
}
}
}
/**
*
* This will invoke the startElement
callback
* in the ContentHandler
.
*
Element
used in callbacks.
* @param nsAtts List
of namespaces to declare with
* the element or null
.
*/
private void startElement(Element element, Attributes nsAtts)
throws JDOMException {
String namespaceURI = element.getNamespaceURI();
String localName = element.getName();
String rawName = element.getQualifiedName();
// Allocate attribute list.
AttributesImpl atts = (nsAtts != null)?
new AttributesImpl(nsAtts): new AttributesImpl();
List attributes = element.getAttributes();
Iterator i = attributes.iterator();
while (i.hasNext()) {
Attribute a = (Attribute) i.next();
atts.addAttribute(a.getNamespaceURI(),
a.getName(),
a.getQualifiedName(),
getAttributeTypeName(a.getAttributeType()),
a.getValue());
}
try {
contentHandler.startElement(namespaceURI, localName, rawName, atts);
}
catch (SAXException se) {
throw new JDOMException("Exception in startElement", se);
}
}
/**
*
* This will invoke the endElement
callback
* in the ContentHandler
.
*
Element
used in callbacks.
*/
private void endElement(Element element) throws JDOMException {
String namespaceURI = element.getNamespaceURI();
String localName = element.getName();
String rawName = element.getQualifiedName();
try {
contentHandler.endElement(namespaceURI, localName, rawName);
}
catch (SAXException se) {
throw new JDOMException("Exception in endElement", se);
}
}
/**
* * This will invoke the callbacks for the content of an element. *
* * @param content element content as aList
of nodes.
* @param namespaces List
stack of Namespaces in scope.
*/
private void elementContent(List content, NamespaceStack namespaces)
throws JDOMException {
for (Iterator i=content.iterator(); i.hasNext(); ) {
Object obj = i.next();
if (obj instanceof Content) {
this.elementContent((Content)obj, namespaces);
}
else {
// Not a valid element child. This could happen with
// application-provided lists which may contain non
// JDOM objects.
handleError(new JDOMException(
"Invalid element content: " + obj));
}
}
}
/**
* * This will invoke the callbacks for the content of an element. *
* * @param node aContent
node.
* @param namespaces List
stack of Namespaces in scope.
*/
private void elementContent(Content node, NamespaceStack namespaces)
throws JDOMException {
// update locator
locator.setNode(node);
if (node instanceof Element) {
element((Element) node, namespaces);
}
else if (node instanceof CDATA) {
cdata(((CDATA) node).getText());
}
else if (node instanceof Text) {
// contentHandler.characters()
characters(((Text) node).getText());
}
else if (node instanceof ProcessingInstruction) {
// contentHandler.processingInstruction()
processingInstruction((ProcessingInstruction) node);
}
else if (node instanceof Comment) {
// lexicalHandler.comment()
comment(((Comment) node).getText());
}
else if (node instanceof EntityRef) {
// contentHandler.skippedEntity()
entityRef((EntityRef) node);
}
else {
// Not a valid element child. This could happen with
// application-provided lists which may contain non
// JDOM objects.
handleError(new JDOMException("Invalid element content: " + node));
}
}
/**
* * This will be called for each chunk of CDATA section encountered. *
* * @param cdataText all text in the CDATA section, including whitespace. */ private void cdata(String cdataText) throws JDOMException { try { if (lexicalHandler != null) { lexicalHandler.startCDATA(); characters(cdataText); lexicalHandler.endCDATA(); } else { characters(cdataText); } } catch (SAXException se) { throw new JDOMException("Exception in CDATA", se); } } /** ** This will be called for each chunk of character data encountered. *
* * @param elementText all text in an element, including whitespace. */ private void characters(String elementText) throws JDOMException { char[] c = elementText.toCharArray(); try { contentHandler.characters(c, 0, c.length); } catch (SAXException se) { throw new JDOMException("Exception in characters", se); } } /** ** This will be called for each chunk of comment data encontered. *
* * @param commentText all text in a comment, including whitespace. */ private void comment(String commentText) throws JDOMException { if (lexicalHandler != null) { char[] c = commentText.toCharArray(); try { lexicalHandler.comment(c, 0, c.length); } catch (SAXException se) { throw new JDOMException("Exception in comment", se); } } } /** *
* This will invoke the ContentHandler.skippedEntity
* callback when an entity reference is encountered.
*
EntityRef
.
*/
private void entityRef(EntityRef entity) throws JDOMException {
if (entity != null) {
try {
// No need to worry about appending a '%' character as
// we do not support parameter entities
contentHandler.skippedEntity(entity.getName());
}
catch (SAXException se) {
throw new JDOMException("Exception in entityRef", se);
}
}
}
/**
* * Appends a namespace declaration in the form of a xmlns attribute to * an attribute list, crerating this latter if needed. *
* * @param attsAttributeImpl
where to add the attribute.
* @param ns Namespace
the namespace to declare.
*
* @return AttributeImpl
the updated attribute list.
*/
private AttributesImpl addNsAttribute(AttributesImpl atts, Namespace ns) {
if (this.declareNamespaces) {
if (atts == null) {
atts = new AttributesImpl();
}
atts.addAttribute("", // namespace
"", // local name
"xmlns:" + ns.getPrefix(), // qualified name
"CDATA", // type
ns.getURI()); // value
}
return atts;
}
/**
* * Returns the SAX 2.0 attribute type string from the type of * a JDOM Attribute. *
* * @param typeint
the type of the JDOM attribute.
*
* @return String
the SAX 2.0 attribute type string.
*
* @see org.jdom.Attribute#getAttributeType
* @see org.xml.sax.Attributes#getType
*/
private static String getAttributeTypeName(int type) {
if ((type < 0) || (type >= attrTypeToNameMap.length)) {
type = Attribute.UNDECLARED_TYPE;
}
return attrTypeToNameMap[type];
}
/**
* * Notifies the registered {@link ErrorHandler SAX error handler} * (if any) of an input processing error. The error handler can * choose to absorb the error and let the processing continue. *
* * @param exceptionJDOMException
containing the
* error information; will be wrapped in a
* {@link SAXParseException} when reported to
* the SAX error handler.
*
* @throws JDOMException if no error handler has been registered
* or if the error handler fired a
* {@link SAXException}.
*/
private void handleError(JDOMException exception) throws JDOMException {
if (errorHandler != null) {
try {
errorHandler.error(new SAXParseException(
exception.getMessage(), null, exception));
}
catch (SAXException se) {
if (se.getException() instanceof JDOMException) {
throw (JDOMException)(se.getException());
}
else {
throw new JDOMException(se.getMessage(), se);
}
}
}
else {
throw exception;
}
}
/**
* * Creates a SAX XMLReader. *
* * @returnXMLReader
a SAX2 parser.
*
* @throws Exception if no parser can be created.
*/
protected XMLReader createParser() throws Exception {
XMLReader parser = null;
// Try using JAXP...
// Note we need JAXP 1.1, and if JAXP 1.0 is all that's
// available then the getXMLReader call fails and we skip
// to the hard coded default parser
try {
Class factoryClass =
Class.forName("javax.xml.parsers.SAXParserFactory");
// MODIFIED: Added (Class[]) and (Object[]) cast sentences in "null" parameters
// to avoid warnings during compilation
// factory = SAXParserFactory.newInstance();
Method newParserInstance =
factoryClass.getMethod("newInstance", (Class[])null);
Object factory = newParserInstance.invoke(null, (Object[])null);
// jaxpParser = factory.newSAXParser();
Method newSAXParser = factoryClass.getMethod("newSAXParser", (Class[])null);
Object jaxpParser = newSAXParser.invoke(factory, (Object[])null);
// parser = jaxpParser.getXMLReader();
Class parserClass = jaxpParser.getClass();
Method getXMLReader =
parserClass.getMethod("getXMLReader", (Class[])null);
parser = (XMLReader)getXMLReader.invoke(jaxpParser, (Object[])null);
} catch (ClassNotFoundException e) {
//e.printStackTrace();
} catch (InvocationTargetException e) {
//e.printStackTrace();
} catch (NoSuchMethodException e) {
//e.printStackTrace();
} catch (IllegalAccessException e) {
//e.printStackTrace();
}
// Check to see if we got a parser yet, if not, try to use a
// hard coded default
if (parser == null) {
parser = XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser");
}
return parser;
}
/**
* * This will create a SAX XMLReader capable of parsing a DTD and * configure it so that the DTD parsing events are routed to the * handlers registered onto this SAXOutputter. *
* * @returnXMLReader
a SAX2 parser.
*
* @throws JDOMException if no parser can be created.
*/
private XMLReader createDTDParser() throws JDOMException {
XMLReader parser = null;
// Get a parser instance
try
{
parser = createParser();
}
catch (Exception ex1) {
throw new JDOMException("Error in SAX parser allocation", ex1);
}
// Register handlers
if (this.getDTDHandler() != null) {
parser.setDTDHandler(this.getDTDHandler());
}
if (this.getEntityResolver() != null) {
parser.setEntityResolver(this.getEntityResolver());
}
if (this.getLexicalHandler() != null) {
try {
parser.setProperty(LEXICAL_HANDLER_SAX_PROPERTY,
this.getLexicalHandler());
}
catch (SAXException ex1) {
try {
parser.setProperty(LEXICAL_HANDLER_ALT_PROPERTY,
this.getLexicalHandler());
} catch (SAXException ex2) {
// Forget it!
}
}
}
if (this.getDeclHandler() != null) {
try {
parser.setProperty(DECL_HANDLER_SAX_PROPERTY,
this.getDeclHandler());
}
catch (SAXException ex1) {
try {
parser.setProperty(DECL_HANDLER_ALT_PROPERTY,
this.getDeclHandler());
} catch (SAXException ex2) {
// Forget it!
}
}
}
// Absorb errors as much as possible, per Laurent
parser.setErrorHandler(new DefaultHandler());
return parser;
}
/**
* Returns a JDOMLocator object referencing the node currently
* being processed by this outputter. The returned object is a
* snapshot of the location information and can thus safely be
* memorized for later use.
*
* This method allows direct access to the location information
* maintained by SAXOutputter without requiring to implement
* XMLFilter
. (In SAX, locators are only available
* though the ContentHandler
interface).
* Note that location information is only available while
* SAXOutputter is outputting nodes. Hence this method should
* only be used by objects taking part in the output processing
* such as ErrorHandler
s.
*
* @return a JDOMLocator object referencing the node currently
* being processed or null
if no output
* operation is being performed.
*/
public JDOMLocator getLocator() {
return (locator != null)? new JDOMLocator(locator): null;
}
}