Package org.apache.commons.jelly.parser
Class XMLParser
java.lang.Object
org.xml.sax.helpers.DefaultHandler
org.apache.commons.jelly.parser.XMLParser
- All Implemented Interfaces:
ContentHandler,DTDHandler,EntityResolver,ErrorHandler
XMLParser parses the XML Jelly format.
The SAXParser and XMLReader portions of this code come from Digester.
- Version:
- $Revision: 219726 $
- Author:
- James Strachan
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected ClassLoaderThe class loader to use for instantiating application objects.protected ErrorHandlerThe application-supplied error handler that is notified when parsing warnings, errors, or fatal errors occur.protected static SAXParserFactoryThe SAXParserFactory that is created the first time we need it.protected LocatorThe Locator associated with our parser.protected MapRegistered namespaces we are currently processing.protected SAXParserThe SAXParser we will use to parse the input stream.protected XMLReaderThe XMLReader used to parse digester rules.protected booleanDo we want to use the Context ClassLoader when loading classes for instantiating new objects? Default isfalse.protected booleanDo we want to use a validating parser? -
Constructor Summary
ConstructorsConstructorDescriptionConstruct a new XMLParser with default properties.XMLParser(boolean allowDtdToCallExternalEntities) Construct a new XMLParser, with the boolean allowDtdToCallExternalEntities being passed in.Construct a new XMLParser, allowing a SAXParser to be passed in.Construct a new XMLParser, allowing an XMLReader to be passed in. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddExpressionScript(ScriptBlock script, Expression expression) Adds the given Expression object to the current Script.protected voidaddTextScript(String text, boolean start) Adds the text to the current script block parsing any embedded expressions into ExpressionScript objects.voidcharacters(char[] buffer, int start, int length) Process notification of character data received from the body of an XML element.protected voidThis method is called only once before parsing occurs which allows tag libraries to be registered and so forthprotected voidconfigureStaticTagAttributes(TagScript script, Attributes list) protected voidconfigureTagScript(TagScript aTagScript) Configure a newly created TagScript instance before any Expressions are createdprotected ExpressioncreateConstantExpression(String tagName, String attributeName, String attributeValue) protected ExpressioncreateEscapingExpression(Expression expression) protected ExpressionFactoryprotected SAXExceptionCreate a SAX exception which also understands about the location in the digester file where the exception occursprotected SAXExceptioncreateSAXException(String message) Create a SAX exception which also understands about the location in the digester file where the exception occursprotected SAXExceptioncreateSAXException(String message, Exception e) Create a SAX exception which also understands about the location in the file where the exception occursprotected TagScriptcreateStaticTag(String namespaceURI, String localName, String qName, Attributes list) Factory method to create a static Tag that represents some static content.protected TagScriptcreateTag(String namespaceURI, String localName, Attributes list) Factory method to create new Tag script for the given namespaceURI and name or return null if this is not a custom Tag.voidProcess notification of the end of the document being reached.voidendElement(String namespaceURI, String localName, String qName) Process notification of the end of an XML element being reached.voidendPrefixMapping(String prefix) Process notification that a namespace prefix is going out of scope.voiderror(SAXParseException exception) Forward notification of a parsing error to the application supplied error handler, if any, otherwise throw a SAXException with the error.voidfatalError(SAXParseException exception) Forward notification of a fatal parsing error to the application supplied error handler, if any, otherwise throw a SAXException with the error.findNamespaceURI(String prefix) Return the currently mapped namespace URI for the specified prefix, if any; otherwise returnnull.Return the class loader to be used for instantiating application objects when required.protected StringReturn the error handler for this XMLParser.protected PropertiesA helper method which loads the static Jelly properties once on startuporg.apache.commons.logging.LogReturn the current Logger associated with this instance of the XMLParserReturn the SAXParser we will use to parse the input stream.Deprecated.Use getXMLReader() instead, which can throw a SAXException if the reader cannot be instantiatedReturns the script that has just been created if this class is used as a SAX ContentHandler and passed into some XML processor or parser.booleanReturn the boolean as to whether the context classloader should be used.booleanReturn the validating parser flag.Return the XMLReader to be used for parsing the input document.voidignorableWhitespace(char[] buffer, int start, int len) Process notification of ignorable whitespace received from the body of an XML element.booleanGets the internal state for allowance for DTDs to call external resources.booleanvoidnotationDecl(String name, String publicId, String systemId) Receive notification of a notation declaration event.Parse the content of the specified file using this XMLParser.parse(InputStream input) Parse the content of the specified input stream using this XMLParser.Parse the content of the specified reader using this XMLParser.Parse the content of the specified URI using this XMLParser.Parse the content of the specified file using this XMLParser.parse(InputSource input) Parse the content of the specified input source using this XMLParser.voidprocessingInstruction(String target, String data) Process notification of a processing instruction that was encountered.voidsetAllowDtdToCallExternalEntities(boolean allowDtdToCallExternalEntities) Sets the boolean allowDtdToCallExternalEntities.voidsetClassLoader(ClassLoader classLoader) Set the class loader to be used for instantiating application objects when required.voidsetContext(JellyContext context) voidsetDefaultNamespaceURI(String namespace) Set the jelly namespace to use for unprefixed elements.voidsetDocumentLocator(Locator locator) Set the document locator associated with our parser.voidsetErrorHandler(ErrorHandler errorHandler) Set the error handler for this XMLParser.voidsetEscapeByDefault(boolean escapeByDefault) voidsetExpressionFactory(ExpressionFactory expressionFactory) Sets the expression factory used to evaluate tag attributesvoidsetLogger(org.apache.commons.logging.Log log) Set the current logger for this XMLParser.voidsetUseContextClassLoader(boolean use) Determine whether to use the Context ClassLoader (the one found by callingThread.currentThread().getContextClassLoader()) to resolve/load classes.voidsetValidating(boolean validating) Set the validating parser flag.voidskippedEntity(String name) Process notification of a skipped entity.voidProcess notification of the beginning of the document being reached.voidstartElement(String namespaceURI, String localName, String qName, Attributes list) Process notification of the start of an XML element being reached.voidstartPrefixMapping(String prefix, String namespaceURI) Process notification that a namespace prefix is coming in to scope.voidunparsedEntityDecl(String name, String publicId, String systemId, String notation) Receive notification of an unparsed entity declaration event.voidwarning(SAXParseException exception) Forward notification of a parse warning to the application supplied error handler (if any).Methods inherited from class org.xml.sax.helpers.DefaultHandler
error, fatalError, resolveEntity, warningMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.xml.sax.ContentHandler
declaration
-
Field Details
-
classLoader
The class loader to use for instantiating application objects. If not specified, the context class loader, or the class loader used to load XMLParser itself, is used, based on the value of theuseContextClassLoadervariable. -
useContextClassLoader
protected boolean useContextClassLoaderDo we want to use the Context ClassLoader when loading classes for instantiating new objects? Default isfalse. -
errorHandler
The application-supplied error handler that is notified when parsing warnings, errors, or fatal errors occur. -
factory
The SAXParserFactory that is created the first time we need it. -
parser
The SAXParser we will use to parse the input stream. -
reader
The XMLReader used to parse digester rules. -
locator
The Locator associated with our parser. -
namespaces
Registered namespaces we are currently processing. The key is the namespace prefix that was declared in the document. The value is an ArrayStack of the namespace URIs this prefix has been mapped to -- the top Stack element is the most current one. (This architecture is required because documents can declare nested uses of the same prefix for different Namespace URIs). -
validating
protected boolean validatingDo we want to use a validating parser?
-
-
Constructor Details
-
XMLParser
public XMLParser()Construct a new XMLParser with default properties. -
XMLParser
public XMLParser(boolean allowDtdToCallExternalEntities) Construct a new XMLParser, with the boolean allowDtdToCallExternalEntities being passed in. If this is set to false, the XMLParser will be created with: XMLReader spf = XMLReaderFactory.createXMLReader(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); as given by https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XMLReader -
XMLParser
Construct a new XMLParser, allowing a SAXParser to be passed in. This allows XMLParser to be used in environments which are unfriendly to JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to James House (james@interobjective.com). This may help in places where you are able to load JAXP 1.1 classes yourself. -
XMLParser
Construct a new XMLParser, allowing an XMLReader to be passed in. This allows XMLParser to be used in environments which are unfriendly to JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you have to configure namespace and validation support yourself, as these properties only affect the SAXParser and emtpy constructor.
-
-
Method Details
-
setEscapeByDefault
public void setEscapeByDefault(boolean escapeByDefault) -
isEscapeByDefault
public boolean isEscapeByDefault() -
parse
Parse the content of the specified file using this XMLParser. Returns the root element from the object stack (if any).- Parameters:
file- File containing the XML data to be parsed- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
parse
Parse the content of the specified file using this XMLParser. Returns the root element from the object stack (if any).- Parameters:
url- URL containing the XML data to be parsed- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
parse
Parse the content of the specified input source using this XMLParser. Returns the root element from the object stack (if any).- Parameters:
input- Input source containing the XML data to be parsed- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
parse
Parse the content of the specified input stream using this XMLParser. Returns the root element from the object stack (if any). (Note: if reading a File or URL, use one of the URL-based parse methods instead. This method will not be able to resolve any relative paths inside a DTD.)- Parameters:
input- Input stream containing the XML data to be parsed- Returns:
- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
parse
Parse the content of the specified reader using this XMLParser. Returns the root element from the object stack (if any). (Note: if reading a File or URL, use one of the URL-based parse methods instead. This method will not be able to resolve any relative paths inside a DTD.)- Parameters:
reader- Reader containing the XML data to be parsed- Returns:
- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
parse
Parse the content of the specified URI using this XMLParser. Returns the root element from the object stack (if any).- Parameters:
uri- URI containing the XML data to be parsed- Throws:
IOException- if an input/output error occursSAXException- if a parsing exception occurs
-
findNamespaceURI
Return the currently mapped namespace URI for the specified prefix, if any; otherwise returnnull. These mappings come and go dynamically as the document is parsed.- Parameters:
prefix- Prefix to look up
-
getContext
-
setContext
-
setDefaultNamespaceURI
Set the jelly namespace to use for unprefixed elements. Will be overridden by an explicit namespace in the XML document.- Parameters:
namespace- jelly namespace to use (e.g. 'jelly:core')
-
getClassLoader
Return the class loader to be used for instantiating application objects when required. This is determined based upon the following rules:- The class loader set by
setClassLoader(), if any - The thread context class loader, if it exists and the
useContextClassLoaderproperty is set to true - The class loader used to load the XMLParser class itself.
- The class loader set by
-
setClassLoader
Set the class loader to be used for instantiating application objects when required.- Parameters:
classLoader- The new class loader to use, ornullto revert to the standard rules
-
getUseContextClassLoader
public boolean getUseContextClassLoader()Return the boolean as to whether the context classloader should be used. -
setUseContextClassLoader
public void setUseContextClassLoader(boolean use) Determine whether to use the Context ClassLoader (the one found by callingThread.currentThread().getContextClassLoader()) to resolve/load classes. If not using Context ClassLoader, then the class-loading defaults to using the calling-class' ClassLoader.- Parameters:
use- determines whether to use JellyContext ClassLoader.
-
getErrorHandler
Return the error handler for this XMLParser. -
setErrorHandler
Set the error handler for this XMLParser.- Parameters:
errorHandler- The new error handler
-
getLogger
public org.apache.commons.logging.Log getLogger()Return the current Logger associated with this instance of the XMLParser -
setLogger
public void setLogger(org.apache.commons.logging.Log log) Set the current logger for this XMLParser. -
getExpressionFactory
- Returns:
- the expression factory used to evaluate tag attributes
-
setExpressionFactory
Sets the expression factory used to evaluate tag attributes -
getParser
Return the SAXParser we will use to parse the input stream. If there is a problem creating the parser, returnnull. -
getReader
Deprecated.Use getXMLReader() instead, which can throw a SAXException if the reader cannot be instantiatedBy setting the reader in the constructor, you can bypass JAXP and be able to use digester in Weblogic 6.0. -
getXMLReader
Return the XMLReader to be used for parsing the input document.- Throws:
SAXException- if no XMLReader can be instantiated
-
getValidating
public boolean getValidating()Return the validating parser flag. -
setValidating
public void setValidating(boolean validating) Set the validating parser flag. This must be called beforeparse()is called the first time.- Parameters:
validating- The new validating parser flag.
-
getScript
Returns the script that has just been created if this class is used as a SAX ContentHandler and passed into some XML processor or parser.- Returns:
- the ScriptBlock created if SAX events are piped into this class, which must include a startDocument() and endDocument()
-
startDocument
Process notification of the beginning of the document being reached.- Specified by:
startDocumentin interfaceContentHandler- Overrides:
startDocumentin classDefaultHandler- Throws:
SAXException- if a parsing error is to be reported
-
endDocument
Process notification of the end of the document being reached.- Specified by:
endDocumentin interfaceContentHandler- Overrides:
endDocumentin classDefaultHandler- Throws:
SAXException- if a parsing error is to be reported
-
isAllowDtdToCallExternalEntities
public boolean isAllowDtdToCallExternalEntities()Gets the internal state for allowance for DTDs to call external resources.- Returns:
- true if we are allowed to make external calls to entities during XML parsing by custom declared resources in the DTD.
-
setAllowDtdToCallExternalEntities
public void setAllowDtdToCallExternalEntities(boolean allowDtdToCallExternalEntities) Sets the boolean allowDtdToCallExternalEntities. If this is set to false, the XMLParser will be created with: XMLReader spf = XMLReaderFactory.createXMLReader(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); as given by https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XMLReader -
startElement
public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException Process notification of the start of an XML element being reached.- Specified by:
startElementin interfaceContentHandler- Overrides:
startElementin classDefaultHandler- Parameters:
namespaceURI- The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.localName- The local name (without prefix), or the empty string if Namespace processing is not being performed.qName- The qualified name (with prefix), or the empty string if qualified names are not available.\list- The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.- Throws:
SAXException- if a parsing error is to be reported
-
characters
Process notification of character data received from the body of an XML element.- Specified by:
charactersin interfaceContentHandler- Overrides:
charactersin classDefaultHandler- Parameters:
buffer- The characters from the XML documentstart- Starting offset into the bufferlength- Number of characters from the buffer- Throws:
SAXException- if a parsing error is to be reported
-
endElement
Process notification of the end of an XML element being reached.- Specified by:
endElementin interfaceContentHandler- Overrides:
endElementin classDefaultHandler- Parameters:
namespaceURI- The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.localName- The local name (without prefix), or the empty string if Namespace processing is not being performed.qName- The qualified XML 1.0 name (with prefix), or the empty string if qualified names are not available.- Throws:
SAXException- if a parsing error is to be reported
-
startPrefixMapping
Process notification that a namespace prefix is coming in to scope.- Specified by:
startPrefixMappingin interfaceContentHandler- Overrides:
startPrefixMappingin classDefaultHandler- Parameters:
prefix- Prefix that is being declarednamespaceURI- Corresponding namespace URI being mapped to- Throws:
SAXException- if a parsing error is to be reported
-
endPrefixMapping
Process notification that a namespace prefix is going out of scope.- Specified by:
endPrefixMappingin interfaceContentHandler- Overrides:
endPrefixMappingin classDefaultHandler- Parameters:
prefix- Prefix that is going out of scope- Throws:
SAXException- if a parsing error is to be reported
-
ignorableWhitespace
Process notification of ignorable whitespace received from the body of an XML element.- Specified by:
ignorableWhitespacein interfaceContentHandler- Overrides:
ignorableWhitespacein classDefaultHandler- Parameters:
buffer- The characters from the XML documentstart- Starting offset into the bufferlen- Number of characters from the buffer- Throws:
SAXException- if a parsing error is to be reported
-
processingInstruction
Process notification of a processing instruction that was encountered.- Specified by:
processingInstructionin interfaceContentHandler- Overrides:
processingInstructionin classDefaultHandler- Parameters:
target- The processing instruction targetdata- The processing instruction data (if any)- Throws:
SAXException- if a parsing error is to be reported
-
setDocumentLocator
Set the document locator associated with our parser.- Specified by:
setDocumentLocatorin interfaceContentHandler- Overrides:
setDocumentLocatorin classDefaultHandler- Parameters:
locator- The new locator
-
skippedEntity
Process notification of a skipped entity.- Specified by:
skippedEntityin interfaceContentHandler- Overrides:
skippedEntityin classDefaultHandler- Parameters:
name- Name of the skipped entity- Throws:
SAXException- if a parsing error is to be reported
-
notationDecl
Receive notification of a notation declaration event.- Specified by:
notationDeclin interfaceDTDHandler- Overrides:
notationDeclin classDefaultHandler- Parameters:
name- The notation namepublicId- The public identifier (if any)systemId- The system identifier (if any)
-
unparsedEntityDecl
Receive notification of an unparsed entity declaration event.- Specified by:
unparsedEntityDeclin interfaceDTDHandler- Overrides:
unparsedEntityDeclin classDefaultHandler- Parameters:
name- The unparsed entity namepublicId- The public identifier (if any)systemId- The system identifier (if any)notation- The name of the associated notation
-
error
Forward notification of a parsing error to the application supplied error handler, if any, otherwise throw a SAXException with the error.- Parameters:
exception- The error information- Throws:
SAXException- if a parsing exception occurs
-
fatalError
Forward notification of a fatal parsing error to the application supplied error handler, if any, otherwise throw a SAXException with the error.- Parameters:
exception- The fatal error information- Throws:
SAXException- if a parsing exception occurs
-
warning
Forward notification of a parse warning to the application supplied error handler (if any). Unlike XMLParser.error(SAXParseException) and XMLParser.fatalError(SAXParseException), this implementation will NOT throw a SAXException by default if no error handler is supplied.- Parameters:
exception- The warning information- Throws:
SAXException- if a parsing exception occurs
-
configure
protected void configure()This method is called only once before parsing occurs which allows tag libraries to be registered and so forth -
getJellyProperties
A helper method which loads the static Jelly properties once on startup -
createTag
protected TagScript createTag(String namespaceURI, String localName, Attributes list) throws SAXException Factory method to create new Tag script for the given namespaceURI and name or return null if this is not a custom Tag.- Throws:
SAXException
-
createStaticTag
protected TagScript createStaticTag(String namespaceURI, String localName, String qName, Attributes list) throws SAXException Factory method to create a static Tag that represents some static content.Note that to if you use jelly:define taglib, these tags might turn out to be non-static during the runtime.
- Throws:
SAXException
-
configureStaticTagAttributes
protected void configureStaticTagAttributes(TagScript script, Attributes list) throws JellyException - Throws:
JellyException
-
configureTagScript
Configure a newly created TagScript instance before any Expressions are created- Parameters:
aTagScript-
-
addTextScript
Adds the text to the current script block parsing any embedded expressions into ExpressionScript objects.- Parameters:
start- If the text precedes a start element. Otherwise the text precedes an end element.- Throws:
JellyException
-
addExpressionScript
Adds the given Expression object to the current Script. -
createEscapingExpression
-
createConstantExpression
protected Expression createConstantExpression(String tagName, String attributeName, String attributeValue) -
createExpressionFactory
-
getCurrentURI
- Returns:
- the current context URI as a String or null if there is no current context defined on the JellyContext
-
createSAXException
Create a SAX exception which also understands about the location in the file where the exception occurs- Returns:
- the new exception
-
createSAXException
Create a SAX exception which also understands about the location in the digester file where the exception occurs- Returns:
- the new exception
-
createSAXException
Create a SAX exception which also understands about the location in the digester file where the exception occurs- Returns:
- the new exception
-